-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathhandler.js
98 lines (88 loc) · 2.47 KB
/
handler.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
'use strict';
const im = require('imagemagick');
const fs = require('fs');
const AWS = require('aws-sdk');
const s3 = new AWS.S3();
exports.handler = async (event) => {
let data = null;
const operation = event.queryStringParameters ? event.queryStringParameters.operation : null;
if (event.httpMethod == 'GET') {
return getPage();
} else {
try {
data = JSON.parse(event.body);
} catch (e) {
data = {
"customArgs": decodeURIComponent(event.body.split('&')[1].split('=')[1]),
"base64Image": decodeURIComponent(event.body.split('&')[3].split('=')[1])
}
}
switch (operation) {
case 'ping':
return sendRes(200, 'pong');
case 'convert':
return await operate(data);
default:
return sendRes(401, '`Unrecognized operation "${operation}"`');
}
}
};
const sendRes = (status, body) => {
var response = {
statusCode: status,
headers: {
"Content-Type": "text/html"
},
body: body
};
return response;
}
const operate = async (body) => {
const customArgs = body.customArgs.split(',') || [];
let outputExtension = body.outputExtension ? body.outputExtension : 'png';
let inputFile = null;
let outputFile = null;
try {
if (body.base64Image) {
inputFile = '/tmp/inputFile.png';
const buffer = new Buffer(body.base64Image, 'base64');
fs.writeFileSync(inputFile, buffer);
customArgs.unshift(inputFile);
}
outputFile = `/tmp/outputFile.${outputExtension}`;
customArgs.push(outputFile);
// [input, customArgs, output]
await performConvert(customArgs);
let fileBuffer = new Buffer(fs.readFileSync(outputFile));
fs.unlinkSync(outputFile);
await putfile(fileBuffer);
return sendRes(200, '<img src="data:image/png;base64,' + fileBuffer.toString('base64') + '"//>');
} catch (e) {
console.log(`Error:${e}`);
return sendRes(500, e);
}
};
const performConvert = (params) => {
return new Promise(function (res, rej) {
im.convert(params, (err) => {
if (err) {
console.log(`Error${err}`);
rej(err);
} else {
res('operation completed successfully');
}
});
});
}
const putfile = async (buffer) => {
let params = {
Bucket: 'serverlessappdemo',
Key: 'images/' + Date.now().toString() + '.png',
Body: buffer
};
return await s3.putObject(params).promise();
}
const getPage = () => {
let data = fs.readFileSync('./form.html', 'utf8');
return sendRes(200, data);
}