LoginSignup
0
0

More than 3 years have passed since last update.

CloudFunctionsのトリガーのファイルを規約化する

Last updated at Posted at 2020-05-22

CloudFunctionのトリガーのファイルを規約化する

下記にてCloudFunctionsのトリガーのディレクトリ設計についてまとめていました。

上記の記事の案2)のケースを元に、規約化するやり方をこの記事ではまとめます。

はじめに

先程の記事の案2)は、こんな感じでファイル名でストレージパスを表現します。

file.png

つまり、下記のようにマッピングしています

  • Firestoreのストレージパス: version/v1/users/{user_id}
  • TypeScriptのディレクトリ設計: ~/version.v1.users.{user_id}.ts

ここで、TypeScript側のファイルはこの命名に従えば規約化されるようなロジックを書きたいです。

では、みていきます。

コード:ファイル名から規約化する

まず、conventer.tsにてファイル名を元にストレージのpathへ変換するメソッドを定義しておきます

conventer.ts
import path from 'path'

export const getStoragePath = (filename: string) =>
  path.basename(filename, '.ts').replace(/\./g, "/");

コード:ファイル名からストレージパスにつなげる

トリガーファンクションで、自分のファイル名を元にFirestoreのファイルパスを導き出すことで規約化します。

こんな感じです。

version.v1.users.{user_id}.ts
import * as functions from "firebase-functions";

import {getStoragePath} from './conventer'

const storagePath = getStoragePath(__filename)
// => version/v1/users/{user_id}

const ref = functions
  .region("asia-northeast1")
  .database.ref(storagePath);

export const onCreate = ref.onCreate((snapshot, context) => {
  // ...
});

シンプルですね。
これで、規約化されました。

0
0
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
0
0