Search code examples
hookfeathersjs

validating lack of parameters in feathresjs


I've read the feathersjs documentation, but after doing a find method in a service I realized that if I don't give any query parameters, the service returns all the data, which is something I don't want. How can I define a hook to validate that there are at least one query parameter in order to proceed; otherwise, send back a 403 error (bad request).?

I have doubts in the way to do it I tried this:

app.service('myService')
    .before(function(hook) {
        if (hook.params.query.name === undefined){
            console.log('There is no name, throw an error!');
        }
})
.find({
    query: {
        $sort: {
            year: -1
        }
    }
})

And I tried in hook file on hooks this (that seemed really desperate & | stupid):

function noparams (hook) {
    if (hook.params.query.name === undefined){
        console.log('There is no name, throw an error!');
    }
}

module.exports = {
    before: {
        find: [ noparams(this) ] ...
    }
}

but it does not compile (I don't know what to send as a parameter there), and the examples seemed to be for pre 2.0 version and on top of that the code I found seemed to be in the app.js, but all is differently coded using feathers-cli, so the examples, even in the book, aren't against the scaffolded version, which is confusing because they shows the code in a different file were should be.

Thanks.


Solution

  • I ended using a before hook, so the code used is this:

    const errors = require('feathers-errors');
    
    module.exports = function () {
      return function (hook) {
        if(hook.method === 'find'){
          if (hook.params.query.name === undefined || hook.params.query.length == 0){
            throw new errors.BadRequest('Invalid Parameters');
          }else{
            return hook;
          }
        }
      }
    };
    

    If have used feathers-cli to generate your application (feathers v2.x) you don't need to do anything else. If is an earlier version you maybe need to add the Express error handler and it is pointed out in the documentation|Errors|REST.

    Thanks.