在没有环回的情况下使用环回数据源和模型

Using Loopback datasources & models without loopback

我设想 loopback 的数据源和模型是 消费 和 API 的有用工具,而不仅仅是自动 创建 一个 REST API.

假设我正在使用 Spotify 的 API。我想要一个在 Spotify 上查找用户信息的命令行应用程序。我可以编写 loopback 个模型来消耗 /v1/albums.

我希望我可以创建一个 Album 模型并像 Album.find('Thriller'); 一样使用它。

想要的是创建一个 REST API。我只是想要一种更好的语言来消费其他人的 API,例如 FacebookInstagram

LoopBack 模型只是一个配置文件和模型文件中的函数集合。所有端点都是由 LoopBack 本身生成的,因此它们本身并不是很有用。也就是说,您 可以 使用 explorer component 为每个模型生成一个 swagger 规范(当您使用脚手架 CLI 时默认安装:slc loopback)。

只需启动您的 LoopBack 应用程序,然后导航至:

http://localhost:3000/explorer/resources/MyModels

然后您可以在支持该标准的任何框架中使用 swagger 规范。

一个好的方法是使用他们的 rest-connector,它允许您将请求和响应调用模板化到外部 API,对返回的数据使用模型验证,然后允许您坚持将新内容添加到您的数据库中。

环回有non-database connectors, including a REST connector的概念。来自文档:

LoopBack supports a number of connectors to backend systems beyond databases.

These types of connectors often implement specific methods depending on the underlying system. For example, the REST connector delegates calls to REST APIs while the Push connector integrates with iOS and Android push notification services.

这是改编自 Spotify 的文档(虽然我还没有尝试过):

datasources.json

Album": {
  "name": "spotify",
  "connector": "rest",
  "debug": false,
  "options": {
    "headers": {
      "accept": "application/json",
      "content-type": "application/json"
    },
    "strictSSL": false
  },
  "operations": [
    {
      "template": {
        "method": "GET",
        "url": "https://api.spotify.com/v1/albums/",
        "query": {
          "album": "{album}"
        },
        "options": {
          "strictSSL": true,
          "useQuerystring": true
        }
      },
      "functions": {
        "find": ["album"]
      }
    }
  ]
}

然后您可以通过以下代码调用此 api:

app.dataSources.Album.find('thriller', processResponse);