GCPのCloud Functionsを使ってみるために、まずはローカルで実行する方法を調べてみた。
ファイル作成
index.jsという名前のファイルで実行されたときに、Hello, Worldというテキスト返す関数を作成する
exports.xxxのxxxが関数名になる
exports.helloWorld = (req, res) => {
res.send('Hello, World');
};
ライブラリインストール
$ npm install @google-cloud/functions-framework
$ yarn add @google-cloud/functions-framework
実行コマンドはfunctions-framework --target=xxx。
package.jsonのscriptsに書いておくと便利です。
"scripts": {
"start": "functions-framework --target=helloWorld"
}
実行
$ yarn run start
Serving function...
Function: handler
URL: http://localhost:8080/
ここにリクエストを送信すると関数が実行される
$ curl localhost:8080
> Hello, World
もしコマンド(functions-framework --target=xxx)実行時にこんなエラーが発生したらポートがすでに使用されているので別のポートを使用するオプションを付ける
Error: listen EADDRINUSE: address already in use :::8080
functions-framework --target=xxx --port=8888
参照:https://cloud.google.com/functions/docs/functions-framework?hl=ja