LoopBack:如何在代码中动态创建自定义REST端点(On The Fly)

ASA*_*SA2 2 rest dynamic endpoint strongloop loopbackjs

我们使用LoopBack REST框架来公开我们的数据库(和业务逻辑).我们需要允许客户在数据库(单租户和多租户)中创建可通过REST端点访问的自定义表.所有客户都需要使用相同的公共(生产)REST端点,这些端点将在多个服务器上公开.但是,只有创建它们的客户才能访问自定义表和关联的REST端点.这意味着我们无法将自定义表的模型写入光盘.我们需要能够在生产REST端点的上下文中动态创建实际的REST端点.

问题:我们如何在代码中动态创建自定义REST端点(动态)而无需将模型写入光盘上的JSON文件?

jak*_*lla 5

您可以在模型的JS文件中创建"远程方法",这会在"运行时"添加API挂钩,尽管它在启动时.也就是说,我认为您可以使用相同的功能随时添加端点,而不仅仅是在启动时(尽管我从未尝试过):

/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'}
    }
  );
};
Run Code Online (Sandbox Code Playgroud)