lykmapipo / sails-hook-validation

Custom validation error messages for sails model with i18n support
104 stars 29 forks source link

Throw Custom Error #30

Open LeonardoGentile opened 8 years ago

LeonardoGentile commented 8 years ago

Hello, first of all thanks for this useful package :+1:

Then, I'm running in couple of problems and I was wondering if someone had already went trough these:

1) For some model I have a complex creation logic and I want so skip standard validation for some creation flows. For doing this I have custom beforeCreate or beforeValidate for some models. What I would like to do is to manually throw your "patched" validation error if some conditions occurs. Is it possible? How?

2) In my controllers when I return a response in json I check whether or not there are errors. I check error.Errors in case a validation error occurs. But this is not always the case, and in many cases the structure of the errors messages are really different. How to manage this? So far I've came to a simple

var errors = err.Errors || err.message || "Unknown Error";
response.json(status, {'errors': errors});

but this is not always the case, because the structure of the error can change, depending on the type of error. I know it's a broad question but I was wondering if you already faced this kind of problems.

Thanks!

Seitk commented 8 years ago

1) I have different use case but the solution might be helpful to you. In my situation, I need to do validation over 2 models in once. You might "clone" your model and put those validations for some creation flows

var objectMerge = require('object-merge');
var Promise = require('bluebird');
var User = require('./User');
var Auth = require('./Auth');

var model = {
  connection: 'memory',
  tableName: 'UserAuthValidation',
  schema: true,
  attributes: {}
};

var attributesToCheck = [ 'id', 'status', 'name', 'email', 'type', 'key', 'credential' ];
for (var key in User.attributes) {
    if (attributesToCheck.indexOf(key) >= 0) {
        model.attributes[key] = User.attributes[key];
    }
}
for (var key in Auth.attributes) {
    if (attributesToCheck.indexOf(key) >= 0) {
        model.attributes[key] = Auth.attributes[key];
    }
}

var key = 'validationMessages';
model[key] = objectMerge(objectMerge.createOptions({depth : 3}), User[key], Auth[key]);

module.exports = model;

2) I think you can use "custom validation rules" in sails, the key can be used in validationMessages when your validation fails http://sailsjs.org/documentation/concepts/models-and-orm/validations#?custom-validation-rules