【问题标题】:How to use jsonschema for Loopback remoteMethod?如何将 jsonschema 用于 Loopback remoteMethod?
【发布时间】:2014-12-16 13:41:45
【问题描述】:

在我的应用中,我想为自定义 API 定义 JSON 模式。

例如来自:http://docs.strongloop.com/display/public/LB/Remote+methods#Remotemethods-Example

module.exports = function(Person){

    Person.greet = function(msg, cb) {
      cb(null, 'Greetings... ' + msg);
    }

    Person.remoteMethod(
        'greet', 
        {
          accepts: <generate definitions from jsonschema>,
          returns: <generate definitions from jsonschema>
        }
    );
};

怎么做?

这样是对的吗?

我的解决方案 - 验证装饰器 + 带有对象类型的远程方法参数

var validate = require('jsonschema').validate;

bySchema = function (schema) {
  return function (func) {

    return function () {
      var data = arguments[0],
        callback = arguments[1];

      var result = validate(data, schema);

      if (result.errors.length > 0) {
        // some errors in request body
        callback(null, {
          success: false,
          error: 'schema validation error',
        });
        return;
      }
      return func.apply(this, arguments);
    };
  };
};

defaultRemoteArguments = {
  accepts: {
    arg: 'data',
    type: 'object',
    http: function(ctx) {
      return ctx.req.body;
    }
  },
  returns: {
    arg: 'data',
    type: 'object',
    root: true
  }
};

例子:

Auth.login = bySchema(require('<path to shcemajson json for this request>'))
  (function(data, cb) {
    // process request
  });
Auth.remoteMethod('login', defaultRemoteArguments);

在此解决方案中,contrib loopback explorer 将没有用,因为请求/响应是对象,而不是字段...

【问题讨论】:

    标签: jsonschema loopbackjs strongloop


    【解决方案1】:

    正确的做法是将returns属性中的type设置为模型名称。 在你的情况下,你会写:

    Person.remoteMethod(
            'greet', 
            {
              ...
              returns: {type:'Person', ...}
            }
        );
    

    【讨论】:

      【解决方案2】:

      您需要修改输出以匹配returns 属性接受的格式。

      ...
      returns: [{arg: "key1", type: "string"}, {arg: "key2", type: "object"}, ...];
      ...
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多