我在 firebase 上有不同的第二代云函数,当我调用其中一个时,我在 firebase 日志系统上收到错误:默认的 firebase 应用程序不存在;这是我的职责:
exports.addCustomClaim = onCall({secrets: [privateKey], ...params},
async (data) => {
const admin = instantiateFirebase().admin;
const user = await admin.auth().getUserByEmail(data.data.email);
console.log("adding claims ", data.data.claims, "to", user.uid);
try {
await admin.auth().setCustomUserClaims(user.uid, data.data.claims);
if (data.data.logoutUser) {
console.log("logging out user", user.uid);
await admin.auth().revokeRefreshTokens(user.uid);
}
return await {
message: ` Success!claims ${Object.keys(data.data.claim)}
have been set on ${data.data.email}`,
};
} catch (err) {
return {error: err, user: user.uid};
}
});
这就是我初始化 firebase 的方式:
const instantiateFirebase = ()=>{
const privateKey= defineSecret("PRIVATE_KEY");
const clientEmail = defineString("CLIENT_EMAIL");
const projectId = defineString("PROJECT_ID");
const databaseURL = defineString("DATABASE_URL");
console.log("instantiating firebase");
if(admin.apps.length===0){
console.log("no app");
initializeApp({
credential: admin.credential.cert({
privateKey: privateKey.value().replace(/\\n/g, "\n"),
projectId: projectId.value(),
clientEmail: clientEmail.value(),
}),
databaseURL: databaseURL.value(),
});}
const db = admin.firestore();
const realtime = admin.database();
console.log("done");
return {db, admin, realtime};
};
export {instantiateFirebase};
我解决了我的问题,我必须使用 admin.initializeApp 初始化管理