羽毛调用自定义API方法 [英] Feathers calling custom API method
问题描述
我用下面的内容定义我的api:
I define my api with something like the below:
class MyFeathersApi {
feathersClient: any;
accountsAPI: any;
productsAPI: any;
constructor(app) {
var port: number = app.get('port');
this.accountsAPI = app.service('/api/accounts');
this.productsAPI = app.service('/api/products');
}
findAdminAccounts(filter: any, cb: (err:Error, accounts:Models.IAccount[]) => void) {
filter = { query: { adminProfile: { $exists: true } } }
this.accountsAPI.find(filter, cb);
}
当我想使用数据库适配器方法时,从客户端,即查找和/或创建,我执行以下操作:
When I want to use database adapter methods, from the client, i.e. find and/or create, I do the below:
var accountsAPIService = app.service('/api/accounts');
accountsAPIService.find( function(error, accounts) {
...
});
我如何从客户端调用自定义方法,例如findAdminAccounts()?
How I call custom methods, such as findAdminAccounts() from the client?
推荐答案
您只能使用客户端上的普通服务接口。我们发现对自定义方法的支持(以及它带来的所有问题,从明确定义的接口到任意方法名称和参数)并不是必需的,因为它本身可以被描述为资源(服务)。
You can only use the normal service interface on the client. We found that support for custom methods (and all the issues it brings with it going from a clearly defined interface to arbitrary method names and parameters) is not really necessary because everything in itself can be described as a resource (service).
到目前为止,好处(如安全性,可预测性和发送明确定义的实时事件)在概念化应用程序逻辑时大大超过了所需思维的微小变化。
The benefits (like security, predictability and sending well defined real-time events) so far have heavily outweighed the slight change in thinking required when conceptualizing your application logic.
在你的例子中,你可以创建一个包装服务来获取这样的管理员帐户:
In your example you could make a wrapper service that gets the admin accounts like this:
class AdminAccounts {
find(params) {
const accountService = this.app.service('/api/accounts');
return accountService.find({ query: { adminProfile: { $exists: true } } });
}
setup(app) {
this.app = app;
}
}
app.use('/api/adminAccounts', new AdminAccounts());
或者你可以实现 hook 将查询参数映射到更大的查询,如下所示:
Alternatively you could implement a hook that maps query parameters to larger queries like this:
app.service('/api/accounts').hooks({
before: {
find(hook) {
if(hook.params.query.admin) {
hook.params.query.adminProfile = { $exists: true };
}
}
}
});
现在可以调用类似 / api / accounts?admin
。
有关详细信息,请参阅此常见问题解答。
For more information see this FAQ.
这篇关于羽毛调用自定义API方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!