简体   繁体   English

为eggjs框架添加koa插件

[英]Add koa plugin to eggjs framework

I would like to add koa-validate to eggjs .我想将koa-validate添加到eggjs

Code from koa-validate readme :来自 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 :因此,我尝试将其添加为Eggjs 文档中所述的中间件:

// 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:为生命周期钩子添加/app.js并添加以下代码:

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.而不是记录的 this.checkQuery() 函数可以作为 this 使用。 ctx .checkQuery. ctx .checkQuery。

Maybe this will help someone else.也许这会帮助别人。

Maybe not the answer but for egg js validating, there is already an official plugin there: https://github.com/eggjs/egg-validate也许不是答案,但是对于 Egg js 验证,那里已经有一个官方插件: https : //github.com/eggjs/egg-validate

For the real answer: You can refer the example repo: https://github.com/Jeff-Tian/egg-useragent .对于真正的答案:您可以参考示例 repo: https : //github.com/Jeff-Tian/egg-useragent This is a real world example that adds koa-useragent to eggjs framework.这是一个将 koa-useragent 添加到 eggjs 框架的真实示例。 Core code is:核心代码是:

import {Application} from "egg"

import koaUserAgent from 'koa-useragent'

export default (app: Application) => {
    app.use(koaUserAgent)
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM