koajs / joi-router

Configurable, input and output validated routing for koa
MIT License
450 stars 96 forks source link

Is there a way to set global joi config? #85

Closed yuxizhe closed 5 years ago

yuxizhe commented 5 years ago

I want to set joi allowUnknown as a global config, because I don't mind what additional fields are passed in as long as the fields I want are supplied. I have to set allowUnknown in every Joi valid code, is there a way to set global Joi config like this below?

const router = require('koa-joi-router');
const pub = router({
  validate: {
    allowUnknown: true,
  },
});
Saghen commented 5 years ago

I have implemented this functionality in my fork: https://github.com/Saghen/joi-router

It has support for a custom error handler and a default spec. In your case, simply do:

const pub = router({
  spec: {
    validate: {
      allowUnknown: true,
    }
  }
});

and here is how to use a custom error handler

const blog = router({
  errorHandler: function(ctx, type, err) {
    // In my case I have a request builder in my ctx via app.context.buildError = myFunction
    ctx.buildError({ 
      status: err.status,
      errors: [{
        message: err.message
      }]
     })
  }
});

Please note that this fork is still very much a work in progress and since changes will be made in the future, I'd recommend forking it yourself and making any changes you need if issues arise.

yuxizhe commented 5 years ago

@Saghen Thanks for your replay! Its very helpful 👍 .

aheckmann commented 5 years ago

Closing as duplicate of #41.