使用FeatherJS,我定义了这样的用户模型:
import NeDB from 'nedb';
import path from 'path';
import { Application } from '../declarations';
export default function (app: Application): NeDB {
const dbPath = app.get('nedb');
const Model = new NeDB({
filename: path.join(dbPath, 'users.db'),
autoload: true,
});
Model.ensureIndex({
fieldName: 'email',
unique: true,
});
return Model;
}
而且我要确保对用户钩子上Joi的验证:
import * as feathersAuthentication from '@feathersjs/authentication';
import * as local from '@feathersjs/authentication-local';
import { disallow } from 'feathers-hooks-common';
import Joi from '@hapi/joi';
import { validate } from '../../hooks';
const { authenticate } = feathersAuthentication.hooks;
const { hashPassword, protect } = local.hooks;
const validation = validate(
Joi.object({
email: Joi.string().email().alter({
create: (schema) => schema.required(),
}),
password: Joi.string().min(8).alter({
create: (schema) => schema.required(),
}),
}),
);
export default {
before: {
all: [],
find: [
authenticate('jwt'),
],
get: [
authenticate('jwt'),
],
create: [
validation,
hashPassword('password'),
],
update: disallow(),
patch: [
hashPassword('password'),
authenticate('jwt'),
],
remove: [
authenticate('jwt'),
],
},
// ...
};
Joi验证正在工作,如果提交的数据无效,则会产生错误的请求错误。
[唯一索引阻止用户使用现有的电子邮件地址创建帐户,但是会产生一个基本的500错误实例,很难在我的前端应用程序上利用。
是否有一种方法可以处理Joi的唯一验证,还是我应该重新考虑自己的逻辑?
注意:我在这里使用NeDB,但也可以迁移到Mongo。
我也面临这个问题。我解决此问题的方法是从挂钩中访问服务,以检查是否已经存在具有相同电子邮件的帐户。
在您的钩中,添加类似内容。
const userService = context.app.service(“users”);// get the users service
const result = await userService.find({query: {email: context.data.email }});
if (result.total > 0) { // throw an error because an account already exists.}
此解决方案对我有效,因为它已与任何类型的数据库或软件包分离。
[我们在这里所做的是询问用户服务,如果使用该服务的find()
方法已经存在具有相同电子邮件的用户。如果服务返回记录,即result.total > 0
,则该服务已经有一个用户使用相同的电子邮件。因此,我们抛出异常。
您可以了解有关查询服务here的更多信息>