Search code examples
loopbackjs

Modify loopback model before returning to client


I have a ServerFile model which stores various pieces of information about an uploaded file.

{
 ....
 filename: 'blah.jpeg',
 container: 'images',
 size: 123654,
 ...
}

I would like to return a dynamically url property with the object, without storing it in a database.

{
 ....
 filename: 'blah.jpeg',
 container: 'images',
 size: 123654,
 ...
 url: 'uploads/images/blah.jpeg'
}

How would I go about doing this?


Solution

  • In your common/models/server-file.js file add a remote hook on find.

    module.exports = function(ServerFile) {
    ....
    ServerFile.afterRemote('find', function(ctx, modelInstance, next) {
        if (ctx.result) {
          if (Array.isArray(ctx.result)) {
            ctx.result.forEach(function(result) {
              result.url = new String(result.constructUrl());
            });
          } else {
            result.url = new String(result.constructUrl());
          }
        }
        next();
      });
    

    Additionally, if you wished to remove an attribute before sending it back you can use

    result.unsetAttribute('password')