如何为一个 Google Cloud Function 拥有多个 API 端点?

Pra*_*ngh 7 serverless-framework google-cloud-functions

我有一个 Google Cloud Function,其中包含要在不同路径上调用的多个模块。

我正在使用无服务器框架来部署我的函数,但它有每个函数只能有一个路径的限制。

我想在一个函数中使用多个路径,就像在 AWS 无服务器框架中一样。

假设user云函数有两条/user/add路径/user/remove;两个路径都应该调用相同的函数。

像这样的东西:

serverless.yml

functions:
  user:
    handler: handle
    events:
      - http: user/add
      - http: user/remove
Run Code Online (Sandbox Code Playgroud)

如何为一个 GCF 提供多个 API 端点?

Pra*_*ngh 4

是的,确实没有实际的 REST 服务来支持 Google Cloud Functions。它使用开箱即用的 HTTP 触发器。

为了快速解决问题,我使用请求负载来确定要执行的操作。在正文中,我添加了一个名为 的键"path"

例如,考虑函数 USER。

添加用户:

{
  "path":"add",
  "body":{
    "first":"Jhon",
    "last":"Doe"
  }
}
Run Code Online (Sandbox Code Playgroud)

删除用户:

{
  "path":"remove",
  "body":{
    "first":"Jhon",
    "last":"Doe"
  }
}
Run Code Online (Sandbox Code Playgroud)

如果你的操作是纯粹的CRUD,你可以使用request.methodwhich提供诸如GET, POST, PUT, 之类的动词DELETE来确定操作。