NodeJS - Updating object on request - javascript

I have the following object:
var user = {
firstName: req.body.first_name,
lastName: req.body.last_name,
email: req.body.email,
password: "",
id: "",
};
Now what I'm trying to do is post a request to the API and if the user is successfully saved in the database, it will return a user id as well as a password (Which can then be emailed to the person)..
request.post({
url: process.env.API_SIGNEDIN_ENDPOINT + "users/store",
form: user,
headers: {
Authorization: "Bearer " + req.session.authorization
}
}, function(error, response, body) {
// Check the response
var theResponse = JSON.parse(response.body);
if(theResponse.code == 400)
{
var error = [
{param: "email", msg: "This email address has already been taken!", value: ""}
];
res.render("create", {
errors: error,
});
}else{
var theUser = JSON.parse(body);
user.password = theUser.password;
user.id = theUser.id;
}
});
This is working fine, however, whenever I try to output user it's not updating the user object outside of this post. The user object is fine and it's working, the issue seems to be from when I try and access the user from this result callback. Any ideas?
EDIT:
Let's say I have "address1" (This is the persons main address) and I have "address2" (This is the persons second address).. The person might only have 1 address and therefore I only need to save one address. However using the logic that place everything in the .then() means I cannot do this because the user might not have 2 addresses but I still need to access the main address, for example:
mainAddress.save().then(function(addressData) {
var theAddressLicenceTick = req.body.address_licence;
if(theAddressLicenceTick)
{
var subAddress = models.addresses.build({
address_1: "asasfasf",
city: "asfafsaf",
postcode: "asfasf",
created_at: new Date(),
updated_at: new Date();
});
subAddress.save().then(function(subAddress) {
// continue integration
// would I have to do the functionality again?
});
}else{
// The user only has one address
}
});
Essentially, I have a customer table which can have multiple addresses through a link table. But I believe that there is an easier way instead of writing all of this code?

Related

In Google Directory API, how do I add a user using javascript?

I have the Google Directory API Javascript quickstart working. This part of the code lists the first 10 users in the directory:
gapi.client.directory.users.list({
'customer': 'my_customer',
'maxResults': 10,
'orderBy': 'email'
}).then(function(response) {
var users = response.result.users;
appendPre('Users:');
appendPre('test')
if (users && users.length > 0) {
for (i = 0; i < users.length; i++) {
var user = users[i];
appendPre('-' + user.primaryEmail + ' (' + user.name.fullName + ')');
}
} else {
appendPre('No users found.');
}
});
I want to add a user to the directory. It looks like this is done using users: insert. So after removing the 'readonly' part from the scope, I replace the above code snippet with this:
var user = {
"password": "Testpass123",
"primaryEmail": "albert.smith#mydomain.com",
"name": {
"givenName": "albert",
"familyName": "smith"
}
};
gapi.client.directory.users.insert(user);
Obviously this does not work, but I am unsure what I am missing. There is a "Try this API" tool on the users:insert reference page, and when I plug in the properties of 'user' in the "request body" field, it adds the user.
I'm not sure how to make a request body though, and I can't find a solution in the docs. The users:list method does not need a request body. I tried something like this, which also didn't work:
gapi.client.request({
'path': 'https://www.googleapis.com/admin/directory/v1/users',
'method': 'POST',
'body': user
});
Hoping someone can give me at least a general idea of what to do. I'm pretty new at this.
Try this dummy data derived from Apps Script's Admin SDK Add user and replace with your correct details:
sample request body:
var user = {
primaryEmail: 'liz#example.com',
name: {
givenName: 'Elizabeth',
familyName: 'Smith'
},
// Generate a random password string.
password: Math.random().toString(36)
};
Try wrapping the user object in a resource object like:
var user = {
resource: {
"password": "Testpass123",
"primaryEmail": "albert.smith#mydomain.com",
"name": {
"givenName": "albert",
"familyName": "smith"
}
}
}
I can't find a reference for this anymore so maybe someone else can post but it is working for me.
Based on https://developers.google.com/admin-sdk/directory/reference/rest/v1/users/insert :
function execute() {
return gapi.client.directory.users.insert({
"resource": {
"name": {
"familyName": "Shmoger",
"givenName": "Joey"
},
"password": "ShmoeyJoey!",
"primaryEmail": "shmogerjoe#grower.com"
}
})
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function(err) { console.error("Execute error", err); });
}

Ember.js - How to properly call the store from a controller?

