Search code examples
loopbackjsstrongloop

Strongloop UUID


heres a snippet of the model I've created. I would like the id property to be ALWAYS automatically generated via the uuid default function. However, when even added to hidden the id property could be decide by the user if they pass that into the post create method.

Other than using the method hooks OR operation hooks, to always overwrite the value is there another Loopback approach or flag (I have tried the foreId property as well) to ensure that the id is always a uuid even when the user provides a value? If not then for my case, "defaultFn": "uuid" completely pointless, if I'm always overwriting it.

{ 
  "name": "Account",
  "base": "PersistedModel",
  "strict": true,
  "idInjection": false,
  "options": {
    "validateUpsert": true
  },
  "properties": {
    "id": {
      "id": true,
      "required": true,
      "type": "string",
      "defaultFn": "uuid"
    },
  },
  "validations": [],
  "relations": {},
  "acls": [],
  "methods": {}
}

Solution

  • For some reason, the id can be redefined by the user through the REST api and is not protected when using idInjection: false and defining a custom id property.

    I'll open a ticket on github if it's not already done, in the meantime you can fix it easily using a before save operation hook

    In Account.js, using the uuid package

    const uuidV4 = require('uuid/v4');
    module.exports = function(Account) {
      Account.observe('before save', function(ctx, cb){
        if (ctx.instance) {
          ctx.instance.id = uuidV4();
        } else {
          ctx.data.id = uuidV4();
        }
        cb();
      });
    };