Search code examples
loopbackjsstronglooploopback

Can I hide model properties from datasources in strongloop?


I would like to pass a "token" object to POST /MyObject. The easiest way to do that seems to be to add it as a property to MyObject.json. The problem is that this token is not persisted (it doesn't last for very long and there's no need to save it).

I figured out how to get around this issue for POST:

MyObject.beforeRemote('create', function (context, unused, nextFn) {
    var token = context.args.data.token;

    //We have to delete this so it doesn't try to put it in the database
    delete context.args.data.token;
    nextFn();
});

But the code crashes when I do a GET.

I tried just adding it as a second parameter to a new remote method, with MyObject as the first param, but after wrestling with strongloop for three hours and having nothing to show for it I gave up/

Is there any way to just add a property so that I can use it in node, but keep it from being persisted?


Solution

  • You can define a model just for representation.

    //MyObjectInput.json
    {
      "name": "MyObjectInput",
      "base": "Model",
      "idInjection": true,
      "options": {
        "validateUpsert": true
      },
      "properties": {
        "name": {
          "type": "string",
          "required": true
        },
        "token": {
          "type": "string"
        }
      ...
      },  
      "validations": [],
      "relations": {},
      "acls": [],
      "methods": {}
    }
    
    
    //MyObject.json
    {
      "name": "MyObject",
      "base": "PersistedModel",
      "strict": true,
      "idInjection": true,
      "options": {
        "validateUpsert": true
      },
      "properties": {
        "name": {
          "type": "string",
          "required": true
        }
      ...
      },  
      "validations": [],
      "relations": {},
      "acls": [],
      "methods": {}
    }
    

    Please note that to sctrict key in MyObject.json. It denotes all defined properties should be persisted. Now you don't have token in MyObject definition, so it's not persisted.

    //MyObject.js
    MyObject.remoteMethod(
            'create', {
                accepts: [
                    {
                        arg: 'data',
                        type: 'MyObjectInput',
                        http: {source: 'body'}
                    }
                ],
                returns: {
                    arg: 'result',
                    type: 'object',
                    root: true
                },
                http: {
                    path: "/create",
                    verb: 'post',
                    status: 201
                }
            }
        );