在 Node 项目中添加多个 BigQuery JSON 凭据文件

Adding multiple BigQuery JSON credential files in Node project

我一直在从事一个涉及从 BigQuery 获取一些数据的 Node 项目。到目前为止一切都很好;我有我的 credential.json 文件(来自 BigQuery),项目按预期工作。

但是,我想在项目中实现一项新功能,这将涉及从 BigQuery 获取另一组数据。对于这个新数据集,我有一个完全不同的 credential.json 文件。我的项目似乎只能识别我拥有的初始 credential.json 文件(尽管我对它们的命名不同)。

这是我如何链接我的第一个 credential.json 文件的片段:

function createCredentials(){

    try{
        const encodedCredentials = process.env.GOOGLE_AUTH_KEY;

        if (typeof encodedCredentials === 'string' && encodedCredentials.length > 0) {
            const google_auth = atob(encodedCredentials);

        if (!fs.existsSync('credentials.json')) {
            fs.writeFile("credentials.json", google_auth, function (err, google_auth) {
                  if (err) console.log(err);
                  console.log("Successfully Written to File.");
                });
          }
      }

    } 

catch (error){
    logger.warn(`Ensure that the environment variable for GOOGLE_AUTH_KEY is set correctly: full errors is given here: ${error.message}`)
    process.kill(process.pid, 'SIGTERM')
  }


}

有没有办法将我的两个 credential.json 文件融合在一起?如果不是,我如何单独声明使用哪个 credential.json 文件?

If not, how can I separately declare which credential.json file to use?

我会做什么我会创建一个函数,它是 BigQuery 的出口点,并将标识符传递给您的函数,生成凭据,然后调用 BigQuery 时将使用此凭据。

下面的代码假设你改变了这个

function createCredentials(){

    try{
        const encodedCredentials = process.env.GOOGLE_AUTH_KEY;

为此:

function createCredentials(auth){

    try{
        const encodedCredentials = auth;

你可以这样使用它


    import BigQuery from '@google-cloud/bigquery';
    import {GoogApi} from "../apiManager" //Private code to get Token from client DB

    if (!global._babelPolyfill) {
        var a = require("babel-polyfill")
    }

    describe('Check routing', async () => {

        it('Test stack  ', async (done, auth) => {

            //Fetch client Auth from local Database

            //Replace the 2 value below with real values
            const tableName = "myTest";
            const dataset = "myDataset";

            try {

                const bigquery = new BigQuery({
                    projectId: `myProject`,
                    <b>keyFilename: this.createCredentials(auth)</b>
                });
                await bigquery.createDataset(dataset)
                    .then(
                        args => {
                            console.log(`Create dataset, result is: ${args}`)
                        })
                    .catch(err => {
                        console.log(`Error in the process: ${err.message}`)
                    })
            } catch (err) {
                console.log("err", err)
            }
        })
    })