google雲函數實現BigQuery數據操作
阿新 • • 發佈:2019-04-03
object .com while firebase com package nod pri only
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
google雲函數實現BigQuery數據操作