Start a new topic

Inserting data with Kinvey metadata during custom endpoint BL

Hey there,



In our app we're doing several .insert()'s from modules.collectionAccess. We noticed when we insert the data this way, versus doing it from the client with a DataStore.save(), the Kinvey metadata doesn't get inserted. I think this is expected.



I found this documentation about adding it to the object before inserting:

http://devcenter.kinvey.com/angular/reference/business-logic/reference.html#kinveyEntity



It works, but what's the best practice way to for example, get the "creator" metadata passed in properly? I've done this, and it works, but I'm not sure if there's a better way.



https://gist.github.com/dmackerman/e24072d29764e53292b2



Thanks!

See this question:



http://support.kinvey.com/hc/communities/public/questions/200365808-Blocked-script-violated?locale=en-us



This is what I use:



var logger = modules.logger,

utils = modules.utils,

moment = modules.moment,

collectionAccess = modules.collectionAccess,

userCollection = collectionAccess.collection('user'),



// find user by name and execute callback with its infos

var findUserByName = function(name, callback) {

userCollection.findOne({

"username": name

}, function(err, user) {

if (!user) { // should only happens when testing from the API console... or the undelying node driver had a hicup

userCollection.findOne({

"username": name

}, function(err, user) { // retry in case of hicup

if (!user) { // this is bad and should never occur

logger.error(name + ' not found after 2 tries: ' + err);

if (callback) callback(err);

} else {

logger.info(name + ' found at 2nd try');

if (callback) callback(err, user);

}

});

} else {

//logger.info(name + ' found at 1st try');

if (callback) callback(err, user);

}

});

};



Then



findUserByName(request.username, function(err, user) {

if (err) {

callback(err);

} else if (!user) {

callback('user not found');

} else {

var doc;

// process doc

utils.kinveyEntity(doc);

// because user._id is a BSON object, it cannot be used to set creator which is a JSON.

// Instead we get its string version from _acl.creator

doc._acl = { "creator": user._acl.creator};

save(doc, {}, function(err, sdoc) {

if (err) {

// handle error

} else {

// handle success

}

});

}



You can get the name of the user who submitted the request by invoking modules.backendContext.getAuthenticatedUsername();
Login or Signup to post a comment