繁体   English   中英

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

[英]firebase function admin SDK get current project name/instance

我的 Firebase 函数导入了 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 ,因此该功能将仅部署到相应的项目。

先感谢您

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

const project = process.env.GCLOUD_PROJECT

阅读文档以获取有关环境变量的更多信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM