好的,我自己解决了。不确定这是否是聪明的或“正确”的方法,但我的解决方案是在每个控制器中创建一个中间件,在ctx.state .bodyAttribs 中设置预期的模式属性。
像这样...
// /src/routers/user.router.ts
import * as UserController from '../controller/user.controller';
import * as Midware from './middleware';
import Router from 'koa-router';
import compose from 'koa-compose';
const router = new Router();
router.prefix('/user');
router.get('/', Midware.verifyAuthToken, UserController.getAll);
router.post('/', compose([
UserController.bodyAttribs,
Midware.verifyAuthToken,
Midware.bodySchemaTest,
Midware.injectionTest,
]), UserController.postNew);
module.exports = router;
// /src/controller/user.controller.ts
import { Context } from 'koa';
import { UserData } from '../data/mongo/user.data.mongo';
import { UserModel } from '../model/user.model';
import { EmailValidate } from '../service/email-validate.service';
import * as Logger from '../util/logger';
const dataContext = new UserData();
// Middleware to set bodyAttribs
export const bodyAttribs = async (ctx: Context, next: any) => {
ctx.state.bodyAttribs = ['handle', 'processUserOptions', 'name', 'email', 'pass', 'passConfirm'];
return await next();
};
...
所以每个控制器都提供了设置我要验证的自定义 bodyAttribs 的自定义中间件。您可以使用这种方法在 ctx.state 中设置并将 1 传递给任意数量的额外参数,无论您需要什么,它总是继续到链中的下一个中间件。跟随?:-)