我的 Firebase Function 导入了 2 个项目,一个用于生产,另一个用于 OTE:
下面是我如何初始化它(这里没问题):
const functions = require('firebase-functions');
var firebaseAdmin = require('firebase-admin');
var productionServiceAccount = require('./keys/production-key.json');
var oteServiceAccount = require("./keys/ote-key.json");
var prodServer = firebaseAdmin.initializeApp({
credential: firebaseAdmin.credential.cert(productionServiceAccount),
databaseURL: 'https://production-panel.firebaseio.com'
}, "prod");
var oteServer = firebaseAdmin.initializeApp({
credential: firebaseAdmin.credential.cert(oteServiceAccount),
databaseURL: "https://ote-panel.firebaseio.com"
}, "ote");
console.log("prodServer: ", prodServer.name, "oteServer: ", oteServer.name)
下面是我如何用 Express
实现它的(也工作正常):
//import express, router, authentication middlewre, etc... i will skip it...
router.post('/createUser', function (req, res) {
let admin = req.headers.env == 'prod' ? prodServer : oteServer
let newUser = {
emailVerified: false
}
if (req.body.email && req.body.password) {
newUser["email"] = req.body.email
newUser["password"] = req.body.password
}
else {
if (!req.body.email) {
return res.status(400).send({
code: -1,
msg: "Email is missing"
})
}
if (!req.body.password) {
return res.status(400).send({
code: -1,
msg: "Password is missing"
})
}
return res.status(400).send({
code: -1,
msg: "Email/Password is missing"
})
}
return admin.auth().createUser(newUser).then(userRecord => {
console.log("successfully created new User: ", userRecord.uid, ", by: ", req.headers.uid)
console.log(userRecord)
return res.status(201).send(userRecord)
}).catch(error => {
console.log("Failed to create user: ", error)
return res.status(400).send({
code: -1,
msg: "Error has occur during creating user",
error: error
})
})
})
app.use(cors)
app.use(router)
exports.api = functions.https.onRequest(app)
你可以看到我添加了一个处理程序来根据 header 将 HTTP 请求路由到 prod/ote 项目
下面是我面临的问题,我不知道如何用 onCall
识别项目/onCreate
事件:
exports.newUserNotification = functions.auth.user().onCreate((user) => {
//How to identify this function is trigger at which project?
//Then I want to write the data to different DB, etc
});
注意:
1) 当我进行部署时,我使用的是 firebase use <projectId>
+ firebase deploy
, 因此该函数将仅部署到相应的项目。
提前致谢
最佳答案
您可以使用 GCLOUD_PROJECT 环境变量来了解哪个项目正在运行任何给定的 Cloud Functions:
const project = process.env.GCLOUD_PROJECT
Read the documentation有关环境变量的更多信息。
关于javascript - firebase 函数 admin SDK 获取当前项目名称/实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52909303/