firebase函数admin SDK获取当前项目名称/实例

时间:2018-10-20 19:18:37

标签: javascript firebase google-cloud-functions

我的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)

您可以看到我添加了一个处理程序,用于根据标头将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,因此该功能将仅部署到相应的项目。

提前谢谢

1 个答案:

答案 0 :(得分:1)

您可以使用GCLOUD_PROJECT环境变量来了解哪个项目正在运行任何给定的Cloud Function:

const project = process.env.GCLOUD_PROJECT

Read the documentation了解有关环境变量的更多信息。