so I am trying to access the store from a controller like so:
import Ember from 'ember';
export default Ember.Controller.extend({
emailAddress: '',
message: '',
isValidEmail: Ember.computed.match('emailAddress', /^.+#.+\..+$/),
isMessageLongEnough: Ember.computed.gte('message.length', 10),
isValid: Ember.computed.and('isValidEmail', 'isMessageLongEnough'),
isNotValid: Ember.computed.not('isValid'),
actions: {
sendConfirmation() {
this.store.createRecord('contact', {
email: emailAddress,
message: message,
}).save();
this.set('responseMessage', 'We got your message and we will be in contact soon :)');
this.set('emailAddress', '');
this.set('message', '');
}
}
});
I looked at the documentation for Ember.js 2.7 and it doesn't specifically tell you where one can have access to the store, but I know it can be access it through a controller or route.
However, doing it this way gives me these errors:
controllers/contact.js: line 17, col 16, 'emailAddress' is not defined.
controllers/contact.js: line 18, col 18, 'message' is not defined.
I'm not sure if it's the way I am accessing the controller, or the way I defined emailAddress and message.
Please help and thank you!
SOLVED:
For this part:
sendConfirmation() {
this.store.createRecord('contact', {
email: emailAddress,
message: message,
}).save();
It should have been this:
sendConfirmation() {
this.store.createRecord('contact', {
email: this.get('emailAddress'),
message: this.get('message'),
}).save();
:)
Your problem is not the way you access the store, it's that you're trying to add a contact with an email and a message without actually defining the variables.
sendConfirmation() {
this.store.createRecord('contact', {
// what do you expect emailAddress and message values to be at this point?
email: emailAddress, // <-- emailAddress is not defined
message: message, // <-- message is not defined
}).save();
// ...
Did you perhaps mean to retrieve them first?
sendConfirmation() {
// retrieve emailAddress and message first
const {
emailAddress,
message
} = this.getProperties('emailAddress', 'message');
// then use them to create a contact
this.store.createRecord('contact', {
email: emailAddress
message: message
}).save();
// ...
One more thing, accessing the store should probably be done using this.get('store'), since using getters/setters is the ember-way of accessing/manipulating properties.
By default store will be injected into controller and route. and one more thing you should get properties through get
sendConfirmation() {
var newRecordObj = {};
newRecordObj['email'] = this.get('emailAddress');
newRecordObj['message'] = this.get('message');
this.get('store').createRecord('contact', newRecordObj).save((result) => {
//success handling
this.set('responseMessage', 'We got your message and we will be in contact soon :)');
this.set('emailAddress', '');
this.set('message', '');
}, () => {
//error handling
this.set('responseMessage', 'Error message');
});
}

Username not changing properly using MongoDB update function?

Below is a snippet of my code where I begin by searching the collection of notes to see if any of them contain the username that I am changing my current session's username to. If the username has not yet been used, it may be changed to that so I change the current session's username and then I update every note to be under this new username then display a changesuccess.jade file. However, when I run the code everything appears to run fine exept the username for each note doesn't change. I feel like it's due to the find() method on the 5th line. Any help would be greatly appreciated!
router.post('/changeusername',function(req, res) {
var newUsername = req.body.username;
var user = req.session.username;
var userFound = notesCollection.find( { owner: newUsername } )
var results = function(infoInput) {
res.render("changedUser.jade", {title: "Username Change",
info: infoInput});
}
var checkChange = function(err) {
if (err) {
results("Username change failed!");
} else {
results("Username changed!");
}
}
console.log(userFound);
if (!userFound.length) {
notesCollection.update({ owner: user },
{ owner: newUsername},
{ multi: true },
checkChange);
} else {
res.render("changedUser.jade", {title: "Username Change",
info: "Username change failed!"});
}
});
If i understand your problem correctly, you are trying to update a collection in mongodb and it is not getting updated.
So the problem is with the way you are calling mongoose#update.
Since you want to update 'owner', you should use mongodb#$set
Mongoose supports the same $set operator in the conditions too.
So just a little correction for your case:
var conditions = { owner: user }
, update = { $set: { owner: newUsername }}
, options = { multi: true };
notesCollection.update(conditions, update, options, callback);
function callback (err, numAffected) {
// numAffected is the number of updated documents
})
So try this now.

angularjs message binding doesn't show until second form submit [duplicate]

This question already has an answer here:
How come Angular doesn't update with scope here?
(1 answer)
Closed 8 years ago.
I'm writing my first angularjs app, and it's beginning to make sense. However, I have a sign up form that isn't getting the messages in some cases to alert users to problems. I'm using Firebase to authenticate, which works fine. But I'm storing users by a unique username as the key. So before I run the $createUser function, I do a quick query to see if there's already a user object with this key-- if not, I create the user.
The problem is when there is an existing user with this username. The console log value prints fine, but the error message (bound to $scope.authMsg) doesn't show up the first time-- but if I click the "register" button again, then the message shows up in the expected message div.
Any hints on the message issue (or suggestions for this code) would be appreciated!
$scope.register = function() {
$scope.authMsg = '';
var ref = new Firebase(FIREBASE_URL);
$scope.authObj = $firebaseAuth(ref);
// check if the username is taken
ref.child("/users/"+$scope.account.username).on("value", function(snapshot) {
if (snapshot.val()) {
//
// PROBLEM HERE!!
//
$scope.authMsg = 'Username exists-- did you forget your password?'; // doesn't show on page until second submit
console.log('Username exists-- did you forget your password?'); // prints to console as expected
} else {
$scope.authObj.$createUser({ email: $scope.account.email, password: $scope.account.password })
.then(function(userData) {
console.dir(userData);
return $scope.authObj.$authWithPassword({
email: $scope.account.email,
password: $scope.account.password
});
}).then(function(authData) {
// we created a user and are now logged in-- store user info
var userdata = {};
userdata[$scope.account.username] = {
uid: authData.uid,
first_name: $scope.account.first_name,
last_name: $scope.account.last_name,
email: $scope.account.email,
full_name: $scope.account.first_name+' '+$scope.account.last_name
};
var usersRef = ref.child("users");
// save the userdata
usersRef.set(userdata);
console.log("Logged in as:", authData.uid);
$state.go('app.dashboard');
}).catch(function(error) {
$scope.authMsg = error;
console.error("Error: ", error);
});
}
}, function (errorObject) {
$scope.authMsg = 'The read failed: ' + errorObject.code;
console.log('The read failed: ' + errorObject.code);
});
};
I'm assuming, the Firebase callback does not involve an angular digest cycle.
To handle this, write
if (snapshot.val()) {
$scope.$apply(function() {
$scope.authMsg = 'Username exists— did you forget your password?';
});
A useful reading about the topic: http://jimhoskins.com/2012/12/17/angularjs-and-apply.html

startAt and endAt not working as expected using angularfire : 0.8.0

Using AngularFire 8.0
Bellow is the code which uses startAt and endAt to limit the data from firebase.
$rootScope.$on('$firebaseSimpleLogin:login', function(e, authUser){
var queryRef = ref.startAt(authUser.uid).endAt(authUser.uid);
var queryArray = $firebase(queryRef).$asArray();
queryArray.$loaded().then(function() {
setCurrentUser(queryArray.$keyAt(0));
});
});
The data returned should be a single element from firebase but queryArray is empty when I use console.log for debugging.
Without the use of startAt and endAt, the queryArray contains all the elements stored in the firebase.Therefore, logging queryArray.$keyAt(0) gives the First elements name as output. Which is as expected.
I have checked the release notes of Firebase 8.0 as well and I don't see any changes in these limiters.
Please point out if any syntactical mistake or any alternative solution which can achive the desired result.
I basically want single record from the Firebase, which is my current user , authUser is the authorized user with authUser.uid as its priority.
Following is the JSON file which is populated in the Firebase when a user registration happens.
{
"users" : {
"User A" : {
"md5_hash" : "d10ca8d11301c2f4993ac2279ce4b930",
"setPriority" : "simplelogin:69",
"username" : "User A"
},
"User B" : {
"md5_hash" : "2076105f6efe7c11e285add95f514b9a",
"setPriority" : "simplelogin:70",
"username" : "User B"
},
"User C" : {
"md5_hash" : "a6d14de05d7b2c3cf4fae7ae14cfa7f3",
"setPriority" : "simplelogin:71",
"username" : "User C"
}
}
}
After Edit
Using the bellow code to get the priority:
queryRef.once('value', function(nameSnapshot) {
var val = nameSnapshot.getPriority();
console.log("Priority is: " + val );
});
Log output is:
Priority is: null
The method used to add user to the Firebase is:
create: function (authUser, username) {
users[username] = {
md5_hash: authUser.md5_hash,
username: username,
setPriority: authUser.uid
};
users.$update(username, {
md5_hash: authUser.md5_hash,
username: username,
setPriority: authUser.uid
//$priority: authUser.uid
}).then(function () {
setCurrentUser(username);
});
}, // end of create method
It looks like the priority on all of your data is null. This prevents endAt and startAt from working properly.
The clue that something is up is the existence of the setPriority key in your data. Priority is metadata that's managed outside the normal view.
Change your user creation code to something like this:
create: function (authUser, username) {
users[username] = {
md5_hash: authUser.md5_hash,
username: username,
.priority: authUser.uid
};
} // end of create method
or this:
create: function (authUser, username) {
users[username] = {
md5_hash: authUser.md5_hash,
username: username
};
users.$update(username, {
md5_hash: authUser.md5_hash,
username: username
}).then(function (dataRef) {
dataRef.setPriority(authUser.uid);
setCurrentUser(username);
});
} // end of create method

Categories

Resources