LoopBack:如何在代码中动态创建自定义REST端点(即时) [英] LoopBack: How to Dynamically Create Custom REST Endpoints In Code (On The Fly)
问题描述
问题:我们如何动态创建自定义REST端点代码(即时),而不将模型写入光盘上的JSON文件?
您可以在模型的JS文件中创建远程方法,这样在运行时添加API钩子,尽管它在启动时。也就是说,我想你可以使用相同的功能来添加任何时候的端点,而不仅仅是在启动时(尽管我从未尝试过):
Inside /common/models/MyModel.js
module.exports = function(MyModel) {
//这是创建端点的端点...
MyModel.addEndpoint = function(name,method,cb){
// audit name and method ..
MyModel [name] = function(options,newCb){
//做任何这个端点应该做的...
newCb(null,'新的端点成功! );
};
MyModel.remoteMethod(
name,
{
接受:[{arg:'options',type:'object'}],//或者你需要...
返回:{arg:'message',键入:'string'},//无论它返回...
http:{动词:方法}
}
);
cb(null,'创建新的端点!');
};
MyModel.remoteMethod(
'addEndpoint',
{
接受:[
{arg:'name',type:'string',http :{source:'body'}},
{arg:'method',type:'string',http:{source:'body'}}
],
返回: arg:'message',键入:'string'},
http:{动词:'post'}
}
);
};
We are using the LoopBack REST framework to expose our database (and business logic). We need to allow our customers to create custom tables in the database (single and multi-tenant) which can be accessed via a REST endpoint. All customers need to use the same common (production) REST endpoints which will be on exposed on multiple servers. However, custom tables and associated REST endpoints need to be accessible to only the customers that created them. Which means we cannot write the model for custom tables to disc. We need to be able to create an actual REST endpoint on the fly within the context of our production REST endpoints.
Question: How can we dynamically create custom REST endpoints in-code (on the fly) without writing the model to a JSON file on-disc?
You can create a "remote method" within a model's JS file, this adds the API hook "at runtime", although it is at startup. That said, I think you could use the same functions to add the endpoint any time, not just at startup (although I've never tried):
Inside /common/models/MyModel.js
module.exports = function(MyModel){
// This is the endpoint for creating endpoints...
MyModel.addEndpoint = function(name, method, cb) {
// audit name and method...
MyModel[name] = function(options, newCb) {
// do whatever this endpoint should do...
newCb(null, 'New endpoint success!');
};
MyModel.remoteMethod(
name,
{
accepts: [{arg: 'options', type: 'object'}], // or whatever you need...
returns: {arg: 'message', type: 'string'}, // whatever it returns...
http: {verb: method}
}
);
cb(null, 'Success creating new endpoint!');
};
MyModel.remoteMethod(
'addEndpoint',
{
accepts: [
{arg: 'name', type: 'string', http: {source: 'body'}},
{arg: 'method', type: 'string', http: {source: 'body'}}
],
returns: {arg: 'message', type: 'string'},
http: {verb: 'post'}
}
);
};
这篇关于LoopBack:如何在代码中动态创建自定义REST端点(即时)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!