在环回模型中隐藏_all_远程方法

Hiding _all_ remote methods in loopback model

我正在使用环回 3。 我的模型的 js 中有这行代码 (survey.js):

let enabledRemoteMethods = []

Survey.sharedClass.methods().forEach(function(method) {
  console.log(method.name, method.isStatic)
  let matchingEnabledRemoteMethod = _.find(enabledRemoteMethods, {name: method.name});

  if (!matchingEnabledRemoteMethod) {
    Survey.disableRemoteMethodByName(method.name, method.isStatic);
  }
});

它有效....几乎。我仍然可以在资源管理器中看到 "PATCH /surveys/{id}" 的 REST 端点。我的期望是:资源管理器中不应列出任何 REST 端点。

然后我查看了那个操作对应的URL,是:

http://localhost:3000/explorer/#!/Survey/Survey_prototype_patchAttributes

根据文档,这意味着 patchAttributes 是一个静态方法。

然后我与控制台中的输出进行了交叉检查...它说:pathAttributes 是 not static。

前后矛盾!

我什至尝试添加这一行:

Survey.disableRemoteMethodByName("patchAttributes", true);

还有

Survey.disableRemoteMethodByName("patchAttributes", false);

运气不好。

有人可以确认它是否是 loopback 3 中的错误(我不知道 loopback 2,还没有检查过)?如果它是一个错误,我就不必花时间在它上面,只需等到它被修复。但如果这不是错误,有人可以指出我的代码中缺少什么吗?

谢谢!


更新:弄清楚了

用这条线我可以摆脱它:

Survey.disableRemoteMethodByName("prototype.patchAttributes", true);

第二个参数似乎无关紧要(你也可以输入false)。不知道为什么(我想它应该只接受 true )。

这是我目前的解决方案:

let disabledPrototypesRemoteMethods = ['patchAttributes']
let enabledRemoteMethods = [
  "create", "findById", "replaceById", "deleteById",
  "replaceOrCreateQuestion"
]
Survey.sharedClass.methods().forEach(function(method) {
  if (enabledRemoteMethods.indexOf(method.name) == -1) {
    Survey.disableRemoteMethodByName(method.name);
  }

  if (disabledPrototypesRemoteMethods.indexOf(method.name) > -1) {
    Survey.disableRemoteMethodByName("prototype." + method.name);
  }
});

还有一个小细节:这个东西仍然出现(我想它为 replaceById 操作的正常 PUT 提供了 POST 替代方案...,但我不想要它;我想要强制我的 API 用户只使用 PUT):

http://localhost:3000/explorer/#!/Survey/Survey_replaceById_post_surveys_id_replace

我尝试添加这一行:

Survey.disableRemoteMethodByName("replaceById_post_surveys_id_replace");

运气不好。

无论如何...希望这对其他人有用;环回文档有点粗略。


您也可以通过查看 stringName 属性 来获取原型方法。这样您就可以将原型包含在您的列表中。

stringName 值中包含 sharedClass 名称,因此您需要解析它。

module.exports = BusinessProfileContacted => {
  const enabledRemoteMethods = ["create", "findById", "replaceById", "deleteById", "replaceOrCreateQuestion", "prototype.replaceAttributes"];

  Survey.sharedClass.methods().forEach(method => {
    const methodName = method.stringName.replace(/.*?(?=\.)/, '').substr(1);
    if (enabledRemoteMethods.indexOf(methodName) === -1) {
      Survey.disableRemoteMethodByName(methodName);
    }
  });
};