LoginSignup
14
5

More than 5 years have passed since last update.

同一 LAN 内で firebase serve している onCall 関数を呼び出す

Posted at

手元のPCで開発用に動かしている Firebase HTTPS Callable Function を React Native なんかで動かしてる開発機から呼びたかったときのやつ。onCall 関数というのは、クライアントから直接叩ける Cloud Functions の関数で、プロトコルとしては Content-Type: JSON の HTTP POST です。

前提条件

  • 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 になっているはず。

14
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
5