Get user from parse in Javascript - javascript

I know this question may be asked multiple times but I am not able to get the User object in its entirity. The problem is that the user object returns only the username, email and the phone number properties while I have certain fields added like first name and last name to the user object.
I'd like to know if there's a way to get the user object in its entirity
The object on parse cloud should look like
User:
{
"firstname": "firstname",
"lastname": "lastname",
"username": "username",
"email": "abc.xyz#jkl.pqr",
"phone": "0123456789",
"type": "admin/super-admin/user"
}
I use following query to get the object
var query = new Parse.Query(Parse.User);
query.equalTo("username", "username"); // Whatever be the username passed by search string
query.find({
success: function (user) {
console.log("Success:", user)
},
error: function (error) {
//Show if no user was found to match
}
});
I get the user object as follows:
user:{
createdAt:"2014-12-27T07:16:09.826Z"
email: "abc.xyz#pqr.mno"
objectId: "223tch5S6J"
phone: "0123456789"
updatedAt: "2014-12-27T07:16:09.826Z"
username: "username"
}
I do not get the other properties like type, firstname, lastname.
Note: I do not need to get the password which parse does not provide anyways so that's not the problem here.

user.attributes should hold all the user attributes saved server side

Related

DynamoDB search object with queries filter

{
"INFO": {
"email": "test#example.com",
"password": "123"
},
"PK": "3a95eab0-57de-4e15-90ea-004082e53384",
"SK": "user"
}
Above is my dataset in dynamoDB. I am building login api with expressjs with dynamodb. I am able to scan and update data with PK & SK keys but i want to query inside my INFO set.
I am trying like this:
var params = {
TableName: "table",
FilterExpression: "contains (INFO, :sendToVal)",
ExpressionAttributeValues: {
":sendToVal": {
email: "test#example.com",
password: "123",
},
},
};
But its returning:
{ error: 'Error retrieving Event' }
{ error: 'Event not found' }
Anyone help guide me, how can i retrive the set.
The DynamoDB documentation explains that the contains() function in an expression only works for strings or sets. This isn't completely accurate - it also works for lists. But in any case, it doesn't work for maps, which is what your INFO is, so the comparison doesn't match anything.
If you intended for INFO to be a list, not a map, please make it so. Otherwise, if you really intended for it to be a map, and you wanted to test whether { email: "test#example.com", password: "123" } is in that map, then what you really need to check is whether the email and password entries in this map is equal to the desired value. So the filter condition can be something like INFO.email = :email AND INFO.password = :password. Or something like this (I'm not sure I understannd what your intention was here).

Nested queries with graphql schema language

I have the following in my buildSchema:
type User {
id: ID
firstname: String
age : Int
company : Company
}
type Company {
id: ID
name: String
description : String
}
type RootQuery {
user(id: ID): User
}
When making this request:
user(id:"1"){
firstname,
company{
id,
name
}
}
company is returning a null value:
{
"data": {
"user": {
"firstname": "Jhoni",
"company": null
}
}
}
How can I get the company value?
The problem here will be to do with what data is coming into your query. The execution itself is successful, but you are not getting the company data for some reason.
To debug this, I would look at what data is actually returned in your resolver for the user query by the request. It could be the reference ID parameter is not linking to any results in where you store company details.
I guess one other possibility is that you may have may not pass back the company data into a parameter named 'company', again, looking at the object that is returned to the resolver for 'user' before it is returned by the function should give you an idea of what's not matching up.

JS library to check if extra data field returned in http response payload?

I’m currently working on building end-to-end testing for an API another team is working on, and I was wondering if anyone perhaps knows about a JS library that I could use to test whether an extra field is returned in HTTP response body? The purpose of this functionality would be to keep the QA team informed when the dev team makes changes to the api via the tests, instead of the developers manually having to let us know they’ve created updates. I know this can be implemented manually but if the wheel already exists, I’d prefer to avoid recreating it lol.
Example scenario:
API call: GET user
- returns : user name, user ID and user birthday.
With proposed functionality, if the dev team made updates to the Get user call, and it returns the following
- return : user name, user ID, user birthday AND user address.
A test would fail to let me know that an extra field that wasn't expected (user address) was returned.
Schema validation seems to be what you are looking for. Besides the library mentioned in another answer, you may also want check a similar one: joi
const Joi = require('joi');
const schema = Joi.object().keys({
userName: Joi.string().alphanum().required(),
userId: Joi.number().required(),
userBirthDay: Joi.number().required(),
})
const result = Joi.validate({
userName: 'johndoe',
userId: 1234567,
userBirthDay: 1970,
userAddress: 'John Doe St.'
}, schema);
if (result.error) {
console.log(result.error.details);
}
In the spec you can make assertion on existence of error key in result object using the assertion library of your choice.
The example above assumes that you are using nodejs as an environment to run tests, but browser version of joi also exists: joi-browser
You need schema validation, there are libraries out there like ajv.
var ajv = new Ajv({ allErrors: true }); // options can be passed, e.g. {allErrors: true}
// API call: GET user - returns : user name, user ID and user birthday.
// With proposed functionality, if the dev team made updates to the Get user call, and it returns the following - return : user name, user ID, user birthday AND user address.
var schema = {
type: "object",
properties: {
userName: {
type: "string",
},
userId: {
type: "string",
},
userBirthdate: {
type: "string",
},
},
required: ["userName", "userId", "userBirthdate"],
additionalProperties: false,
};
var validate = ajv.compile(schema);
var validUser = {
userName: "John",
userId: "john",
userBirthdate: "01012000",
};
var invalidUser = {
userName: "John",
userId: "john",
userBirthdate: "01012000",
userAddress: "World",
};
var valid = validate(validUser);
console.log(`Valid user is valid: ${valid}`);
valid = validate(invalidUser);
console.log(`Invalid user is valid: ${valid}`);
console.log('Validate errors:', validate.errors);
<script src="https://cdnjs.cloudflare.com/ajax/libs/ajv/6.6.2/ajv.min.js"></script>

Accessing a sub-document ID after save - mongoose

When a user is created on my app their details are saved on the MongoDB using mongoose. The user schema contains sub-documents and I am trying to access the _id if the sub-document after using the user.save function.
The schema is below:
{
name: String,
email: String,
address: String,
phone:[
{landLine: Number,
mobile: Number}
]
}
I can access the name, email and address easily like so:
console.log(user.name + user.email + user.address)
I tried user.phone._id but it returns undefined. I think because phone is an array of objects.
user.save(function(err) {
if (err)
throw err;
else {
console.log("user ID " + user._id); // SUCCESS!!
console.log("user sub-document ID " + user.phone._id); // UNDEFINED!!
return (null, user);
}
});
How can I access the _id of the sub-document inside the save function right after the user is created and saved into mongoDB?
There are a couple of approaches to getting this information, but personally I prefer the "atomic" modification method using $push.
The actual implementation here is helped by mongoose automatically including an ObjectId value which is "monotonic" and therefore always increasing in value. So this means that my method for handling this even works with a $sort modifier applied to the $push.
For example:
// Array of objects to add
var newNumbers = [
{ "landline": 55555555, "mobile": 999999999 },
{ "landline": 44455555, "mobile": 888888888 }
];
User.findOneAndUpdate(
{ "email": email },
{ "$push": { "phone": { "$each": newNumbers } } },
{ "new": true },
function(err,user) {
// The trick is to sort() on `_id` and just get the
// last added equal to the length of the input
var lastIds = user.phone.concat().sort(function(a,b) {
return a._id > b._id
}).slice(-newnumbers.length);
}
)
And even if you used a $sort modifier:
User.findOneAndUpdate(
{ "email": email },
{ "$push": { "phone": { "$each": newNumbers, "$sort": { "landline": 1 } } } },
{ "new": true },
function(err,user) {
var lastIds = user.phone.concat().sort(function(a,b) {
return a._id > b._id
}).slice(-newnumbers.length);
}
)
That little trick of "sorting" a temporary copy on the _id value means that the "newest" items are always at the end. And you just need to take as many off the end as you added in the update.
The arguable point here is that it's actually mongoose that is inserting the _id values in the first place. So in fact those are being submitted in the request made to the server for each array item.
You "could" get fancy and use "hooks" to record those ObjectId values that were actually added to the new array members in the update statement. But it's really just a simple process of returning the last n "greatest" _id values from the array items anyway, so the more complex approach is not needed.

How do I link each user to their data in Firebase?

I plan to create a main tree named users which will include the name different users used as username. So, from each username will be included their data e.g. Full Name, Address, Phone No.
I want to know how to get each user's data when they log in on their profile.
First of all i suggest you spend some time getting familiar with firebase by reading the Firebase Guide (Link to old Firebase Guide). Everything you need to know to answer your own question is available there. But for simplicity i will put an example here:
Lets start with security, here are the basic firebase rules you need for this example: (source: Understanding Security) (old source: Understanding Security)
{
"rules": {
"users": {
"$user_id": {
".write": "$user_id === auth.uid"
}
}
}
}
I will skip the actual user creation and logging in and focus on the question about storing and retrieving user data.
Storing data: (source: Firebase Authentication) (old source: User Authentication)
// Get a reference to the database service
var database = firebase.database();
// save the user's profile into Firebase so we can list users,
// use them in Security and Firebase Rules, and show profiles
function writeUserData(userId, name, email, imageUrl) {
firebase.database().ref('users/' + userId).set({
username: name,
email: email
//some more user data
});
}
The resulting firebase data will look like this:
{
"users": {
"simplelogin:213": {
"username": "password",
"email": "bobtony"
},
"twitter:123": {
"username": "twitter",
"email": "Andrew Lee"
},
"facebook:456": {
"username": "facebook",
"email": "James Tamplin"
}
}
}
And last but not least the retreiving of the data, this can be done in several ways but for this example i'm gonna use a simple example from the firebase guide: (source: Read and Write data) (old source: Retreiving Data)
//Get the current userID
var userId = firebase.auth().currentUser.uid;
//Get the user data
return firebase.database().ref('/users/' + userId).once('value').then(function(snapshot) {
//Do something with your user data located in snapshot
});
EDIT: Added example of return data
So when you are logged in as user twitter:123 you will get a reference to the location based on your user id and will get this data:
"twitter:123": {
"username": "twitter",
"email": "Andrew Lee"
}
Though I agree with Andre about setting the rules for good security - I would handle the data a bit differently. Instead of generating the string I use the child() method. It's a matter of personal preference.
Get the UID and define a data object:
let user = firebase.auth().currentUser
let uid = user.uid
let yourdata = { foo: 'something', bar: 'other'}
Save the data:
firebase.database().ref('users').child(uid).set(yourdata)
.then((data) => {
console.log('Saved Data', data)
})
.catch((error) => {
console.log('Storing Error', error)
})
Fetch the data:
firebase.database().ref('users').child(uid).once('value')
.then((data) => {
let fetchedData = data.val()
console.log('Fetched Data', fetchedData)
})
.catch((error) => {
console.log('Fetching Error', error)
})
Please notice that set() will override your data so you might want to use push() later on.

Categories