FeathersJS 防止服务重复的方法
FeathersJS way of preventing duplicates in a service
我正在使用 FeathersJS 和 MongoDB 开发应用程序。我想阻止某些服务创建某些值(或值对)的副本。
例如,使用 feathers-cli 工具创建的 FeathersJS "Authenticate" 服务不会阻止应用程序使用同一电子邮件地址创建 2 个或更多用户(至少使用 MongoDB)。另一个例子是为每个用户创建一些 "categories" 的服务。我希望后端阻止用户创建 2 个或更多具有相同名称的类别,但我需要允许 2 个不同的用户创建他们自己的类别,尽管他们的名称相同(但不是用户)。
我知道我可以通过在 MongoDB 集合中使用索引来做到这一点,但这会使应用 MongoDB 依赖。
有没有人知道是否有任何类型的钩子或任何推荐的方法来做这些事情"the FeathersJS way"?
谢谢!
在大多数情况下,唯一性可以 - 并且应该 - 在数据库或 ORM/ODM 级别得到保证,因为它会给你最好的性能(在大多数情况下不值得为了便携性而牺牲一些东西)。
一种更 Feathers-y 的方式和实现更复杂的限制将是 Feathers hooks which are an important part of Feathers and explained in detail in the basics guide。
在这种情况下,before
挂钩可以查询 total of items and throw an error 是否存在:
const { Conflict } = require('@feathersjs/errors');
app.service('myservice').hooks({
before: {
create: [async context => {
const { fieldA, fieldB } = context.data;
// Request a page with no data and extract `page.total`
const { total } = await context.service.find({
query: {
fieldA,
fieldB,
$limit: 0
}
});
if(total > 0) {
throw new Conflict('Unique fields fieldA and fieldB already exist');
}
return context;
}]
}
})
我正在使用 FeathersJS 和 MongoDB 开发应用程序。我想阻止某些服务创建某些值(或值对)的副本。
例如,使用 feathers-cli 工具创建的 FeathersJS "Authenticate" 服务不会阻止应用程序使用同一电子邮件地址创建 2 个或更多用户(至少使用 MongoDB)。另一个例子是为每个用户创建一些 "categories" 的服务。我希望后端阻止用户创建 2 个或更多具有相同名称的类别,但我需要允许 2 个不同的用户创建他们自己的类别,尽管他们的名称相同(但不是用户)。
我知道我可以通过在 MongoDB 集合中使用索引来做到这一点,但这会使应用 MongoDB 依赖。
有没有人知道是否有任何类型的钩子或任何推荐的方法来做这些事情"the FeathersJS way"?
谢谢!
在大多数情况下,唯一性可以 - 并且应该 - 在数据库或 ORM/ODM 级别得到保证,因为它会给你最好的性能(在大多数情况下不值得为了便携性而牺牲一些东西)。
一种更 Feathers-y 的方式和实现更复杂的限制将是 Feathers hooks which are an important part of Feathers and explained in detail in the basics guide。
在这种情况下,before
挂钩可以查询 total of items and throw an error 是否存在:
const { Conflict } = require('@feathersjs/errors');
app.service('myservice').hooks({
before: {
create: [async context => {
const { fieldA, fieldB } = context.data;
// Request a page with no data and extract `page.total`
const { total } = await context.service.find({
query: {
fieldA,
fieldB,
$limit: 0
}
});
if(total > 0) {
throw new Conflict('Unique fields fieldA and fieldB already exist');
}
return context;
}]
}
})