Node.js Joi验证Sequelize自定义方法
我目前正试图通过Sequelize验证用户名是否已经存在,但是当前在将响应发送回客户机后,承诺将返回,这意味着Joi每次都认为用户名不存在。任何人都知道如何不让Joi过早地完成验证,并实际处理查询/返回正确的结果 schema.jsNode.js Joi验证Sequelize自定义方法,node.js,sequelize.js,joi,Node.js,Sequelize.js,Joi,我目前正试图通过Sequelize验证用户名是否已经存在,但是当前在将响应发送回客户机后,承诺将返回,这意味着Joi每次都认为用户名不存在。任何人都知道如何不让Joi过早地完成验证,并实际处理查询/返回正确的结果 schema.js const Joi = require('joi') const { User } = require('../models') const validateUsername = (value, helpers) => { User.findOne(
const Joi = require('joi')
const { User } = require('../models')
const validateUsername = (value, helpers) => {
User.findOne({ where: { username: value } }).then(user => {
if (user) {
return helpers.error('username.exists')
}
return value
})
}
const schema = Joi.object({
body: {
username: Joi.string().min(3).required().custom(validateUsername)
.messages({
'string.base': 'Invalid Username',
'string.empty': 'Username Required',
'string.min': 'Username Must Be At Least {#limit} Characters Long',
'any.required': 'Username Required',
'username.exists': 'Username Already In Use'
})
}
})
module.exports = schema
const options = {
abortEarly: false,
allowUnknown: true,
stripUnknown: true
}
const validator = (schema) => {
return (req, res, next) => {
const { error } = schema.validate(req, options)
const valid = error == null
if (valid) {
next()
} else {
const { details } = error;
const errors = details.map(i => i.message)
res.status(422).json({ errors })
}
}
}
module.exports = validator
validator.js
const Joi = require('joi')
const { User } = require('../models')
const validateUsername = (value, helpers) => {
User.findOne({ where: { username: value } }).then(user => {
if (user) {
return helpers.error('username.exists')
}
return value
})
}
const schema = Joi.object({
body: {
username: Joi.string().min(3).required().custom(validateUsername)
.messages({
'string.base': 'Invalid Username',
'string.empty': 'Username Required',
'string.min': 'Username Must Be At Least {#limit} Characters Long',
'any.required': 'Username Required',
'username.exists': 'Username Already In Use'
})
}
})
module.exports = schema
const options = {
abortEarly: false,
allowUnknown: true,
stripUnknown: true
}
const validator = (schema) => {
return (req, res, next) => {
const { error } = schema.validate(req, options)
const valid = error == null
if (valid) {
next()
} else {
const { details } = error;
const errors = details.map(i => i.message)
res.status(422).json({ errors })
}
}
}
module.exports = validator