Save data from GET request as variable - javascript

I've got a simple axios GET request that is working with Azure directline 3.0. The GET request pulls back data and shows it in the console (as seen in the picture).
The data I want to save into a variable is the conversationId. I then want to use this variable with Axios Post in another JS file to post as part of the link e.g. let URL = "https://directline.botframework.com/v3/directline/conversations/"+convID"/activities". With convID being the variable I wish to create. Right now I am manually changing the convID with the new conversation ID, but I want to create a variable so I can place it in the post javascript file so it is automatic.enter image description here

There are various ways you can solve this problem. Easiest one being, exposing the data on a shared object window.convID = convID and then accessing it wherever required.
You could also look to make singleton objects, which can be instantiated only once and hence will share it's variables across the lifespan of the application.
axios.get(/* URL */).then(res => {
window.convID = res.data.conversationId;
});

You can save that variable value in LocalStorage. Something like this:
let routeToYourApi = '/api/conversations'; // or something like this...
axios.get(routeToYourApi).then((response) => {
let conversationId = response.data.conversationId; // not sure if data object from your image is directly nested inside response that you get from server, but you get the idea...
window.localStorage.setItem("convId", conversationId);
}) // here you can fetch your conversation id
Than you can access it anywhere in your app:
let conversationId = window.localStorage.getItem("convId");
... and eventually remove it from local storage:
window.localStorage.removeItem("convId")
Hope this will help you!

Related

Unable to display information from fetched serialized api in react component

I am developing a web app that fetches concerts from an api based on a user search. However, since I want to add, and save, attributes from different users to those concerts, I decided that when a user clicks a link for an individual concert it a) gets saved to the database, and then b) renders the individual card component for that concert. However, the data rendered in the individual card is not the data from the external api, but data fetched from my own db, as to populate the extra attributes that my users have entered. That already has been a pain in and of itself. Now- here's the issue: For some reason whenever I try and display data from my redux state that's two levels deep, let's say like concerts.attributes.venue, I get a TypeError: Cannot read property 'venue' of undefined. This happens for any nested properties I have. For more context, I am using hooks to fetch the data from my db in my functional concert component. I also tried turning it into a class component with lifecycle methods, but same issue. Part of of me thinks it is the asynchronous nature of fetching, with data rendering before the entire serialized data comes back? I am not sure. Anybody know how to rectify this?
Share the code snippet for better understanding. its a bit difficult to just visualize the code by just your words.
you will get a some data as a response from the Api. You need to store that data to some variable. somewhat like this
XHR call in JS and storing response to var x
let x;
function successListener() {
var data = JSON.parse(this.responseText); //to parse the data to json format
x=data;
}
function failureListener(err) {
console.log('Request failed', err);
}
var request = new XMLHttpRequest();
request.onload = successListener;
request.onerror = failureListener;
request.open('get', 'URL', true);
request.send();
then access the data you need like this:
x[key][subkey]
don't know what you are doing here
concerts.attributes.venue

Requesting 2 secrets from AWS Secrets Manager in One API Call with JavaScript

