LoginSignup
22
17

More than 3 years have passed since last update.

[JavaScript]Firebase Cloud Functionsにおける関数ごとのファイル分割テンプレート

Last updated at Posted at 2019-03-17

やること

FirebaseのCloud Functionsで関数ごとにファイルを分割して管理しやすくしたい.
すでにJSだけでなく様々な言語でも提案されてきた内容ですが,JSで使い回せるテンプレートをまとめたいと思います.

どうするか

論よりコードです.

ディレクトリ図

functions/
 ├ index.js
 ├ src/
 │ └ hoge-function.js
  ...

コード

index.js
const admin = require('firebase-admin');
admin.initializeApp();

const functions = {
  // Write function references
  hogeFunction: './src/hoge-function',
};

loadFunctions = (funcs) => {
  for (let name in funcs) {
    if (!process.env.FUNCTION_NAME || process.env.FUNCTION_NAME === name) {
      exports[name] = require(funcs[name]);
    }
  }
};

loadFunctions(functions);

src/hoge-function.js
const functions = require('firebase-functions');
const admin = require('firebase-admin');

module.exports = functions.https.onRequest((req, res) => {
  if (req.body.message === undefined) {
    // This is an error case, as "message" is required
    res.status(400).send('No message defined!');
  } else {
    // Everything is ok
    console.log(req.body.message);
    res.status(200).end();
  }
})

index.jsからhoge-function.jsを呼び出すという一般的な構造です.
ここにfirebaseのモジュールへの参照を追加しています.

関数を追加する場合は,srcフォルダ内にファイルを追加し,hoge-function.jsと同様のフォーマットで関数を記述します.その後,index.jsのfunctionsに参照を追加します.

注意点

admin.initializeApp関数は複数ファイルで呼び出すとエラーが発生するため,大元のindex.jsでのみ呼び出します.
関数を記述するファイルでは呼び出さないようにしてください.

参考

ほとんどの内容を参考にさせていただきました.ありがとうございます.

さいごに

料金に注意しつつ,Cloud Functionsを堪能しよう!

22
17
2

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
22
17