-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathhandler.js
More file actions
53 lines (46 loc) · 1.25 KB
/
handler.js
File metadata and controls
53 lines (46 loc) · 1.25 KB
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
'use strict';
const PDFKit = require('pdfkit');
const AWS = require('aws-sdk');
const s3 = new AWS.S3();
const key = `football-stats-${Date.now()}.pdf`;
const generatePDF = async (text) => {
return new Promise((resolve) => {
const doc = new PDFKit();
const buffers = [];
doc.list(text, { listType: 'numbered' });
doc.on('data', buffers.push.bind(buffers));
doc.on('end', () => {
const pdf = Buffer.concat(buffers);
resolve(pdf);
});
doc.end();
});
};
const savePDF = async (key, pdf) => {
return await(new Promise((resolve) => {
s3.putObject({
Bucket: process.env.BUCKET,
Key: key,
Body: pdf,
ContentType: 'application/pdf',
ACL: 'public-read'
}, (err, result) => {
if(err) console.log('ERROR!', error);
if(result) {
console.log('RESULT!', result);
resolve(result);
}
});
}));
};
const generateURI = (keyValue) =>
`https://${process.env.BUCKET}.s3.${process.env.REGION}.amazonaws.com/${keyValue}`;
module.exports.generate = async ({body}) => {
const text = JSON.parse(body) || 'Pending...';
return generatePDF(text)
.then((pdf) => savePDF(key, pdf))
.then(() => ({
statusCode: 200,
body: generateURI(key),
}));
};