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-2025 CODEPRJ.COM