forked from andersao/node-serverless
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprocessor-index.js
63 lines (53 loc) · 1.53 KB
/
processor-index.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
const AWS = require('aws-sdk');
const s3 = new AWS.S3();
const ServiceManager = require('./services/service-manager');
const { createConnection } = require('./config/db');
const connection = createConnection();
const services = new ServiceManager(connection);
const { BATCH_BUCKET, APP_DEBUG } = process.env;
async function executeRecord(payload) {
const { articlesService } = services;
const { id, path } = JSON.parse(payload.body);
const { Body } = await s3
.getObject({
Bucket: BATCH_BUCKET,
Key: path,
})
.promise();
const batchData = JSON.parse(Body.toString());
try {
console.log(`processando lote ${id}`);
await articlesService.saveBatch(id, batchData);
console.log(`lote ${id} processado com sucesso`);
return true;
} catch (e) {
console.error(`erro no lote: ${id}`, e);
}
}
async function processRecords(records) {
if (!Array.isArray(records) || records.length === 0) return true;
const [record] = records.splice(0, 1);
try {
await executeRecord(record);
} catch (error) {
console.log(error);
} finally {
return processRecords(records);
}
}
const handler = async (event) => {
if (APP_DEBUG === 'true') {
console.log('event: %j', event);
}
if (!event || !event.Records) return;
try {
const filterSQS = (rec) => rec.eventSource === 'aws:sqs';
const records = event.Records.filter(filterSQS);
await processRecords(records);
return true;
} catch (error) {
console.log(error);
return false;
}
};
module.exports.handler = handler;