【问题标题】:How to override the default loopback model API paths如何覆盖默认环回模型 API 路径
【发布时间】:2019-03-03 01:27:51
【问题描述】:

我们如何覆盖默认的环回 REST API 模型端点?例如,我想在调用以下 GET API 时调用名为 list 的自定义模型方法。

我指的是文档https://loopback.io/doc/en/lb2/Exposing-models-over-REST.html

1.来自环回浏览器的API端点:http://localhost:3000/api/Assets

2.Model方法定义:

Asset.list = function(cb) {
    console.log("called");
}

Asset.remoteMethod('list', {
    http: {path: '/'},
    returns: {type: 'Object', root: true}
});

【问题讨论】:

  • 你上面试过了吗?
  • 您是否考虑过使用Model 而不是PersistedModel 作为基础?

标签: node.js express swagger loopbackjs strongloop


【解决方案1】:

您的console.log("called"); 应该只出现在您的终端中,而不是作为您的网络浏览器上的返回 - 这可能是您目前看不到它的原因。

如果你想在你的网络浏览器上看到一些东西,你必须为你的回调返回一个值,比如:

module.exports = function (Asset) {

    Asset.list = function(cb) {
        console.log("called");
        cb(false, {'called': true}); // cb(error, returned value(s));
    }

    Asset.remoteMethod('list', {
        http: {verb: 'get'},
        returns: {type: 'Object', root: true}
    });
}

这个文件应该在你的 common/model/asset.js


在您的 server/model-config.json 中,不要忘记引用您的模型:

     ...
     "Asset": {
        "dataSource": "yourdatasource", //change this by your datasource name
        "public": true
     }
     ...

【讨论】:

  • 同意以上几点,我的列表 API 工作正常。但是,我正在寻找一种方法来覆盖默认的 GET API(请查看帖子附带的屏幕截图)
  • 我不确定您是否可以覆盖默认的 /POST /PUT /GET /PATCH /DELETE,但您可以使用自定义 mixin 删除这些端点并像您一样添加新的端点。
【解决方案2】:

如果您不想使用默认路径(默认方法不使用),您应该在 JSON 模型配置中添加新的远程方法并在 JS 模型文件中定义方法:

"methods": {
  "myCustomMethod": {
    "accepts": [
      {
        "arg": "req",
        "type": "object",
        "http": {
          "source": "req"
        }
      }
    ],
    "returns": [
      {
        "type": "Array",
        "root": true
      }
    ],
    "http": {
      "verb": "GET",
      "path": "/myCustomPath"
    }
  }
}

Candidate.myCustomMethod = (req) => {//method code}

如果您想覆盖默认环回路径(自动生成的方法),您还应该禁用默认方法。

Candidate.disableRemoteMethodByName('find');

所以现在您可以将 JSON 配置“/myCustomPath”更改为“/”,并且您的远程方法将引用您的函数而不是默认值。

【讨论】:

    猜你喜欢
    • 2022-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-09
    • 1970-01-01
    • 2012-07-26
    • 2014-01-21
    相关资源
    最近更新 更多