I would like to add koa-validate to eggjs.
Code from koa-validate readme:
var koa = require('koa');
var app = koa();
var router = require('koa-router')();
require('koa-validate')(app);
app.use(require('koa-body')({multipart:true , formidable:{keepExtensions:true}}));
app.use(router.routes()).use(router.allowedMethods());
So I tried to add it as middleware as described in the eggjs docs:
// app/middleware/validate.js
const validate = require('koa-validate');
module.exports = (options, app) => {
validate(app);
return function session(ctx, next) {
return next();
}
}
But what I am actually looking for is to load the plugin 'on boot' and have the app object to add the validate plugin. Do you have any idea where I should place this?
thank you!
Okay, I solved it myself:
Add /app.js for life-cycle hooks and add the following code:
const validate = require('koa-validate');
class AppBootHook {
constructor(app) {
this.app = app;
validate(app);
}
}
module.exports = AppBootHook;
Instead of the documented this.checkQuery() the function is available as this.ctx.checkQuery.
Maybe this will help someone else.