Reputation: 3329
With this code in common/models/model.js, I can add a custom validation function to a model:
module.exports = function(model) {
model.validate('property', validatorCallback, { message: 'Message.' });
function validatorCallback(err) {
// How to access userId and assigned user roles here?
}
};
But how can I access the current user's userId and roles in the validation function?
Upvotes: 1
Views: 297
Reputation: 3329
It looks like this is currently not possible. There is a work in progress issue on Github about this: WIP: Custom validator promises and options #1229
My solution for now is to to add a before save operation hook and validate the value there. In the before save hook, the context is available and can be used to access ctx.options.accessToken.userId
. If the value is invalid, I set it to a specific invalid value (in my case -1). Then I can simply add a validator that excludes -1:
validatesExclusionOf('validatedProperty', { in: [-1], message: 'Invalid value.' });
The advantage of using a before save operation hook is that it runs regardless of how the model is accessed / changed. And by using the in-built validatesExclusionOf
validator, I get the standard ValidationError response.
Upvotes: 1
Reputation: 9406
There is a loopback-context
created for this goal. But as my experience it is buggy and useless.
But validator is not a good place for your goal.
Remote hooks is the best place for that.
Upvotes: 1