整理多個函式


將 Cloud Functions 整合至專案後,程式碼可能會擴充,包含許多獨立的函式。您可能有太多函式,無法合理地放入單一檔案,或是不同團隊可能部署不同的函式群組,導致某個團隊覆寫或誤刪另一個團隊的函式。Cloud Functions 提供多種程式碼整理方式,方便您瀏覽及維護函式。

整理程式碼集內的函式

您可以使用 firebase.json 中函式設定物件的 codebase 屬性,在單一存放區 monorepo 設定中管理多個存放區或子套件中的大量函式:

# firebase.json
"functions": {
  "codebase": "my-codebase"
  # NOTE: Codebase must be less than 63 characters and can contain only
  # lowercase letters, numeric characters, underscores, and dashes.
}

Firebase CLI 10.7.1 以上版本支援 codebase 屬性。

管理多個存放區

codebase 屬性可協助簡化多個存放區的管理作業。我們來看看以下情境:您有兩個不同的存放區,分別將函式部署至同一個 Firebase 專案:

$  tree .
├── repoA
│   ├── firebase.json
│   └── functions
│       ├── index.js
│       └── package.json
└── repoB
    ├── firebase.json
    └── functions
        ├── index.js
        └── package.json

如果沒有程式碼集註解,Firebase CLI 會在部署時提示您刪除其他存放區中定義的函式:

$ (cd repoA && firebase deploy --only functions)
...
i  functions: preparing functions directory for uploading...
  functions: functions folder uploaded successfully
The following functions are found in your project but do not exist in your local source code:
        fn1FromRepoB
        fn2FromRepoB
        ...
? Would you like to proceed with deletion? Selecting no will continue the rest of the deployments. (y/N)

如要避免這個問題,請在每個專案存放區的 firebase.json 函式設定區段中新增專屬的程式碼庫註解:

# repoA/firebase.json
"functions": {
  "codebase": "repo-a"
}

# repoB/firebase.json
"functions": {
  "codebase": "repo-b"
}

有了程式碼集註解,Firebase CLI 就不會再提示您刪除在當前存放區外定義的函式:

$ (cd repoA && firebase deploy --only functions)
...
i  functions: preparing functions directory for uploading...
  functions: functions folder uploaded successfully
#  Gleefully ignores functions from repoB
i  functions: creating Node.js 16 function fnFromRepoA (us-central1)...
  Deploy Complete!

管理多個來源套件 (單一版本庫)

codebase 屬性可協助簡化單一存放區中多個來源套件的管理作業。我們來看看以下情況:您有一個 Firebase 專案目錄,其中的函式定義分散在多個子套件中:

$  tree .
├── firebase.json
├── teamA
│   ├── index.js
│   └── package.json
└── teamB
    ├── index.js
    └── package.json

這項設定適合下列用途:

  • 您有單一來源檔案庫設定,且不同團隊在獨立套件中管理各自的函式定義。
  • 您有一個具有大量外部依附元件和長時間初始化的函式,且想要將該函式與其他對延遲敏感的函式隔離。

如要支援此類 monrepo 設定,請在 firebase.json 中定義多個函式設定:

"functions": [
  {
    "source": "teamA",
    "codebase": "team-a"
  },
  {
    "source": "teamB",
    "codebase": "team-b"
  },
]

在這種情況下,Firebase CLI 會在單一部署指令中部署所有套件的函式:

$ firebase deploy --only functions
i  deploying functions
i  functions: preparing codebase team-a for deployment
i  functions: preparing codebase team-b for deployment
i  functions: creating Node.js 16 function team-a:helloATeam(us-central1)...
i  functions: creating Node.js 16 function team-b:helloBTeam(us-central1)...
...

您也可以部署特定程式碼集:

$ firebase deploy --only functions:team-b
i  deploying functions
i  functions: preparing codebase team-b for deployment
i  functions: updating Node.js 16 function team-b:helloBTeam(us-central1)...
...

在多個檔案中編寫函式

開始使用 Cloud Functions 時,您可以將前幾個函式放在單一檔案中:

index.js

const functions = require('firebase-functions/v1');
exports.foo = functions.https.onRequest((request, response) => {
  // ...
});
exports.bar = functions.https.onRequest((request, response) => {
  // ...
});

main.py

from firebase_functions import https_fn

@https_fn.on_request()
def foo(req: https_fn.Request) -> https_fn.Response:
    return https_fn.Response("Hello foo!")

@https_fn.on_request()
def bar(req: https_fn.Request) -> https_fn.Response:
    return https_fn.Response("Hello bar!")

但如果有幾個以上的函式,就很難管理。您可以將每個函式的所有邏輯放在各自的檔案中,並使用來源檔案做為匯出清單:

Node.js

foo.js

const functions = require('firebase-functions/v1');
exports.foo = functions.https.onRequest((request, response) => {
  // ...
});

bar.js

const functions = require('firebase-functions/v1');
exports.bar = functions.https.onRequest((request, response) => {
  // ...
});

index.js

const foo = require('./foo');
const bar = require('./bar');
exports.foo = foo.foo;
exports.bar = bar.bar;

Python

foo.py

from firebase_functions import https_fn

@https_fn.on_request()
def foo(req: https_fn.Request) -> https_fn.Response:
    return https_fn.Response("Hello foo!")

bar.py

from firebase_functions import https_fn

@https_fn.on_request()
def bar(req: https_fn.Request) -> https_fn.Response:
    return https_fn.Response("Hello foo!")

main.py

from fn_impl.foo import *
from fn_impl.bar import *

這項設定假設專案目錄結構如下所示:

my-project
├── firebase.json
└── functions
    ├── fn_impl
    │   ├── __init__.py
    │   ├── foo.py
    │   └── bar.py
    ├── main.py
    └── requirements.txt

fn_impl:可使用任何名稱

__init__.py:必要,但可留空

群組函式

在許多專案中,函式可以分為邏輯群組,這些群組應一併部署及維護。舉例來說,您可能會使用一組用於回報指標的函式:

metrics.js


const functions = require('firebase-functions/v1');
exports.usageStats = functions.https.onRequest((request, response) => {
  // ...
});
exports.nightlyReport = functions.https.onRequest((request, response) => {
  // ...
});

您可以在 index.js 檔案中匯出這些函式時,將這些函式放入群組:

index.js


// Export both functions from metrics.js in the "metrics" group:
//  - metrics-usageStats
//  - metrics-nightlyReport
exports.metrics = require('./metrics');

部署時,函式會加上群組名稱做為前置字串,因此在本例中,函式會命名為 metrics-usageStatsmetrics-nightlyReport

部署函式時,您可以將動作限制在單一群組:


firebase deploy --only functions:metrics

後續步驟

如要進一步瞭解 Cloud Functions,請參閱: