Firebase Cloud Functions × TypeScript

2 min read読了の目安(約2200字

Firebase CLI インストール

$ npm install -g firebase-tools

Firebase ログイン

$ firebase login

Firebase Cloud Functions

$ firebase init functions

ESLintパッケージ インストール

$ npm install --save-dev eslint @typescript-eslint/eslint-plugin @typescript-eslint/parser prettier eslint-config-prettier eslint-plugin-prettier

.eslintrc.json

{
  "extends": [
    "eslint:recommended",
    "plugin:@typescript-eslint/eslint-recommended",
    "plugin:@typescript-eslint/recommended",
    "plugin:prettier/recommended",
    "prettier/@typescript-eslint"
  ],
  "plugins": [
    "@typescript-eslint"
  ],
  "env": { "node": true, "es6": true },
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
    "sourceType": "module",
    "project": "./tsconfig.json"
  },
  "rules": {
  }
}

Linter 実行

$ npm run lint:fix
$ npm run lint

onUpdate関数

import * as functions from "firebase-functions";
import * as admin from "firebase-admin";

/**
cloudFirestore 設定
*/
admin.initializeApp(functions.config().firebase);
const f = functions.region("us-central1");

/**
onUpdate関数 設定
*/
export const onUpdate =
  f.firestore.document("test/test1")
      .onUpdate(async (change, context) => {
        const data = change.after.data();
        const sample = data.sample;

        const ansRef = sample.replace(/\r?\n/g, "");

        return change.after.ref.set({
          sample: ansRef,
        }, {merge: true});
      });

デプロイ

$ npm run deploy

参考文献