In node.js how to extract uid from returned facebook providerData json array? - javascript

I've got my users signing in with facebook and that gets stored in firebase auth. In index.js i've got an onCreate function that stores some facebook related data in firestore.
When i log to cloud functions console event.data.providerData I get this:
[ { displayName: 'xxxx xxxxx',
photoURL: 'https://scontent.xx.fbcdn.net/v/t1.0-1/p100x100/xxxxxxxxx_439xxx336xxxxxx.jpg?oh=bcxxxxxxxxxxx431ce&oe=xxxx4xxx3',
providerId: 'facebook.com',
uid: 'xxxxx725xxxxxx80' } ]
In my index.js file i've set this as
const providerData = event.data.providerData;
This always confuses me and i've read about it a lot.
These are my questions:
Is this a javascript object? Or a JSON object? Or a JSON array?
Does this need to be parsed? eg. JSON.parse(event.data.providerData)? What is JSON.parse actually doing?
To get access to the uid I have tried:
providerData[3]
providerData.uid
providerData["uid"]
providerData['uid']
JSON.parse(providerData) - and then all the above again
var obj = JSON.parse(providerData);
console.log( obj.uid );
I know there are plenty of posts out there re: similar topics and I think i've read a lot of them.
Thanks.

It's an array containing a JSON object at index 0.
The javascript interpreter is automatically parsing Valid JSON as a Javascript object.
Knowing that, you can now access directly the properties of your object like this:
providerData[0].displayName
providerData[0].photoURL
providerData[0].providerId
providerData[0].uid // <-- Your use case

Related

How to access a json object in javascript files from a model passed to the view

I have a JSON object in my database that contains html inside it. I pass the object as part of a model to my view. I need to access the object and read it in the javascript files for the page. However when i try and assign the object to a global variable in my html file i cannot access it in my javascript file.
I tried reading the object as a string it returns decoded html (
"page-1":) which i cant do anything with. If i call #Html.Raw(#Model.CourseContent.ExpectedResult) it created the JSON object as expected. However in my javascript file it is listed as undefined. I have no idea how to solve this.
#model DataTransferObjects.Models.UserCourseAndContent
<script>
var totalPages = '#Model.CourseContent.TotalPages';
var expectedResults = #HTML.Raw(#Model.CourseContent.ExpectedResult)
</script>
The json object that comes out when i use the above code looks like
var expectedResults = {
"page-1": "<head></head><body></body>",
"page-3": "<head></head><body><h1>My Cool News Article</h1><p>Welcome
to my news article, you’ll find some cool news here.</p>
<Our most recent
news</<p>Below you’ll find my most recent news!</p></body>"
};
I expected it to be an actual json string but instead ive got an object (?) i am confused as to how to decode the html out of it then turn the resulting json obejct into a json string to be read in the javascript file.
Any help would be great!
var expectedResults = {
"page-1": "<head></head><body></body>",
"page-3": "<head></head><body><h1>My Cool News Article</h1><p>Welcome
to my news article, you’ll find some cool news here.</p>
<Our most recent
news</<p>Below you’ll find my most recent news!</p></body>"
};
// Parse JSON
const parsedJSON = JSON.parse(JSON.stringify(expectedResults));
// Access to properties
const page-1 = parsedJSON['page-1'];
const page-3 = parsedJSON['page-3'];

Save/Load Variables in js

I'm trying to create a save/load function for my game in js, but I have basically no idea with how to go through with doing this. I can save variables to a JSON file or LocalStorage, but I don't know how to load them back into the program. I'm also pretty sure I'm exporting variables the wrong way as well. Any help?
Normally, I use JSON format to store and read data (of any type).
To save data (using key gamedata as example):
var myData = {
name: 'David',
score: 10
}
localStorage.setItem('gamedata', JSON.stringify(myData));
** without JSON.stringify, you data will be saved as string [Object object]
To retrieve the data back:
var savedData = localStorage.getItem('gamedata'); // savedData is string
var myData = JSON.parse(savedData); // parse JSON string to java object
setup a bin on www.myJSON.com. p5 has built in functionality for ajax requests such as loadJSON. that way it's not in local storage and you can access your data if you have it on github. I know your struggle, I used to deal with this sort of issue myself before I found myJSON

Firebase pushing array - Javascript

