LOOPBACK 4:在 API 调用中添加参数

LOOPBACK 4: Add parameters in a API call

我是 Loopback 4 (NodeJS) 的新手,我有一个问题。我正在开发 API。如何在 post 请求的正文中指示未定义为模型的参数?

示例:

@post('/gameshits/{id}', {
    responses: {
      '200': {
        description: 'Return the number of correct answers',
      },
    },
  })
  async gamesHits(
    @param.path.string('id') id: string,
    @requestBody() answers: Array<String>,
  ): Promise<number> {
     ....
}

问题出在requestBody() 它编译但在 loopback/explorer 中表示它可以被渲染。唯一的选择是创建模型?如何添加更多参数以在调用正文中发送? (不像@param那样在url中)

谢谢。

不,你不需要创建一个模型来指示参数,实际上它很容易,但没有太多关于它的文档。

您可以这样指出。

@post('/gameshits/{id}', {
  responses: {
    '200': {
      description: 'Return the number of correct answers',
    },
  },
})
async gamesHits(
  @param.path.string('id') id: string,
  @requestBody({
    content: {
      'application/json': {
        type: 'object',
        schema: {
          properties: {
            gameName: {type: 'string'},
            characters: {
              type: 'array',
              items: {
                properties: {
                  name: {type: 'number'},
                  power: {type: 'number'},
                  cost: {type: 'number'},
                  ability: {type: 'string'}
                },    
              },
            },
          },
        },
      },
    },
  }) data: any,
): Promise<number> {
   ....
}

要获得这样的 loopback/explorer 响应。

{
  "gameName": "string",
  "characters": [
    {
      "name": 0,
      "power": 0,
      "cost": 0,
      "ability": "string"
    }
  ]
}

您不需要任何文档,但需要 swagger 关于描述请求的文档:https://swagger.io/docs/specification/2-0/describing-request-body/?sbsearch=request

然后只需在 @requestBody 装饰器中应用 OpenAPI 规范,如 darkunbeknownst 所述。