Skip to content

Commit cc79ae8

Browse files
author
1cadumagalhaes
committed
✨ feat(bigquery): inserindo dados no BQ na requisição post
1 parent 60f3144 commit cc79ae8

File tree

7 files changed

+36
-26
lines changed

7 files changed

+36
-26
lines changed

bigquery.js

+14-8
Original file line numberDiff line numberDiff line change
@@ -18,23 +18,23 @@ let schemaExample = [
1818
*/
1919
async function getOrCreateDataset(datasetId) {
2020
const bq = new BigQuery();
21-
const dataset = await bq.dataset(datasetId).get({ autoCreate: true });
22-
return dataset;
21+
await bq.dataset(datasetId).get({ autoCreate: true });
22+
return bq.dataset(datasetId);
2323
}
2424

2525
async function getOrCreateTable({ datasetId, tableName, schema }) {
2626
try {
2727
const dataset = await getOrCreateDataset(datasetId);
28-
2928
const options = {
3029
schema,
3130
location: 'US',
3231
type: 'TABLE',
3332
};
34-
return dataset.table(tableName).get({
33+
const table = await dataset.table(tableName).get({
3534
autoCreate: true,
3635
...options,
3736
});
37+
return dataset.table(tableName);
3838
} catch (error) {
3939
console.error(`Error getting table ${tableName}:`, error);
4040
throw new Error(error);
@@ -65,23 +65,29 @@ async function insertRowsAsStream(rows, datasetId, tableName, schema) {
6565
* @param {*} tableName
6666
* @param {*} schema - Schema of the table, in case you need to create it.
6767
*/
68-
async function loadData(rows, datasetId, tableName, schema) {
68+
async function loadData(rows, datasetId, tableName) {
6969
try {
7070
const metadata = {
7171
sourceFormat: 'NEWLINE_DELIMITED_JSON',
7272
location: 'US',
7373
writeDisposition: 'WRITE_APPEND',
7474
};
75-
const tempFilePath = path.join(os.tmpdir(), 'data.json');
7675
let data = rows instanceof Array ? rows : [rows];
76+
const schema = generateSchema(data[0]);
7777
data = data.map((r) => JSON.stringify(r)).join('\n');
78+
79+
const tempFilePath = path.join(os.tmpdir(), 'data.json');
7880
fs.writeFileSync(tempFilePath, data);
7981
const table = await getOrCreateTable({ datasetId, tableName, schema });
82+
console.info(`Trying to create load job with ${data.length} rows.`);
8083
await table.load(tempFilePath, metadata, (err, apiResponse) => {
81-
if (err) throw new Error('Error loading job');
84+
if (err) {
85+
throw new Error(err);
86+
}
8287
});
88+
fs.unlinkSync(tempFilePath);
8389
} catch (error) {
84-
console.error(`Error inserting ${rows.lenght} in ${tableId}. \n`, error);
90+
console.error(`Error inserting ${rows.lenght || 1} row in ${tableName}. \n`, error);
8591
}
8692
}
8793

index.js

+5-3
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,12 @@ const express = require('express');
33
const cors = require('cors');
44
const { insertRowAsStream, loadData } = require('./bigquery');
55
const { hubMessage } = require('./message');
6+
const schema = require('./log_schema.json');
67

78
const app = express();
89
const port = 8000;
910
const DATASET_ID = 'raft_suite',
10-
TABLE_ID = 'record';
11+
TABLE_ID = 'hub';
1112

1213
app.use((req, res, next) => {
1314
res.header('Access-Control-Allow-Origin', '*');
@@ -21,10 +22,10 @@ app.use(cors());
2122
app
2223
.route('/')
2324
.get(function (req, res) {
24-
const message = JSON.stringify(hubMessage(), null, 2);
25+
let message = hubMessage();
26+
message = JSON.stringify(message, null, 2);
2527
const response = `This is a example message:\n${message}`;
2628
res.status(200).send(response);
27-
loadData(message, DATASET_ID, TABLE_ID);
2829
console.log(message);
2930
})
3031
.post(function (req, res) {
@@ -41,6 +42,7 @@ app
4142
const data = hubMessage(body);
4243
res.status(200).send(data.jobId);
4344
console.log(JSON.stringify(data));
45+
loadData(data, DATASET_ID, TABLE_ID);
4446
} catch (error) {
4547
res.status(400).send(error.toString());
4648
console.error(error);

log.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -12,5 +12,5 @@
1212
"description": "",
1313
"details": ""
1414
},
15-
"payload": "{\"teste\":: \"Cadu\"}"
15+
"payload": "{\"teste\": \"Cadu\"}"
1616
}

log_schema.json

-4
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,6 @@
1515
"name": "module",
1616
"type": "STRING"
1717
},
18-
{
19-
"name": "project",
20-
"type": "STRING"
21-
},
2218
{
2319
"name": "spec",
2420
"type": "STRING"

message.js

+9-8
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
const cuid = require('cuid');
22
const status = require('./status.json');
3+
const { version } = require('./package.json');
34

45
function getStatusMessage(statusCode) {
56
let [dimension, code] = statusCode.split('-');
@@ -35,16 +36,16 @@ function hubMessage(body) {
3536
return {
3637
timestamp: new Date().toISOString(),
3738
jobId: cuid(),
38-
project: project,
39-
module: module,
40-
spec: spec,
41-
deploy: deploy,
42-
version: '0.0.1',
39+
project,
40+
module,
41+
spec,
42+
deploy,
43+
version,
4344
status: {
44-
code: code,
45+
code,
4546
message: getStatusMessage(code),
46-
description: description,
47-
details: details,
47+
description,
48+
details,
4849
},
4950
payload: JSON.stringify(payload),
5051
};

package.json

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
{
22
"name": "raft-suite-hub",
33
"private": "true",
4-
"version": "0.1.5",
4+
"version": "1.0.0",
55
"description": "Google Cloud Function",
66
"repository": {
77
"type": "git",
@@ -80,4 +80,4 @@
8080
"sinon": "^11.1.1",
8181
"uuid": "^8.3.2"
8282
}
83-
}
83+
}

test/unit/bigquery.test.js

+5
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
const { assert, expect } = require('chai');
22

33
const { formatEntrie, generateSchema } = require('../../bigquery');
4+
const { hubMessage } = require('../../message');
45

56
const COLUMN_NAME = 'Teste';
67
const TYPES = [
@@ -33,4 +34,8 @@ describe.only('BigQuery helper', () => {
3334
expect(name).to.equal('a');
3435
expect(type).to.equal('INT64');
3536
});
37+
it('formatEntrie - Converte uma mensagem em schema', () => {
38+
const message = hubMessage();
39+
const schema = generateSchema(message);
40+
});
3641
});

0 commit comments

Comments
 (0)