koa 运用 joi 实现 接口一致性检

堵雅健
2023-12-01
import Koa from 'koa';
import Joi from 'joi';
import Router from '@koa/router';
import validateSchemaJoi from './middlewares/schema.js';

const app = new Koa();
const router = new Router();

const loginSchema = Joi.object({
  a: Joi.string()
      .min(3)
      .max(30)
});

router.get('/test', validateSchemaJoi('get', loginSchema), async (req, next) => {
  req.body = 'haha'
});

app
  .use(router.routes())
  .use(router.allowedMethods());

app.listen(3000);
 
function validateSchemaJoi(method, schema) {
  async function validateSchema (ctx, next) {
    let data = undefined;
    if (method === 'get') {
      data = ctx.request.query;
    } else {
      data = ctx.request.body;
    }
    const { value, error } = schema.validate(data);
    if (error) {
      ctx.body = error;
    } else {
      next();
    }
  }
  return validateSchema;
}

export default validateSchemaJoi;
 类似资料: