我正在学习来自Laravel的NodeJS。我已经在Feathers生成器提供的钩子中设置了用户注册的基本验证。
如何使用用户服务检查数据库中是否已存在电子邮件地址?我使用MongoDB作为服务的数据库
const {authenticate} = require('@feathersjs/authentication').hooks;
const validator = require('validator');
const {
hashPassword, protect
} = require('@feathersjs/authentication-local').hooks;
module.exports = {
before: {
all: [],
find: [authenticate('jwt')],
get: [authenticate('jwt')],
create: [hashPassword(),
function(context) {
let input = context.data;
const userService = app.service('users');
if (validator.isEmpty(input.name)) {
throw new Error('Please enter your name.');
}
if (validator.isEmpty(input.email)) {
throw new Error('Please enter your email address.');
} else if (!validator.isEmail(input.email)) {
throw new Error('Please enter a valid email address.');
}
if (validator.isEmpty(input.password)) {
throw new Error('Please enter a password for your account.');
}
userService.find({
query: {
email: input.email
}
}).then((users) => {
console.log(users);
})
}
],
update: [hashPassword(), authenticate('jwt')],
patch: [hashPassword(), authenticate('jwt')],
remove: [authenticate('jwt')]
},
after: {
all: [
// Make sure the password field is never sent to the client
// Always must be the last hook
protect('password')
],
find: [],
get: [],
create: [],
update: [],
patch: [],
remove: []
},
error: {
all: [],
find: [],
get: [],
create: [
],
update: [],
patch: [],
remove: []
}
};
答案 0 :(得分:1)
上下文对象允许访问钩子的服务。 (这是问题的解决方案)因此,以下代码可用于确定数据库中是否存在用户的电子邮件地址。
此外,重复的电子邮件检查将在用户插入数据库后执行,因为它是一个承诺。因此,async和await用于在继续之前等待promise的解析。
module.exports = {
before: {
all: [],
find: [authenticate('jwt')],
get: [authenticate('jwt')],
create: [hashPassword(),
async context => {
let input = context.data;
//const userService = app.service('users');
if (validator.isEmpty(input.name)) {
throw new Error('Please enter your name.');
}
if (validator.isEmpty(input.email)) {
throw new Error('Please enter your email address.');
} else if (!validator.isEmail(input.email)) {
throw new Error('Please enter a valid email address.');
}
if (validator.isEmpty(input.password)) {
throw new Error('Please enter a password for your account.');
}
await context.service.find({
query: {
email: input.email
}
}).then((data) => {
if (data.data.length) {
throw new Error('This email address is already in use by somebody else.');
}
});
}
],
update: [hashPassword(), authenticate('jwt')],
patch: [hashPassword(), authenticate('jwt')],
remove: [authenticate('jwt')]
},