目的
- firebase functionsをローカル環境でデバッグする。
- 最小の動作する例
環境
friebase 11.24.1
クライアント側
import { getFunctions, httpsCallable, connectFunctionsEmulator } from "firebase/functions";
const app = initializeApp({{環境のキーとか}}); //0)
const functions = getFunctions(app);
getTestCall = () => {
return new Promise(async (resolve) => {
const functions = getFunctions(app, 'us-central1') //<- 1) エミュレータはこの処理を追加(リージョン指定必須)
connectFunctionsEmulator(functions, "localhost", 5001); //<- エミュレータはこの処理を追加
const addMessage = httpsCallable(functions, 'addMessage'); //<-関数名
addMessage({ test: "test" })
.then((result) => {
console.log(result)
console.log(result.data.message)
})
.catch((error) => {
console.log("checkStripeUserById コール失敗");
console.log(error);
});
})
}
functions側
onCallする場合のサンプル
const functions = require('firebase-functions');
exports.addMessage = functions.https.onCall((data, context) => {
functions.logger.log(" 呼び出し=============", data);
console.log("test " + data)
return { message: "test" };
})
起動
{{firebase init等は済み}}
firebase emulators:start --only functions
2)
ポイント
- '0) 実行環境
- クライアントは接続プロジェクトをAPIキーで指定。サーバはローカルで受け止める、1)でプログラム上で明記。
- '1) クライアントコード修正。ローカルのlocalhostに繋ぐようにここで指示する
- '3) http://127.0.0.1:4000/functions のようなものが払い出される。ここでログや、エンドポイントの一覧が確認可能になる