-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
78 lines (67 loc) · 1.9 KB
/
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
const im = require('imagemagick');
const fs = require('fs');
const AWS = require('aws-sdk');
const s3 = new AWS.S3();
exports.handler = async (event) => {
const operation = event.queryStringParameters ? event.queryStringParameters.operation : null;
let data = JSON.parse(event.body);
switch (operation) {
case 'ping':
sendRes(200, 'pong');
break;
case 'convert':
return await operate(data);
default:
return sendRes(401, `Unrecognized operation ${operation}`);
}
};
const sendRes = (status, body) => {
return {
statusCode: status,
headers: {
"Content-type": "text/html"
},
body: body
};
}
const operate = async (data) => {
const customArgs = data.customArgs.split(',') || [];
let outputExtension = 'png';
let inputFile = null, outputFile = null;
try {
if (data.base64Image) {
inputFile = '/tmp/inputFile.png';
const buffer = new Buffer(data.base64Image, 'base64');
fs.writeFileSync(inputFile, buffer);
customArgs.unshift(inputFile);
}
outputFile = `/tmp/outputFile.${outputExtension}`;
customArgs.push(outputFile);
await performConvert(customArgs);
let fileBuffer = new Buffer(fs.readFileSync(outputFile));
fs.unlinkSync(outputFile);
await saveFile(fileBuffer);
return sendRes(200, `<img src="data:image/png;base64,${fileBuffer.toString('base64')}"/>`);
} catch (error) {
return sendRes(500, error);
}
}
const performConvert = (params) => {
return new Promise((resolve, reject) => {
im.convert(params, (error) => {
if (error) {
reject(error);
} else {
resolve('Operation completed succesfully');
}
})
});
}
const saveFile = async (buffer) => {
const params = {
Bucket: 'imagetransformation',
Key: `images/${Date.now().toString()}.png`,
Body: buffer
};
return await s3.putObject(params).promise();
}