cj8988

Google Cloud Function操作BigQuery数据库。

1、部署云函数时在配置文件中(package.json)添加一项 "@google-cloud/bigquery": "^2.1.0":

(注:如何部署google云函数请参考https://www.cnblogs.com/cj8988/p/9454350.html

{
  "name": "functions",
  "description": "Cloud Functions for Firebase",
  "scripts": {
    "lint": "eslint .",
    "serve": "firebase serve --only functions",
    "shell": "firebase functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log"
  },
  "dependencies": {
    "@google-cloud/bigquery": "^2.1.0",
    "firebase-admin": "~7.0.0",
    "firebase-functions": "^2.2.0"
  },
  "devDependencies": {
    "eslint": "^5.12.0",
    "eslint-plugin-promise": "^4.0.1"
  },
  "private": true
}

2、函数实现

const functions = require(\'firebase-functions\');
const {BigQuery} = require(\'@google-cloud/bigquery\');
const bigquery = new BigQuery({
    projectId: \'wosd2b3\',                         //项目ID
});
const dataset = bigquery.dataset(\'wodgegh\');      // BigQuery库名称
const table = dataset.table(\'demo\');              // BigQuery表名

// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//函数实现
exports.demoBq = functions.https.onRequest((request, response) => {
    table.insert({
        id:\'cj112\',
        type:\'11000\',
        time:\'11000\'
    }).then((data) => {
        const apiResponse = data[0];

        return response.json({code:200,msg:apiResponse});
    }).catch((err) => {
        if (err.name === \'PartialFailureError\') {
            // Some rows failed to insert, while others may have succeeded.
            // err.errors (object[]):
            // err.errors[].row (original row object passed to `insert`)
            // err.errors[].errors[].reason
            // err.errors[].errors[].message
            
            return response.json({code:-1,msg:err});
        }
        return response.json({code:-2,msg:err});
    });
});

 

更多操作参考:https://cloud.google.com/nodejs/docs/reference/bigquery/2.0.x/Table#insert

https://github.com/googleapis/nodejs-bigquery/blob/main/samples/insertRowsAsStream.js

 

分类:

技术点:

相关文章:

  • 2022-12-23
  • 2021-10-10
  • 2022-03-04
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-12-25
  • 2022-12-23
  • 2021-11-12
  • 2021-12-05
相关资源
相似解决方案