-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathhandler.js
More file actions
78 lines (60 loc) · 1.75 KB
/
Copy pathhandler.js
File metadata and controls
78 lines (60 loc) · 1.75 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
'use strict';
const AWS = require('aws-sdk');
const child_process = require('child_process');
const stream = require('stream');
const s3 = new AWS.S3();
module.exports.exportToPdf = (event, context, callback) => {
var gameid = event.pathParameters.gameid;
if (!gameid)
{
return callback(new Error(`Please include the game id in the request.`));
}
const key = gameid + ".pdf";
const bucket = 'serverless-lichess-to-pdf.dev';
var php = './php';
// workaround to get 'sls invoke local' to work
if (typeof process.env.PWD !== "undefined") {
php = 'php';
}
var proc = child_process.spawn(php, [ "main.php", gameid, { stdio: 'inherit' } ]);
var phpResult = new stream.Readable();
phpResult._read = function noop() {};
proc.stdout.on('data', function (data) {
var dataStr = data.toString('utf8');
phpResult.push(data);
});
proc.stderr.on('data', function (data) {
console.log(`stderr: ${data}`);
});
proc.on('close', function(code) {
if(code !== 0) {
return callback(new Error(`Process exited with non-zero status code ${code}`));
}
else
{
// close the stream
phpResult.push(null);
var body = phpResult.read();
const params = {
Bucket: bucket,
Key: key,
ACL: 'public-read-write',
Body: body,
ContentType: 'application/pdf'
};
s3.putObject(params, function(err, data) {
if (err)
{
return callback(new Error(`Failed to put s3 object: ${err}`));
}
const response = {
statusCode: 302,
headers: {
location : `https://s3-eu-west-1.amazonaws.com/${bucket}/${key}`
}
};
return callback(null, response);
});
}
});
};