如何设置我的 google 云函数的端点路径(使用无服务器框架)

How to set endpoint path to my google cloud function (using serverless framework)

我正在使用无服务器框架在具有以下配置的 GCP 中部署云函数:

service: myname

provider:
  name: google
  stage: prod
  runtime: nodejs10
  region: us-central1
  project: myname
  credentials: keyfile.json
  environment:
    IS_PROD: 'true'

plugins:
  - serverless-google-cloudfunctions

package:
  exclude:
    - node_modules/**
    - .gitignore
    - .git/**

functions:
  clear:
    handler: clearCommand
    events:
      - http: clear

我正在使用 serverless-google-cloudfunctions 插件版本 3.1.0。部署后,address/path 变为:

https://us-central1-myname.cloudfunctions.net/myname-prod-clear

想知道有没有办法自己设置路径如下:

https://us-central1-myname.cloudfunctions.net/clear

有办法设置吗?首选serverless框架方式

有了serverless框架,好像不行。查看 the source code

中的这一行

deploymentName 是自动生成的,没有参数可以覆盖它。我没有更深入地寻找设置 clear 值的位置,但显然,它是一个静态值。

实际上是您可以在控制台中找到的 Cloud Functions 的名称。如果你自己部署这个功能,你可以选择你想要的名称,从而实现你想要的

link 的最后一部分是 Cloud Functions 名称。创建 Cloud Functions 时已完成,如果您使用 Cloud Console 创建 Cloud Functions,只需引入名称即可。

另一方面,如果您使用 gcloud 部署 Cloud Functions,则必须添加参数名称,例如:

gcloud 函数部署 my_function --runtime=python37 --trigger-event=providers/cloud.firestore/eventTypes/document.write --trigger-resource=projects/project_id/databases/(默认)/documents/messages/{pushId}

这将导致如下结果:

https://us-central1-myname.cloudfunctions.net/[Your_CFName]

考虑到一旦您将 Cloud Functions 命名为 couldn't be changed

可以在serverless.yml中的函数定义中指定name,如中所述。

所以,在你的 serverless.yml 中,它会像下面这样,

functions:
  clear:
    name: clear
    handler: clearCommand
    events:
      - http: clear

但是请注意,在serverless-google-cloudfunctions 3.1.0 版本中,函数名称分配仍然存在问题。部署工作正常,GCP 中部署的函数名称也是正确的。但在 serverless deploy 执行结束时未正确反映在部署状态中。

编辑: 部署状态问题已在 3.1.1 版本中修复。

在早期版本中,我们仍然需要执行以下 hacky 解决方法来手动更新 node_modules 中的 serverless-googlecloudfunctions

info/lib/displayServiceInfo.js中替换当前的getFunctionNameInService函数实现,

const getFunctionNameInService = (funcName, service, stage) => {
  let funcNameInService = funcName;
  funcNameInService = funcNameInService.replace(service, '');
  funcNameInService = funcNameInService.replace(stage, '');
  funcNameInService = funcNameInService.slice(2, funcNameInService.length);
  return funcNameInService;
};

const getFunctionNameInService = (funcName, service, stage) => {
  let funcNameInService = funcName;
  funcNameInService = funcNameInService.replace(`${service}-`, '');
  funcNameInService = funcNameInService.replace(`${stage}-, '');
  return funcNameInService;
};

希望对您有所帮助。