是空

駆け出しエンジニアが学んだことをまとめていくブログ

Google Cloud Functionsをローカルで実行する

公式のドキュメントでは2019年9月4日現在、cloud-functions-emulator をインストールして使うように記載されていますが、cloud-functions-emulatorは現在archiveされており、公式のgithubにて2019年5月16日に作成されたissueによると functions-framework という新しいツールの利用を推奨しています。

なので、functions-frameworkをインストールして使っていきます。

インストール

公式で案内されているのは下記です。

$ npm install @google-cloud/functions-framework

私はYarnを利用しているので下記でインストールしました。

$ yarn add @google-cloud/functions-framework

バージョンについて

node.js v8.10.0でインストールしたところ、

error @google-cloud/functions-framework@1.2.1: The engine "node" is incompatible with this module. Expected version ">=10.0.0". Got "8.10.0"

>=10.0.0ですよーと怒られたのでv10.16.3で入れました。

yarn add v1.17.3
[1/4] 🔍  Resolving packages...
[2/4] 🚚  Fetching packages...
[3/4] 🔗  Linking dependencies...
[4/4] 🔨  Building fresh packages...

success Saved lockfile.
success Saved 28 new dependencies.
info Direct dependencies
└─ @google-cloud/functions-framework@1.2.1
info All dependencies
├─ @google-cloud/functions-framework@1.2.1
├─ accepts@1.3.7
├─ array-flatten@1.1.1
├─ body-parser@1.19.0
├─ content-disposition@0.5.3
├─ cookie-signature@1.0.6
├─ cookie@0.4.0
├─ destroy@1.0.4
├─ ee-first@1.1.1
├─ express@4.17.1
├─ finalhandler@1.1.2
├─ forwarded@0.1.2
├─ ipaddr.js@1.9.0
├─ media-typer@0.3.0
├─ merge-descriptors@1.0.1
├─ methods@1.1.2
├─ mime-db@1.40.0
├─ minimist@1.2.0
├─ negotiator@0.6.2
├─ path-to-regexp@0.1.7
├─ proxy-addr@2.0.5
├─ raw-body@2.4.0
├─ safer-buffer@2.1.2
├─ serve-static@1.14.1
├─ type-is@1.6.18
├─ unpipe@1.0.0
├─ utils-merge@1.0.1
└─ vary@1.1.2
✨  Done in 1.06s.

つらつらーとログが流れて、インストール完了!

確認

index.jsファイルを作成して、nodeサーバーを立ち上げて確認します。

index.js

exports.helloWorld = (req, res) => {
  res.send('Hello, World');
};

index.jsを作ったら、コマンドを叩きます。

$ npx @google-cloud/functions-framework --target=helloWorld
Serving function...
Function: helloWorld
URL: http://localhost:8080/

こんな感じでサーバーが立ち上がったら、http://localhost:8080/を見てみましょう。

functions-frameworkでHello World
functions-frameworkでHello World

無事、Hello Worldできました! Congratulations!

Congratulations! カイジ
Congratulations! カイジ

まとめ

公式のドキュメントも時には疑ってかからなければならないことを学びました。

そして、最新の情報はgithubにあり!

もっと言うと、コードにあり!!

参考: functions-framework を利用したGoogle Cloud Functionsにおいてpubsubのテストをする方法