| ページ一覧 | ブログ | twitter |  書式 | 書式(表) |

MyMemoWiki

Cloud Functions

提供: MyMemoWiki
2020年11月9日 (月) 14:04時点におけるPiroto (トーク | 投稿記録)による版 (→‎Expressと統合)
(差分) ← 古い版 | 最新版 (差分) | 新しい版 → (差分)
ナビゲーションに移動 検索に移動

| Google Cloud Platform | Firebase |

Cloud Functions

ローカル実行

  • Firebase エミュレータを呼び出す

**package.json で定義された、firebase emulators:start を実行

  1. $ npm install -g firebase-tools
  2. $ cd functions
  3. $ npm run serve

Expressと統合

  1. $ npm install --save express
  2. $ npm install --save-dev @types/express
  • index.ts
  1. import * as functions from 'firebase-functions';
  2. import * as express from 'express';
  3. const app: express.Express = express();
  4.  
  5. const router: express.Router = express.Router()
  6. app.use(router);
  7.  
  8. router.post('/test', (req, res) => {
  9. res.send('TEST!');
  10. });
  11.  
  12. export const api = functions.https.onRequest(app);

https.onCall のプロトコル仕様

  • https://firebase.google.com/docs/functions/callable-reference
  • 呼び出し可能なトリガー エンドポイントへの HTTP リクエストは、次のヘッダーが含まれる POST にする必要があります。
    • 必須: Content-Type: application/json
    • 省略可: Authorization: Bearer <token>:リクエストを行うログイン済みユーザーの Firebase Authentication ユーザー ID トークンです。このトークンはバックエンドで自動的に検証され、ハンドラの context で使用可能になります。トークンが有効でない場合、リクエストは拒否されます。
    • 省略可: Firebase-Instance-ID-Token: <iid>:Firebase クライアント SDK の FCM 登録トークンです。これには文字列を設定する必要があります。またハンドラの context で使用できます。プッシュ通知のターゲティングに使用されます。

カスタムドメイン

  1. Hostingと併用することで対応
  2. Hostingに対してカスタムドメインを設定
  3. firebase.json の hosting の rewrite に functions を追加
  • Functions
  1. import * as functions from 'firebase-functions';
  2. import * as express from 'express';
  3.  
  4. const app: express.Express = express();
  5.  
  6. router.get('/api/test', (req, res) => {
  7. res.send('TEST!');
  8. });
  9.  
  10. export const apiService = functions.https.onRequest(app);
  • firebase.json
    • パスもapi、公開(export)する関数も apiだと、パスにマッチしないため、別の名前にする
  1. "hosting": [
  2. {
  3. : 省略
  4. "rewrites": [
  5. {
  6. "source": "/api/**",
  7. "function": "apiService"
  8. },
  9. {
  10. "source": "**",
  11. "destination": "/index.html"
  12. }
  13. ]
  14. }
  15. ]
  • 実行

Functions custom domain.png