-
Notifications
You must be signed in to change notification settings - Fork 1
/
DynamoDBBigQuery.js
68 lines (60 loc) · 1.91 KB
/
DynamoDBBigQuery.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
var config = require('./gcpconfig');
var gcloud = require('gcloud');
var unmarshalItem = require('dynamodb-marshaler').unmarshalItem;
var _ = require('lodash');
exports.handler = function(event, context) {
var rows = _.chain(event.Records)
.filter(function(obj) {
return obj.eventName == 'INSERT' || obj.eventName == 'MODIFY';
})
.pluck('dynamodb.NewImage')
.map(function(element) {
return unmarshalItem(element);
}).value();
var tableName;
if (_.has(config, 'table') && config.table) {
tableName = config.table
} else {
var arn = _.chain(event.Records).first().get('eventSourceARN').toString();
var resource = arn.split(':')[5];
tableName = resource.split('/')[1];
}
console.log('tableName:', tableName);
var bigquery = gcloud.bigquery({
projectId: config.project,
keyFilename: 'gcpkey.json',
});
var table = bigquery.dataset(config.dataset).table(tableName);
var options = {};
if (config.tablePartitionPeriod == "monthly") {
var date = new Date();
date.setDate(1);
options.templateSuffix = getTemplateSuffix(date);
} else if (config.tablePartitionPeriod == "daily") {
var date = new Date();
options.templateSuffix = getTemplateSuffix(date);
}
table.insert(rows, options, function(err, insertErrors, apiResponse) {
if (err) return context.done(err);
if (insertErrors && insertErrors.length > 0) {
_.forEach(insertErrors, function (insertError){
console.log(insertError.row);
_.forEach(insertError.error, function(e) {
console.log("%s: %s", e.reason, e.message);
});
});
return context.done("error");
}
console.log(apiResponse);
context.done(null, "success");
});
};
function getTemplateSuffix(d) {
return d.getFullYear() + padZero(d.getMonth() + 1) + padZero(d.getDate());
}
function padZero(n) {
if (n > 9) {
return n.toString(10);
}
return '0' + n.toString(10);
}