灏天阁

Node/Koa2[33]: 用户信息校验

· Yin灏

目录结构

└─src
    ├─middlewares
    │  └─validator.js
    ├─routes
    │  └─api
    │      └─user.js
    └─validator
        ├─user.js
        └─_validate.js

安装校验插件

npm i ajv --save

数据校验格式

src/validator/user.js

const validate = require("./_validate");

const SCHEMA = {
  type: "object",
  properties: {
    userName: {
      type: "string",
      pattern: "^[a-zA-Z][a-zA-Z0-9_]+$", // 字母开头,字母数字下划线
      maxLength: 255,
      minLength: 2,
    },
    password: {
      type: "string",
      maxLength: 255,
      minLength: 3,
    },
    newPassword: {
      type: "string",
      maxLength: 255,
      minLength: 3,
    },
    nickName: {
      type: "string",
      maxLength: 255,
    },
    picture: {
      type: "string",
      maxLength: 255,
    },
    city: {
      type: "string",
      maxLength: 255,
      minLength: 2,
    },
    gender: {
      type: "number",
      minimum: 1,
      maximum: 3,
    },
  },
};

// 执行校验
function userValidate(data = {}) {
  return validate(SCHEMA, data);
}

统一校验函数

src/validator/_validate.js

const Ajv = require("ajv");
const ajv = new Ajv({
  // allErrors: true, // 输出所有错误
});

function validate(schema, data = {}) {
  const valid = ajv.validate(schema, data);
  if (!valid) {
    return ajv.errors[0];
  }
}

module.exports = validate;

抽离中间件

src/middlewares/validator.js

const { ErrorModel } = require("../model/ResModel");
const { jsonSchemaFileInfo } = require("../model/ErrorInfo");

function genValidator(validateFn) {
  async function validator(ctx, next) {
    const data = ctx.request.body;
    const error = validateFn(data);
    if (error) {
      ctx.body = new ErrorModel(jsonSchemaFileInfo);
      return;
    }
    // 验证成功,继续执行
    await next();
  }
  return validator;
}
module.exports = {
  genValidator,
};

路由中使用校验

src/routes/api/user.js

//...
const userValidate = require("../../validator/user");
const { genValidator } = require("../../middlewares/validator");
// 注册路由
// 抽离中间件
router.post("/register", genValidator(genValidator), async (ctx, next) => {
  const { userName, password, gender } = ctx.request.body;
  ctx.body = await register({ userName, password, gender });
});

- Book Lists -