GAミント至上主義

Web Monomaniacal Developer.

Firebase Functions + TypeScriptで複数リージョン指定する方法

デフォルトでus-central1で動くFirebase Functionsですが、やっぱりネットワークでレスポンス遅くなるので日本でも動かしたいなと思ってやってみたら下記のエラーが起きたのでメモ。

Cloud Functions のロケーション  |  Firebase

functions.region() でカンマ区切りの複数のリージョン文字列を渡すことで、複数のリージョンを指定できます。推奨手順の詳細については、関数のリージョンを変更するをご覧ください。

「カンマ区切りの複数のリージョン文字列」って'us-central1,asia-northeast1'だろって思って書いたのが下記。

# だめだったコード1
export const example = functions
  .region('us-central1,asia-northeast1')
  .https
  .onRequest(app)

エラー内容↓

Error: The only valid regions are: us-central1, us-east1, us-east4, europe-west1, europe-west2, europe-west3, asia-east2, asia-northeast1

TypeScriptでビルドできません。

試しにregionをつなげて見たところ、ビルドは通るものの、ローカルエミュレータでは後ろのasia-northeast1しか起動していないもよう。

# だめだったコード2
export const example = functions
  .region('us-central1')
  .region('asia-northeast1')
  .https
  .onRequest(app)

落ち着いてVS Codeで型定義を見てみると・・・

(method) FunctionBuilder.region(...regions: ("us-central1" | "us-east1" | "us-east4" | "europe-west1" | "europe-west2" | "europe-west3" | "asia-east2" | "asia-northeast1")[]): functions.FunctionBuilder

なんかよくわからない・・・。

リファレンスを見たらExampleがありました。こっちを最初にみるべきだった。
https://firebase.google.com/docs/reference/functions/function_builder_.functionbuilder#region

Example
functions.region('us-east1')

Example
functions.region('us-east1', 'us-central1')

# OKなコード
export const example = functions
  .region('us-central1', 'asia-northeast1')
  .https
  .onRequest(app)

あいまいな「カンマ区切りの複数のリージョン文字列」という説明に振り回されただけだった。

でも、ここまで来たら型定義も"us-central1" 、"us-east1"等の配列を「...」で展開したものっていうのがわかった。

結局ローカルエミュレーターは最初の一つのリージョンしか起動しなかったけど、firebase deployしたところ無事2つ生えました。

Step #3 - "Deploy to Firebase": i  functions: creating Node.js 10 function example(asia-northeast1)...
Step #3 - "Deploy to Firebase": i  functions: updating Node.js 10 function example(us-central1)...


プログラミングTypeScript ―スケールするJavaScriptアプリケーション開発

プログラミングTypeScript ―スケールするJavaScriptアプリケーション開発

  • 作者:Boris Cherny
  • 発売日: 2020/03/16
  • メディア: 単行本(ソフトカバー)