sails endpoint and model validation

0

in a project with sails, I have created a car model:

// Coche.js

module.exports = {
  attributes: {
    name: {
      type: 'string',
      required: true
    },

    color: {
      type: 'string',
      required: false
    },

    price: {
      type: 'number,
      required: true
    }
  }
}

With this, the sails themselves have their own endpoints with / car, so I can have the get, post, delete ...

Now, I need to create an endpoint / car / validate itself (I just need to validate the post with the model, then I call a service with the data NOT STORED in BBDD). I've defined it like this:

(module).exports = function api(sails) {
    return {
        initialize: function(cb) {
        sails.on('router:after', function() {
            sails.router.bind('/coche/validate', validate, 'post', {});
        });

        function validate(req: Request, res: Response, next: Function) {
/**
            como puedo "validar" mi modelo coche, si lo que tengo es req y res?
            con req.body obtengo los parametros de post, pero todos son string.
**/            return(res.json(resultado));
        }

        return cb();
        },
    }

The problem is that I do not really know how to link or work with the model, in this action. The ones of get, post and delete of / car are "auto-magicas" of the own sails ...

Is there any way to check the post (with req.body I get an array with the fields that arrive in the post) and validate with some function of sails that data with the model ????

    
asked by Jakala 01.03.2018 в 17:00
source

1 answer

0

Investigating a little more, I have solved the problem in the following way, installing a library called

  

link

With this library installed, now the request object has a new method called "validate", and we can do:

req.validate({'price': 'number'}, false, callback);

where:

  • first parameter is an array with the name of the field and the type that we want to validate
  • false is to disable the validation that comes through defect (makes a direct response and I'm not interested)
  • callback: is a function to decide what to do if the validation is correct or invalid.

If you are interested, take a look at the previous link, it is the manual where it is best explained.

    
answered by 06.03.2018 в 11:21