開発している積読用の読書管理サービスで一部Functionsで処理している部分がある、
https.onRequest()を利用しているが、https.onCall()のほうが早いらしい。
ので、アプリのみから使う関数をhttps.onCall()で実装したときの備忘録。
Nuxt.jsからCloud Functions for FirebaseをonCall経由で呼ぶ例。
onCallの関数はこんな感じ
msgを受け取って、msgを返す、echo的な関数の例。
公式ドキュメントでの説明はこちら。
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
exports.echo = functions.https.onCall(async (data, context) => {
// 引数の取得
const msg = data.msg;
// 認証情報の取得
const uid = !!context.auth ? context.auth.uid : "";
console.info(`uid=${uid}, msg=${msg}`);
// 返り値の返却
return { msg: msg }
});
context.authで認証情報を取得できるので、
関数を呼べるユーザを制限もできる。
作ったonCall関数をアプリから呼ぶ
こんな感じ。
こんなファイルを用意しておいて、await doEcho()を呼べば、
onCall経由でFunctionsの関数を呼ぶことができる。
import * as firebase from "firebase/app";
import "firebase/functions";
// firebaseの初期化。
if (!firebase.apps.length) {
const config = "...";
if (config) firebase.initializeApp(config);
}
// functionsのインスタンスを取得
const functions = firebase.functions();
export default async function doEcho(msg:string): Promise<string> {
// 作った関数のインスタンスを取得
const func = functions.httpsCallable("echo");
// 作った関数の実行
const res = await func({ msg: "なんかのメッセージ" });
// 返り値のmsgを取得&返却
return res.msg
}
ローカルPCで実行が大変...
作った関数を開発中のアプリから実行するときは、
useFunctionsEmulatorを使うと良い感じ。
こうすると、呼び出される関数のローカルPCに変更できる。
// functionsのインスタンスを取得
const functions = firebase.functions();
if (process.env.NODE_ENV != "productions") {
functions.useFunctionsEmulator("http://localhost:5000");
}
こんな感じで、useFunctionsEmulatorを設定した上で、
-
firebase serve --only functionsでfunctionを立ち上げ -
nuxtでNuxt.jsアプリを立ち上げ
とすると、Nuxt.jsがローカルで立ち上げたFunctionsを参照するようになる。
これで開発するときも安心(´ω`)
おわりに
アプリで使うだけならonCallがはやくてステキ(´ω`)
積読ハウマッチは、Nuxt.js+Firebaseで開発してます!
もしよかったら、遊んでみてくださいヽ(=´▽`=)ノ
要望・感想・アドバイスなどあれば、
公式アカウント(@MemoryLoverz)や開発者(@kira_puka)まで。