Search code examples
sails.jswaterline

sails.js api blueprints are generating POST endpoints even for auto incremented id, how to avoid this?


for example if I create a model called Job

module.exports = {
  attributes: {
    id: {
      type: 'integer',
      autoIncrement: true,
      unique: true,
      primaryKey: true
    },

    name: {
      type: 'string',
      required: true
    }
}

the blueprint generates POST method on /job/:id

But I don't want the users to be allowed to specify the ID by themselves. I want the ID to be auto-incremented by server. So the mentioned POST api endpoint should not be created at all. To create a new Job, there should only be POST endpoint /job

Is there an option for api blueprints to change this behavior? Or is there any workaround other than disabling blueprints and defining the api endpoints manually?


Solution

  • The blueprint routes are a great shortcut to get things started, but ultimately I feel like you will probably want more custom behaviour than they offer in most cases.

    To override the create access on just a single model, you can add a custom create method on that model's controller. So, in /api/controllers/JobController.js:

    module.exports = {
        create: function(req, res) {
            var createParams = req.body;
            // do whatever you want with the passed in parameters here
            createParams.customCreate = true;
            delete createParams.id;
    
            Job.create(createParams).exec(function(err, createdJob) {
                if (err) {
                    // handle the error
                } else {
                    return res.send(createdJob);
                }
            });
        },
        // ...
    };
    

    If you want to manage blueprint routes for all models at once, see here - you can turn blueprints off all together if that is preferred.