Search code examples
loopbackjsstrongloop

On Loopback, how to programmatically add data to the posted content, such as UserID and Date?


Suppose that you created an App that allow registered users to POST content to the Database (MySQL) through the Loopback API. Now, how would you intercept the posted content to fill out some of the fields, such as: - The UserID, based on the Access Token? - The current Date/Time?


Solution

  • Using a remote hook will be right way. Here is an example of remote hook that will add created date, modified date and userId before saving the record. The created date and ownerId will be set only if it's a new record and set the modified date on update calls.

    common/models/model.js

    'use strict';
    
    module.exports = function(Model) {
        // Set dates and userId before saving the model
        Model.observe('before save', function setAutoData(context, next) {
            if (context.instance) {
                if(context.isNewInstance) {
                    context.instance.created = Date.now();
                    context.instance.ownerId = context.options.accessToken.userId;
                }
                context.instance.modified = Date.now();
            }
            next();
        });    
    };