如何在 Strongloop 上为自定义远程方法设置自定义架构

How to set custom schema for custom remote methods on Strongloop

我是 Strongloop 的新手,我找不到有关如何自定义我的响应的信息 class(我构建的对象的模型模式),我不知道如何在 API 使用自定义数据探索对象。

例如,我有一个名为 score 的自定义远程方法

POST /Challenges/score

我想为参数 data 显示一个自定义模型架构而不是单个参数,而不是挑战模型架构,主体上的数据具有所有参数并在数据上显示给用户类型:模型架构,这可能吗?

{
  "id": "string",
  "limit": 0,
  "order": "string",
  "userId": "string"
}

另一方面,在 Response Class 中,我想显示响应对象的架构。像这样:

{
  "id":"string",
  "userId":"string",
  "user": {},
  "totalScore":0,
  "tags": []
}

我看了不同的问题 ( and ),但找不到解决这个问题的方法。

更新

这里是远程方法的定义

Challenge.remoteMethod('score', {
    accepts: { arg: 'data', type: 'object', http: { source: 'body' } },
    returns: {arg: 'scores', type: 'array'},
    http: {path: '/score', verb: 'post'}
});

相信你可能已经看过strongloop的官方文档了。如果没有,这里是 link 解释远程方法及其接受的数据类型。 https://docs.strongloop.com/display/public/LB/Remote+methods

假设您的自定义对象是 Challenge,要在响应中显示对象,您必须指定类型(该类型可以是环回的数据类型之一或您的自定义模型)。因此,对于 return Challenge 你必须添加以下代码:

Challenge.remoteMethod('score', {
    accepts: { arg: 'data', type: 'object', http: { source: 'body' } },
    returns: {arg: 'scores', type: 'Challenge', root: true},
    http: {path: '/score', verb: 'post'}, 
});

您指定的第二个箭头是您要在 API 调用中尝试的默认值。您可以传递任何以 default 作为键的自定义字符串。 例如,如果你想传递一些对象:

Challenge.remoteMethod('score', {
    accepts: {
        arg: 'data',
        type: 'object',
        default: '{
            "id": "string",
            "userId": "string",
            "user": {},
            "totalScore": 0,
            "tags": []
        }',
        http: {
            source: 'body'
        }
    },
    returns: {
        arg: 'scores',
        type: 'Challenge'
    },
    http: {
        path: '/score',
        verb: 'post'
    }
});

因此,对于响应,您无法自定义模型。但要传递默认值,您可以将任何内容放入字符串格式。

我发现解决这个问题的方法是用这种方式创建一个新模型,用助手 slc loopback: model

? Enter the model name: ArgChallenge
? Select the data-source to attach ArgChallenge to: (no data-source)
? Select model's base class PersistedModel
? Expose ArgChallenge via the REST API? No
? Common model or server only? server

然后我继续添加属性,然后在 Challenge.js:

Challenge.remoteMethod('score', {
    accepts: { arg: 'data', type: 'ArgChallenge', http: { source: 'body' } },
    returns: {arg: 'scores', type: 'array'},
    http: {path: '/score', verb: 'post'}
});

这很有效!如果有人知道更好的方法,请分享。

@jrltt,不要使用 default,而是使用指向 type under accepts 的对象结构] 它应该可以工作。注意,需要http source:body

随机对象:

Challenge.remoteMethod('score', {
    accepts: {
        arg: 'data',
        type: {
            "id": "string",
            "userId": "string",
            "user": {},
            "totalScore": 0,
            "tags": []
          },
        http: {
            source: 'body'
        }
    },
    returns: {
        arg: 'scores',
        type: 'Challenge'
    },
    http: {
        path: '/score',
        verb: 'post'
    }
});

使用模型配置中可用的定义模型或使用环回模型生成器创建,然后该模型名称可用于指向类型。 所以让我们使用 User 模型来显示接受参数,

Challenge.remoteMethod('score', {
    accepts: {
        arg: 'data',
        type: 'User',
        http: {
            source: 'body'
        }
    },
    returns: {
        arg: 'scores',
        type: 'Challenge'
    },
    http: {
        path: '/score',
        verb: 'post'
    }
});

在环回中,远程参数可以识别使用ds.define('YourCustomModelName', dataFormat);

定义的数据模型

所以对于你的情况,在 Challenge.js 文件中写一个函数,它将有一个远程方法(在你的情况下 score) 已定义。

const loopback = require('loopback');
const ds = loopback.createDataSource('memory'); 
module.exports = function(Challenge) {
  defineChallengeArgFormat() ;
 // remote methods (score) defined
};

let defineChallengeArgFormat = function() {
  let dataFormat = {
            "id": String,
            "userId": String,
            "user": {},
            "totalScore": Number,
            "tags": []
        };
  ds.define('YourCustomModelName', dataFormat);
};

在远程参数类型下使用 'type': 'YourCustomModelName'

    Challenge.remoteMethod('score', {
        accepts: {
            arg: 'data',
            type: 'YourCustomModelName',
            http: {
                source: 'body'
            }
        },
        returns: {
            arg: 'scores',
            type: 'Challenge'
        },
        http: {
            path: '/score',
            verb: 'post'
        }
    });

重启服务器并刷新后,您应该会在资源管理器中看到它:)

我找到了一种通过更改接受数组中的类型参数来解决此问题的方法。 当我们创建 remoteMethod 时;我们提供接受数组。有 arg,类型,必需,http。然后我们可以将请求对象放入 type 参数中。

示例代码

UserModel.remoteMethod(
 'login',
  {
    description: 'Login a user with username/email and password.',
    accepts: [
      {
        arg: 'credentials',
        type: {'email': 'string', 'password': 'string'},
        required: true,
        http: {source: 'body'},
      },
      {
        arg: 'include', type: ['string'], http: {source: 'query'},
        description: 'Related objects to include in the response. ' +
          'See the description of return value for more details.',
      },
    ],
    returns: {
      arg: 'accessToken', type: 'object', root: true,
      description:
        g.f('The response body contains properties of the {{AccessToken}} created on login.\n' +
          'Depending on the value of `include` parameter, the body may contain ' +
          'additional properties:\n\n' +
          '  - `user` - `U+007BUserU+007D` - Data of the currently logged in user. ' +
          '{{(`include=user`)}}\n\n'),
    },
    http: {verb: 'post'},
  },
);