Typescript 和 Express Validator 自定义验证类型
Typescript and Express Validator custom validation types
使用快速验证器的自定义方法时出现错误
Argument of type '(userDoc: User | null) => Promise<never> | undefined' is not assignable to parameter of type '(value: User | null) => PromiseLike<never>'.
Type 'Promise<never> | undefined' is not assignable to type 'PromiseLike<never>'.
Type 'undefined' is not assignable to type 'PromiseLike<never>'.
import express from 'express';
import { body } from 'express-validator/check'
import User from '../models/User';
import { login, signUp } from '../controllers/auth';
const router = express.Router();
router.post(
'/sign-up',
[
body('username', 'User Name should be atlest 4 characters long')
.isLength({ min: 4 })
.isString()
.trim()
.custom((username: string, { req }) => {
return User.findOne({ username }).then(userDoc => {
if (userDoc) {
return Promise.reject('User Name is already taken');
}
});
})
],
signUp,
);
您实施 User.findOne
return 的方式是一个承诺。这就是为什么您使用 Promise.reject
来抛出错误的原因。因此,如果验证成功,您还必须 return 一个 Promise 对象。
if (userDoc) {
return Promise.reject('User Name is already taken');
}
return Promise.resolve()
使用快速验证器的自定义方法时出现错误
Argument of type '(userDoc: User | null) => Promise<never> | undefined' is not assignable to parameter of type '(value: User | null) => PromiseLike<never>'.
Type 'Promise<never> | undefined' is not assignable to type 'PromiseLike<never>'.
Type 'undefined' is not assignable to type 'PromiseLike<never>'.
import express from 'express';
import { body } from 'express-validator/check'
import User from '../models/User';
import { login, signUp } from '../controllers/auth';
const router = express.Router();
router.post(
'/sign-up',
[
body('username', 'User Name should be atlest 4 characters long')
.isLength({ min: 4 })
.isString()
.trim()
.custom((username: string, { req }) => {
return User.findOne({ username }).then(userDoc => {
if (userDoc) {
return Promise.reject('User Name is already taken');
}
});
})
],
signUp,
);
您实施 User.findOne
return 的方式是一个承诺。这就是为什么您使用 Promise.reject
来抛出错误的原因。因此,如果验证成功,您还必须 return 一个 Promise 对象。
if (userDoc) {
return Promise.reject('User Name is already taken');
}
return Promise.resolve()