Skip to content

Instantly share code, notes, and snippets.

@WaleedAshraf
Last active April 20, 2018 20:57
Show Gist options
  • Save WaleedAshraf/1b34d876a581c840d1e179be6c3e8cac to your computer and use it in GitHub Desktop.
Save WaleedAshraf/1b34d876a581c840d1e179be6c3e8cac to your computer and use it in GitHub Desktop.
Building you first Serverless app in Node.js with AWS Lambda + S3 + API Gateway
const im = require('imagemagick');
const fs = require('fs');
exports.handler = async (event) => {
const operation = event.queryStringParameters ? event.queryStringParameters.operation : null;
let data = JSON.parse(event.body);
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 = 'png';
let inputFile = null, outputFile = null;
try {
if (body.base64Image) {
inputFile = '/tmp/inputFile.png';
const buffer = new Buffer(body.base64Image, 'base64');
fs.writeFileSync(inputFile, buffer);
customArgs.unshift(inputFile); // customArgs should be like [inputFile, options, outputfile]
}
outputFile = `/tmp/outputFile.${outputExtension}`;
customArgs.push(outputFile);
await performConvert(customArgs);
let fileBuffer = new Buffer(fs.readFileSync(outputFile));
fs.unlinkSync(outputFile);
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');
}
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment