将自定义对象定义为输入& Loopback模型的输出

时间:2017-07-06 08:07:28

标签: node.js loopbackjs


我是node.js的新手,尝试使用loopback框架创建一组API。我的要求是接受JSON作为我的API的输入,并且我试图在模型JSON文件中定义相同的内容。根据官方文档,loopback支持object类型作为参数类型,但我不知道在哪里可以定义JSON对象结构。有人可以让我知道如何做到这一点? 该模型的相关片段如下:

"retrieveProfile": {
        "description": "Returns back a particular entity's profile details",
        "isStatic": true,
        "accepts": [
            {
                "arg": "msg",
                "type": "string",
                "http": {
                    "source": "query"
                }
            }
        ],
        "returns": {
            "arg": "greeting",
            "type": "string"
        },
        "http": {
            "verb": "get"
        }
    }

1 个答案:

答案 0 :(得分:0)

我想出了这个。在回送实例中,您可以将自定义对象定义为新模型。

假设您的环回实例中具有以下两个模型(这是伪代码,尚未进行测试,但希望您能理解):

buildings.json

{
  "name": "Buildings",
  "properties": {
    "name": {
      "type": "string"
    },
    "address": {
      "type": "string"
    },
    "rent": {
      "type": "number"
    }
  }
}

tenants.json

{
  "name": "Tenants",
  "properties": {
    "name": {
      "type": "string"
    }
  }
}

确保在model-config.json中声明它们。如果将这些模型连接到数据源,则仍然可以使用,但是不必将它们连接到数据源即可完成此工作。我在model-config.json中声明了它们,然后将数据源设置为null

然后,当您创建远程方法时,您将像这样

buildings.json

{
  "name": "Buildings",
  ...
  "methods": {
    "chargeRent": {
      "accepts": [
        {
          "arg": "tenant",
          "type": "Tenants",
          "required": true
        }
      ],
      "returns": {
        "root": true,
        "type": "object"
      },
      "http": {
        "verb": "post"
      }
    }
  }
}

显然,您可以根据需要配置远程方法,但是最重要的部分是您定义的type与模型名称匹配。

完成此操作后,如果在Loopback API资源管理器中查看此方法,则应该看到文档将自定义对象显示为该端点的参数。而且,根据您如何定义自定义对象的属性(即不要求),如果不包含这些属性,则会抛出错误。

希望这会有所帮助!