// | ------------------------------------------------------------ // | @版本: version 0.1 // | @创建人: 【Nie-x7129】 // | @E-mail: x71291@outlook.com // | @所在项目: P01CentralControl // | @文件描述: index.js - // | @创建时间: 2024-01-15 10:49 // | @更新时间: 2024-01-15 10:49 // | @修改记录: // | -*-*-*- (时间--修改人--修改说明) -*-*-*- // | = // | ------------------------------------------------------------ import Ajv from 'ajv'; // ajv错误消息回应 import ajvErrors from 'ajv-errors'; // 将字符串转化为全小写 export function isLowerCase(ajv){ ajv.addKeyword({ keyword: 'isLowerCase', // 开启错误收集 errors: true, modifying: true, validate: function validateIsEven(schema, data, parentSchema, dataCxt) { if(typeof data == 'string'){ dataCxt.parentData[dataCxt.parentDataProperty] = dataCxt.parentData[dataCxt.parentDataProperty].trim().toLowerCase(); return true; }else{ validateIsEven.errors = [ { message: '错误的数据' } ]; return false; } } }); } // 去除两端空格 export function isTrim(ajv){ ajv.addKeyword({ keyword: 'isTrim', type: 'string', // 开启错误收集 errors: true, modifying: true, validate: function validateIsEven(schema, data, parentSchema, dataCxt) { if(typeof data == 'string'){ dataCxt.parentData[dataCxt.parentDataProperty] = dataCxt.parentData[dataCxt.parentDataProperty].trim(); return true; }else{ validateIsEven.errors = [ { message: 'is note String' } ]; return false; } } }); } // 给fastify添加自定义的参数校验规则 function customAjv(fastify, options){ // 创建一个新的 AJV 实例 // 创建一个新的 AJV 实例 const ajv = new Ajv({ removeAdditional: true, useDefaults: true, coerceTypes: true, // jsonPointers: true, allErrors: true }); ajvErrors(ajv); isLowerCase(ajv); // 使用自定义的 AJV 实例为 Fastify 设置验证器编译器 fastify.setValidatorCompiler(({ schema, method, url, httpPart }) => { return ajv.compile(schema); }); }