问题:如果我想在单独的功能文件中使用Firebase服务,我是否必须在每个文件的顶部包含admin.initializeApp();
?
目前最佳做法是什么?
我有一个包含3个文件的源文件夹
我的index.ts文件是:
export { basicHTTP, advanceHTTP, api } from "./http";
export { createUserRecord } from "./auth";
我的auth.ts文件使用admin.firestore():
import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
admin.initializeApp();
const db = admin.firestore();
export const createUserRecord = functions.auth
.user()
.onCreate((user, context) => {
const userRef = db.doc(`users/${user.uid}`);
return userRef.set({
name: user.displayName,
createdAt: context.timestamp,
nickname: "bubba"
});
});
我的http.ts文件包含以下内容,如果我想在此功能内使用Firebase服务怎么办?:
import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
// Express
import * as express from "express";
import * as cors from "cors";
// Most basic http function
export const basicHTTP = functions.https.onRequest((request, response) => {
response.send("Hello from firebase");
});
export const advanceHTTP = functions.https.onRequest((request, response) => {
const name = request.query.name;
if (!name) {
response.status(400).send("You must supply a name");
}
response.send(`Hi there ${name}`);
});
// Custom middleware
const auth = (request, response, next) => {
if (!request.header.authorization) {
response.status(400).send("Unauthorized. Access denied");
}
next();
};
// Multi Route ExpressJS HTTP Function
const app = express();
app.use(cors({ origin: true }));
app.use(auth);
app.get("/cat", (request, response) => {
response.send("Cat");
});
app.get("/dog", (request, response) => {
response.send("dog");
});
export const api = functions.https.onRequest(app);
答案 0 :(得分:1)
第一次运行此命令
import * as admin from "firebase-admin";
admin.initializeApp();
从其他文件中的后续导入返回的admin
已被初始化。这是因为从模块中进行的所有导入都会产生完全相同的对象。
如果您想在多个地方使用firebase-admin,则可能只需在函数入口点(index.ts)导入并初始化一次,然后在所有其他地方假定它已经被初始化:>
import * as admin from "firebase-admin";
admin.initializeApp();
export { basicHTTP, advanceHTTP, api } from "./http";
export { createUserRecord } from "./auth";
现在,您只需在其他模块中导入firebase-admin即可使用admin,而无需对其进行初始化。