11import functions from '@google-cloud/functions-framework'
2- import { BigQuery } from '@google-cloud/bigquery'
32
3+ import { BigQueryExport } from './bigquery.js'
44import { callRunJob } from './cloud_run.js'
55import { getCompilationResults , runWorkflow } from './dataform.js'
6+ import { StorageUpload } from './storage.js'
67
78const projectId = 'httparchive'
89const location = 'us-central1'
910const jobId = 'bigquery-export'
1011
12+ const bigquery = new BigQueryExport ( {
13+ projectId,
14+ location : 'US'
15+ } )
16+
1117const TRIGGERS = {
1218 crux_ready : {
1319 type : 'poller' ,
@@ -83,8 +89,22 @@ async function handleExport (req, res) {
8389 return
8490 }
8591
86- const jobName = `projects/${ projectId } /locations/${ location } /jobs/${ jobId } `
87- await callRunJob ( jobName , payload )
92+ const { query, destination, config } = payload
93+
94+ if ( destination === 'cloud_storage' ) {
95+ console . info ( 'Cloud Storage export' )
96+ console . log ( query , config )
97+
98+ const data = await bigquery . queryResults ( query )
99+ const storage = new StorageUpload ( config . bucket )
100+ await storage . exportToJson ( data , config . name )
101+ } else if ( destination === 'firestore' ) {
102+ console . info ( 'Firestore export' )
103+ const jobName = `projects/${ projectId } /locations/${ location } /jobs/${ jobId } `
104+ await callRunJob ( jobName , payload )
105+ } else {
106+ throw new Error ( 'Bad Request: destination unknown' )
107+ }
88108
89109 res . status ( 200 ) . json ( {
90110 replies : [ 200 ] ,
@@ -136,7 +156,9 @@ async function handleTrigger (req, res) {
136156 const trigger = TRIGGERS [ eventName ]
137157 if ( trigger . type === 'poller' ) {
138158 console . info ( `Poller action ${ eventName } ` )
139- const result = await runQuery ( trigger . query )
159+
160+ const rows = await bigquery . queryResults ( trigger . query )
161+ const result = rows . length > 0 && rows [ 0 ] [ Object . keys ( rows [ 0 ] ) [ 0 ] ] === true
140162 console . info ( `Query result: ${ result } ` )
141163 if ( result ) {
142164 await executeAction ( trigger . action , trigger . actionArgs )
@@ -160,22 +182,6 @@ async function handleTrigger (req, res) {
160182 }
161183}
162184
163- /**
164- * Run BigQuery poll query.
165- *
166- * @param {string } query Polling query.
167- * @returns {boolean } Query result.
168- */
169- async function runQuery ( query ) {
170- const bigquery = new BigQuery ( )
171-
172- const [ job ] = await bigquery . createQueryJob ( { query } )
173- console . info ( `Query job ${ job . id } started.` )
174-
175- const [ rows ] = await job . getQueryResults ( )
176- return rows . length > 0 && rows [ 0 ] [ Object . keys ( rows [ 0 ] ) [ 0 ] ] === true
177- }
178-
179185/**
180186 * Execute action based on the trigger configuration.
181187 *
0 commit comments