Background
I am using AWS Secrets Manager to store a few different passwords and secret values in AWS. The first entry is specifically for AWS RDS information.
To enter arbitrary secret data in Secrets Manager you must select a different entry than RDS.
I did this and then created a few key value pairs to be stored. Now that I have done this I have 2 sets of SecretIds. The SecretIds is what is used to return the correct secret from Secrets Manager. I have 2 different SecretIds and need to return 2 different sets of secrets. I am hoping I can do this without having to make 2 separate API calls.
Example
Originally this was the secretId for returning the RDS username and password.
const secretRds = 'some/thing/something';
I was able to return this data like this,
client.getSecretValue({ SecretId: secretRds }, {...}
Question
Now that I have a second secretId I have 2 sets that look like this,
const secretRds = 'some/thing/something';
const secretConfigs = 'some/thing/sopmethingElse';
Since the original secretId was passed into the SecretId key as the value in the getSecretValue params, how do I pass a second secretId in?
Looking at the documentation here, I can not seem to find anything explaining this.
Something like this is what I am trying to accomplish,
Obviously this wont work because the key is named twice.
I need to understand how to pass 2 secretIds in to the same secretId.
const secretRds = 'some/thing/something';
const secretConfigs = 'some/thing/sopmethingElse';
client.getSecretValue({ SecretId: secretRds: SecretId: secretConfigs }, {...}
Unfortunately, the Secrets Manager API does not support passing multiple SecretId's in a single GetSecretValue call.
There does not seem to be any way to retrieve more than 1 secret value in a single API call. You will have to issue 2 different API calls to GetSecretValue.
What are these values you are storing? If they are related, like the DB username, password, and connection string, you can just store them all in the same JSON blob in the secret. You could go back to the console and edit the secret to combine everything.
If they are not all related, you probably want to keep them in separate secrets so that you can manage the permissions to them separately.

Express with JSON Data Control

I use lowDB dependency to control the JSON Data with Express and actually it works. But there is a bug and I cannot find how to solve it.
I create /create page to add information in JSON file and it contains 4 form and submit button.
And In express I code like this. each forms data will save it in variable and push with lowdb module.
router.post('/post', function (req, res) {
let pjName = req.body.projectName;
let pjURL = req.body.projectURL;
let pjtExplanation = req.body.projectExplanation;
let pjImgURL = req.body.projectImgURL;
console.log(pjName);
db.get('project').push({
name: pjName,
url: pjURL,
explanation: pjtExplanation,
imgurl: pjImgURL
}).write();
console.log(db.get('project'));
console.log(db.get('project').value());
res.redirect('/');
})
And it works well. But when I modify the JSON file myself (ex. reset the JSON file) and execute again. It shows the data that I reset before. I think in this app somewhere saves the all data and show save it in array again.
And When I shutdown the app in CMD and execute again, the Array is initialized.
As you may already know the lowdb persist the data into your secondary memory (hdd), and may return a promise depending on your environment when you call write method.As mentioned in the doc
Persists database using adapter.write (depending on the adapter, may return a promise).
So the data may be still getting write when you read them, so the old data is queried. Try this,
db.get('project').push({
name: pjName,
url: pjURL,
explanation: pjtExplanation,
imgurl: pjImgURL
}).write().then(() => {
console.log(db.get('project'));
console.log(db.get('project').value());
});

Need helping retrieving data from Firebase

So I've been using Firebase as a database for my website (this is a web based project, using HTML, CSS and JS) and I'm running into a problem retrieving data from it.
Basically this site allows users to create a profile for a character (they can fill in the name, the characters stats etc...) and when they click submit, it'll save the values they filled out to the database.
The values are saved perfectly fine, but when I go to retrieve the data the command doesn't seem to do anything.
So in order to get the profiles, I've been trying to use this bit of code to get whatever is stored at the specified .ref(path):
var uid = firebase.auth().currentUser.uid;
var getChar = firebase.database().ref('/users/' + uid + '/chars/').orderByKey();
Which according to the Firebase docs should return a list of keys at the path that I specified in .ref(). However whenever I try to access whatever is in the var, it just gives me the string that contains a link to the database that looks like this:
https://#mydatabaseurlhere.firebaseio.com/users/uid/chars
Where #mydatabaseurlhere is the url I created on the Firebase app, and the uid is the authenticated user's ID.
I've been reading the docs, and its telling me that the above code should return a list of whatever is at the path that I specified, but so far it just gives me a link. Is there something I've been missing from the Docs that'll allow me to access whatever data is currently in the database? Because I've tried to take a snapshot using .once() to no avail either. I've also set the rules on /users/ to allow anyone to read/write to the database but I'm still not able to access the data (or maybe I am accessing, I'm just missing how to retrieve it).
Either way, I'm wondering how one can go about accessing this data, as I'm extremely confused as to why I can't seem to retrieve the data that has been successfully written to the database.
You're defining a query. But that doesn't yet retrieve the data.
To retrieve the data, you need to attach a listener. For example:
var uid = firebase.auth().currentUser.uid;
var getChar = firebase.database().ref('/users/' + uid + '/chars/').orderByKey();
getChar.on('value', function(snapshot) {
snapshot.forEach(function(child) {
console.log(child.key, child.val());
});
});

Why is node.js variable persisting

I'm making a temporary fake API and am trying to set up a simple request response script in node using express.js to achieve this. It's very strraightforward, A request comes in, is validated and, if valid, is merged with a .json template file and the result returned, thus giving the impression the user was successfully created.
app.post('/agent/user', function(req, res){
var responseTemplate = new jsonRequired('post_user');
var errorTemplate = new jsonRequired('post_user_error');
var payload = req.body;
var responseData;
var hasErrors = false;
console.log('Creating new user');
//Recursive Merge from http://stackoverflow.com/a/383245/284695
responseData = new mergeRecursive(responseTemplate,payload);
if(!payload.username){
hasErrors = true;
errorTemplate.errors.username.push('A username is required.');
}
if (hasErrors){
res.send(errorTemplate,422);
}else{
res.send(responseData,200);
}
});
The problem I'm having is that data is persisting between calls. So if I define a username and name[first] in 1 request and just a username in the 2nd one, both requests come back with the name[first] property.
I have a feeling it's something to do with js closures. Unfortunately, every tutorial I find seems to be about making closures, not avoiding them.
It should work like this:
The client POST's username=user1&name[first]=joe&name[last]=bloggs
The Server loads a json file containing a prepopulated user object: e.g.
{"username":"demo","name":{"first":"John","last":"Doe"}...}
mergeRecursive() merges the payload from the POST request over the template object and returns the new object as the POST response text.
The problem is that with every new request, the server is using the result of step 3 in step 2 instead of reloading the .json file.
That mergeRecursive function has the same caveat as jQuery.extend: it modifies the first object sent into it. In fact, you don't even need to use its return value.
You didn't show the code of jsonRequired function (it's not even clear why you've used new when invoking it), but it looks like this function doesn't create a new object each time it's called, instead fetching this object from some outer repository. Obviously, mergeRecursive modifications for it won't be lost after that function ends.
The solution is using your data object for merging. Like this:
var responseData = {};
...
mergeRecursive(responseData, responseTemplate);
mergeRecursive(responseData, payload);
Merging two objects will make this for you.
If your responseTemplate has parameter, which actual request did not have, then you will end up having it there.
Check definition of word merge ;)
While this doesn't resolve the issue I had, I have found a workaround using the cloneextend package available via npm:
$ npm install cloneextend
This allows me to use the following js:
var ce = require('cloneextend');
...
ce.extend(responseData, responseTemplate);
ce.extend(responseData, payload);

Categories