I am using Firebase to store information for a workout application.
I user adds a workout name and then I push it to the database. I can continue pushing these but my issue is that it does not seem to be pushing as an array just an object. See the screen shots below...
As you can see in the console log picture the workouts property is an object not an array like I expect.
The code I'm using to push it:
let newWorkout = {
title: 'title',
exercises: [{
name: 'pulldownsnsn',
sets: 4
}]}
let ref = firebase.database().ref("/userProfile/"+this.userId);
ref.child("workouts").push(newWorkout);
The Firebase Database stores lists of data in a different format, to cater for the multi-user and offline aspects of modern web. The -K... are called push IDs and are the expected behavior when you call push() on a database reference.
See this blog post on how Firebase handles arrays, this blog post on the format of those keys, and the Firebase documentation on adding data to lists.
Arrays are handy, but they are a distributed database nightmare for one simple reason: index element identification is not reliable when elements get pushed or deleted. Firebase database instead uses keys for element identification:
// javascript object
['hello', 'world']
// database object
{ -PKQdFz22Yu: 'hello', -VxzzHd1Umr: 'world' }
It gets tricky when using push(), because it does not actually behaves like a normal push, but rather as a key generation followed by object modification.
Example usage
firebase.database().ref('/uri/to/list').push(
newElement,
err => console.log(err ? 'error while pushing' : 'successful push')
)
Heres an example from firebase documentation:
const admin = require('firebase-admin');
// ...
const washingtonRef = db.collection('cities').doc('DC');
// Atomically add a new region to the "regions" array field.
const unionRes = await washingtonRef.update({
regions: admin.firestore.FieldValue.arrayUnion('greater_virginia')
});
// Atomically remove a region from the "regions" array field.
const removeRes = await washingtonRef.update({
regions: admin.firestore.FieldValue.arrayRemove('east_coast')
});
More info on this firebase documentation.

How to correctly parse the JSON?

I have developed a Cordova android plugin for my library. The library is used for sending events across different connected devices.
JS interface receives a JSON from the java side. What I want to do is to parse this before reaching the application so that the developer can directly use it as a JS object. When I tried to parse the JSON in my plugin's JS interface, I am running into issues. Below is an example:
Received by JS interface:
{"key":"name","data":"{\"name\":\"neil\",\"age\":2,\"address\":\"2 Hill St\"}"}
After parsing in JS interface:
Object {key: "name", data: "{"name":"neil","age":2,"address":"2 Hill St"}"}
data:"{"name":"neil","age":2,"address":"2 Hill St"}"
key:"name"
__proto__:Object
As you can see, if this data reaches the app and the developer accesses the data:
eventData.key = name;
eventData.data = {"name":"neil","age":2,"address":"2 Hill St"};
eventData.data.name = undefined
How can I parse the inner data as well in my JS interface so that the developer can access directly. In the above case, he has to parse eventData.data to access the properties. I don't want this to happen and I want to do this in JS interface itself.
Please note that eventData can have many properties and hence they should be properly parsed before passing into the app.
I am new to Javascript and hence finding it difficult to understand the problem.
It seems that your returned JSON contains a string for the data property.
var response = {"key":"name","data":"{\"name\":\"neil\",\"age\":2,\"address\":\"2 Hill St\"}"};
//Parse the data
var jsonData = JSON.parse(response.data);
console.log(jsonData.name); //neil
console.log(jsonData.age); //2
console.log(jsonData.address);//"2 Hill St"
As others pointed out, you have to do JSON.parse(eventData.data) as the data comes as a string.
You have to look why that happens. The inner data might be stored in this way, in some cases its valid to store it in db as flat object or it is stringified twice by mistake:
var innerdata = JSON.stringify({ name: "neil" });
var eventData = JSON.stringify({ key: "name", data: innerdata });
would correspond to your received string.
Correct way to stringify in first place would be:
var innerdata = { name: "neil" };
var eventData = JSON.stringify({ key: "name", data: innerdata });

Is it possible to retrieve a record from parse.com without knowing the objectId

See the sample code below - in this case, the objectId for the record I am trying to retrieve is known.
My question is, if I don't know the Parse.com objectId, how would I implement the code below?
var Artwork = Parse.Object.extend("Artwork");
var query = new Parse.Query(Artwork);
query.get(objectId, {
success: function(artwork) {
// The object was retrieved successfully.
// do something with it
},
error: function(object, error) {
// The object was not retrieved successfully.
// warn the user
}
});
Query.get() is used when you already know the Parse object id.
Otherwise, one can use query.find() to get objects based on the query parameters.
Sure, you can use Parse Query to search for objects based on their properties.
The thing that wasn't clear to me in the documentation is that once you get the object in the query, you would need to do:
With Query (can return multiple objects):
artwork[0].get('someField');
With 'first' or 'get':
artwork.get('someField');
You cannot do something like artwork.someField like I assumed you would

Categories

Resources