google云函数实现BigQuery数据操作


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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2026 CODEPRJ.COM