liuxiaodong / egg-joi Goto Github PK
View Code? Open in Web Editor NEWLicense: MIT License
License: MIT License
下面是 Express 的实现,供参考:
export default function(validations, options = {
// when true, allows object to contain unknown keys which are ignored. Defaults to false.
allowUnknown: true,
// allowUnknown: false,
// stripUnknown: true,
// when true, stops validation on the first error, otherwise returns all the errors found. Defaults to true
abortEarly: true,
}) {
// When stripUnknown is true, Joi will validate every parameter in req.params, req.body, req.query.
// If false, Joi will only validate parameters specified in the given validation object and pass any others directly through.
function validate(req, res, next) {
if (!validations || !validations.isJoi) {
return next(new Error('Must be a joi object.'))
}
// Get all of our req data items
const body = req.body
const params = req.params // RESTful API 参数
const query = req.query
let items = {}
copyObject(params, items, null, null)
copyObject(query, items, null, null)
copyObject(body, items, null, null)
try {
Joi.validate(items, validations, options, function(err, value) {
if (err) {
console.log(items);
next(err)
} else {
req.items = value
next()
}
})
} catch (err) {
next(err)
}
}
return validate
}
/**
*
*
* @param {Object} from
* @param {Object} to
* @param {Object} validations list of validation keys.
* @param {Boolean} decode
*/
function copyObject(from, to, validations, decode) {
if (from) {
for (var key in from) {
try {
to[key] = (decode && typeof(from[key]) === 'string') ? decodeURIComponent(from[key]) : from[key]
} catch (err) {
to[key] = from[key]
}
}
}
}
error 的获取应该直接try catch。而不是通过返回。
目前这样,下面这种偷懒技巧就不太好用了。
const { phone, password } = ctx.validate...
// 这样会不会很奇怪
const { value: { phone, password }} = ctx.validate...
目前Joi schema中如果使用了 .error(), 代码报错
例如:
login: Joi.object().keys({
mobile: Joi.string().regex(/^1\d{10}$/).label('手机号码')
.error(new Error('手机号码输入不正确')),
}),
需要对.error()返回的结果进行处理
"Error: 手机号码输入不正确"
如果以字符串的形式提交一个期望是number或者date类型的属性。通过验证后,joi会把数据类型转换成number或者date。 但是在这里依然是string类型
I just write index.d.ts for egg-joi, dynamic validator interface support can use egg-ts-helper, just like egg-sequelize app/model directory. My approach as follow:
// egg-joi
// index.d.ts
import * as Joi from 'joi';
declare module 'egg' {
interface Application {
Joi: typeof Joi;
}
interface Context {
validate<T>(schema: Joi.Schema, data: T, opt?: Joi.ValidationOptions, autoThrow?: boolean): Joi.ValidationResult<T> | any;
}
}
// in application
// tshelper.js
module.exports = {
watchDirs: {
validator: {
directory: 'app/validator', // files directory.
// pattern: '**/*.(ts|js)', // glob pattern, default is **/*.(ts|js). it doesn't need to configure normally.
// ignore: '', // ignore glob pattern, default to empty.
generator: 'auto', // generator name, eg: class、auto、function、object
interface: 'IValidator', // interface name
declareTo: 'Application.validator', // declare to this interface
// watch: true, // whether need to watch files
// caseStyle: 'upper', // caseStyle for loader
// interfaceHandle: val => `ReturnType<typeof ${val}>`, // interfaceHandle
// trigger: ['add', 'unlink'], // recreate d.ts when receive these events, all events: ['add', 'unlink', 'change']
}
}
}
// app/validator/api.ts
import { Application } from 'egg';
export default (app: Application) => {
const Joi = app.Joi;
return {
dateRange: Joi.object().keys({
begin: Joi.string().required(),
end: [ Joi.string(), Joi.number() ],
}),
};
};
// generated file
// This file is created by [email protected]
// Do not modify this file!!!!!!!!!
import 'egg';
type AutoInstanceType<T, U = T extends (...args: any[]) => any ? ReturnType<T> : T> = U extends { new (...args: any[]): any } ? InstanceType<U> : U;
import ExportApi from '../../../app/validator/api';
declare module 'egg' {
interface Application {
validator: IValidator;
}
interface IValidator {
api: AutoInstanceType<typeof ExportApi>;
}
}
Object.assign(config.joi.options, options )
这是符合预期的么,没有做 required 的区分么。。
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.