整理多個函式


將 Cloud Functions 整合到專案中之後,程式碼就能擴展到 包含許多獨立函式您可能有太多函式 或者不同團隊可以部署 造成單一團隊覆寫或意外刪除 另一個團隊的職責。Cloud Functions 提供不同的方式 讓瀏覽及維護函式更方便。

整理程式碼集中的函式

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

# 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 v10.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

這種設定適合下列用途:

  • 您擁有 monorepo 設定,而且在獨立的套件中,由不同團隊管理自己的函式定義。
  • 您有一個函式具有繁重的外部依附元件,而且需要長時間執行初始化作業,並想將該函式與其他易受延遲影響的函式分開。

如要支援這類 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');
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');
exports.foo = functions.https.onRequest((request, response) => {
  // ...
});

bar.js

const functions = require('firebase-functions');
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');
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,請參閱: