【问题标题】:Remote method doesn't show up in loopback API explorer远程方法未显示在环回 API 资源管理器中
【发布时间】:2019-01-08 23:24:42
【问题描述】:

我有一个将 userId 映射到 roleId 的角色映射模型,我需要角色映射模型上的远程方法来检索给定 userId 的 role-mappingId。

这是 remoteMethod 的代码

'use strict';

module.exports = function(Rolemapping) {
   Rolemapping.getRolesByUser = async function (id, cb) {
    const roleMappings = await Rolemapping.find({ where: { principalId: id 
 } })
    cb(null, roleMappings);
  };
  Rolemapping.remoteMethod("getRolesByUser", {
    http: {
      path: "/getRolesByUser",
      verb: "get"
    },
    accepts: [
      { arg: "userId", type: "string", http: { source: "query" } }
    ],
    returns: {
      arg: "result",
      type: "string"
    },
    description: "Cvs "
  });
 };

这是角色映射 json 文件:

{
  "name": "roleMapping",
  "base": "RoleMapping",
  "idInjection": true,
  "options": {
  "validateUpsert": true
},
   "properties": {},
   "validations": [],
   "relations": {
   "role": {
   "type": "belongsTo",
   "model": "role",
   "foreignKey": "roleId"
 }
 },
   "acls": [],
   "methods": {}
 }

上述远程方法未显示在环回 API 资源管理器中。

【问题讨论】:

    标签: javascript node.js loopbackjs


    【解决方案1】:

    RoleMapping 是一个内置模型,它的role-mapping.js 文件隐藏在node_modules/loopback 中,我已经测试过它看起来不会从common/models 为自己加载一个js 文件。

    看起来启动脚本是您唯一的选择。这是相同的代码,但您的函数接收服务器对象。

    server/boot/get-roles-by-user.js

    module.exports = function(server) {
      const Rolemapping = server.models.RoleMapping;
      Rolemapping.getRolesByUser = async function (id) {
        return JSON.stringify(await Rolemapping.find({ where: { principalId: id
          } }))
      };
      Rolemapping.remoteMethod("getRolesByUser", {
        http: {
          path: "/getRolesByUser",
          verb: "get"
        },
        accepts: [
          { arg: "userId", type: "string", http: { source: "query" } }
        ],
        returns: {
          arg: "result",
          type: "string"
        },
        description: "Cvs "
      });
    }
    

    我还从您的远程方法中删除了 cb 参数,因为返回 Promise 的方法不需要它,只需像任何其他函数一样返回值

    【讨论】:

      猜你喜欢
      • 2021-01-08
      • 1970-01-01
      • 2019-11-19
      • 2015-02-03
      • 2020-05-04
      • 2013-10-01
      • 1970-01-01
      • 2020-09-13
      • 2013-06-30
      相关资源
      最近更新 更多