google cloud function file structure
/ 2 min read
Table of Contents
如果使用 google 手冊上 sample 的寫法,會發現到這坨 functions
都是寫在 index.js 裡面,真的很難維護。
起因
在開發 cloud function 的時候,通常都會先參考官方的手冊,但是官方的手冊絕大部分都是 sample
,有時候很不好套用在真實的開發環境上。
像是 google 手冊上 sample 的寫法, 是將所有的 functions
寫進 index.js
裡面,
但是這在多人開發的時候就會冒出問題了,總不能等夥伴開發完了之後,再換你開發;又或者大家一起進入到 git 的 merge 地獄。
解決方式
index.js
'use strict';
const admin = require("firebase-admin");const functions = require("firebase-functions");
const glob = require("glob");const files = glob.sync('./**/*.function.js', { cwd: __dirname });const fileLength = files.length;
// initialize appadmin.initializeApp(functions.config().firebase);
for (let f = 0; f < fileLength; f ++) { const file = files[f]; const functionName = file.split('/').pop().slice(0, -12); // Strip off '.function.js'
if (!process.env.FUNCTION_NAME || process.env.FUNCTION_NAME === functionName) { exports[functionName] = require(file); }}
file structure
├── index.js├── package-lock.json├── package.json└── src ├── database │ ├── dmError-write │ │ └── deleteMessagesAndSecretWhenDmError.function.js │ ├── messages-update │ │ └── sendPwdToSenderViaDm.function.js │ ├── messsges-write │ │ └── sendMessageToTwitter.function.js │ ├── senders-write │ │ ├── deleteTweet.function.js │ │ └── writeMessagesToDatabase.function.js │ └── tweetError-write │ └── deleteMessagesAndSecretWhenTweetError.function.js └── pubsub └── twitterDmReceived.function.js
這樣子就可以把這些 functions
依照你喜愛的存放方式存放了。