我可以制作仅适用于本地 Firebase 模拟器的 Cloud Function 吗?

can I make a Cloud Function that only for local Firebase Emulators?

我需要制作一个仅用于 Firebase 模拟器的功能。我需要对我的 Firestore 模拟器执行一些操作,以使用虚拟数据填充 Firestore 模拟器。

我在 index.ts

中写了这段代码
exports.onlyForFirebaseSimulator = functions.https.onRequest(async (req, res) => {
  
  
});

我想在 运行 firebase emulators:start 时启用此功能,但在 运行 firebase deploy.[=14= 时它不会部署到生产环境中]

我必须在部署前手动将其注释掉。我不想手动设置它,因为它很容易出错。

如果您使用 Firebase CLI deploy command you could select only the functions to deploy to production by specifying the --only flag as explained on the relevant sections of the docs 进行部署:例如如果您有三个名为 addMessage、makeUppercase 和 onlyForFirebaseSimulator 运行 的函数,则以下命令:

firebase deploy --only functions:addMessage,functions:makeUppercase

不会将您的 onlyForFirebaseSimulator 部署到生产环境。

我想我找到了答案。

我在我的index.ts中使用group functions来组织多个函数,建议你先阅读它,否则你看我的index.ts会很困惑。我正在使用 Typescript/ES6,但概念相同

对于'normal'部署,在index.ts中会是这样

// Firestore triggers
export * as users from "./firestore/triggers/users/users_triggers";
export * as users_attendedEvents from "./firestore/triggers/users/attendedEvents/attended_events_triggers";
export * as users_followers from "./firestore/triggers/users/followers/followers_triggers";

// Firebase Authentication triggers
export * as auth from "./firebase_authentication/triggers/firebase_auth_triggers";

现在我想添加不会在生产环境中部署的功能(当我 运行 firebase deploy 时),但当模拟器 运行ning 时可用(当我 运行 火力基地 emulators:start)

检测模拟器是否为运行ning,我们可以查看其环境变量,process.env.FUNCTIONS_EMULATOR为真。 check this answer 了解更多信息

所以我的完整index.ts会是这样

// Firestore triggers
export * as users from "./firestore/triggers/users/users_triggers";
export * as users_attendedEvents from "./firestore/triggers/users/attendedEvents/attended_events_triggers";
export * as users_followers from "./firestore/triggers/users/followers/followers_triggers";
    
// Firebase Authentication triggers
export * as auth from "./firebase_authentication/triggers/firebase_auth_triggers";

// The code below will be exported only if emulators are running, to avoid deployment to production server
const isRunningOnEmulator = (process.env.FUNCTIONS_EMULATOR && process.env.FIRESTORE_EMULATOR_HOST);
import * as emulator_functions from "./utilities/emulators/http_triggers/for_testing_via_firestore_emulators";
export const forEmulator = isRunningOnEmulator ? emulator_functions : undefined;