手元のPCで開発用に動かしている Firebase HTTPS Callable Function を React Native なんかで動かしてる開発機から呼びたかったときのやつ。onCall 関数というのは、クライアントから直接叩ける Cloud Functions の関数で、プロトコルとしては Content-Type: JSON
の HTTP POST です。
- https.onCall のプロトコルの仕様 Firebase https://firebase.google.com/docs/functions/callable-reference?hl=ja
前提条件
- Cloud Functions を動かすサーバーとアクセスするクライアントが同じLAN内にある(≠ 同じ端末)
- 同じ端末内で両方動かす場合はローカルIPを指定せずに localhost と書けばよい
cloud-functions
import * as functions from 'firebase-functions'
export const echo = functions
.region('asia-northeast1')
.https.onCall(async (data, context) => {
return { data }
})
onCall Function を書く、ここのコードでは東京リージョンを指定している
$ firebase serve --only functions -o 0.0.0.0
-o 0.0.0.0
で Bind Address にワイルドカードを指定して、Cloud Functions を手元で起動する
$ ipconfig getifaddr en0
10.0.1.2
Cloud Functions を起動したIPアドレスを確認する(en0でないかもしれない)
client-app
import firebase from 'firebase'
import 'firebase/functions'
const app = firebase.initializeApp({...})
app.functions().useFunctionsEmulator(`http://10.0.1.2:5000`)
firebase
.functions()
.httpsCallable('echo')()
.then(response => {
console.log(response)
})
app.functions().useFunctionsEmulator(url: string)
に先程のIPアドレスとポートを指定した http の URL をセットする。ポートはデフォルトで 5000
になっているはず。