Skip to content

Instantly share code, notes, and snippets.

@doapp-ryanp
Created October 17, 2017 21:28
Show Gist options
  • Save doapp-ryanp/7e982d38cf84809171e7628271676072 to your computer and use it in GitHub Desktop.
Save doapp-ryanp/7e982d38cf84809171e7628271676072 to your computer and use it in GitHub Desktop.
Image resize Lambda for APIG proxy
'use strict';
const im = require('imagemagick');
const fs = require('fs');
const https = require('https');
const http = require('http');
const url = require('url');
const querystring = require('querystring');
const resize = (srcPath, width, callback) => {
const dstPath = `/tmp/resized.png`,
resizeOpts = {
width: width,
srcPath: srcPath,
dstPath: dstPath
};
try {
im.resize(resizeOpts, (err) => {
if (err) {
throw err;
} else {
callback(null, fs.readFileSync(dstPath).toString('base64'));
}
});
} catch (err) {
console.log('Resize operation failed:', err);
callback(err);
}
};
const handleError = (msg, callback, code = 400) => {
const d = {
body: msg || "Unknown error",
statusCode: code
};
callback(null, d);
};
const download = (srcUrl, dest) => {
return new Promise((resolve, reject) => {
console.log(`Downloading`,srcUrl);
let urlParts = {};
try {
urlParts = url.parse(srcUrl);
} catch (e) {
reject(e);
}
let file = fs.createWriteStream(dest);
const protocolLib = ('https:' === urlParts.protocol)
? https
: http;
let request = protocolLib.get(srcUrl, (response) => {
if (response.statusCode !== 200) {
reject(new Error('Non 200 status ' + response.statusCode));
}
response.pipe(file);
file.on('finish', () => {
file.close(resolve); // close() is async, call cb after close completes.
});
});
// check for request error too
request.on('error', (err) => {
fs.unlink(dest);
reject(err);
});
file.on('error', (err) => { // Handle errors
fs.unlink(dest); // Delete the file async. (But we don't check the result)
reject(err);
});
});
};
exports.handler = (event, context, callback) => {
const qs = event.queryStringParameters;
if ('myKey' !== qs.k) {
return handleError('Not authd', callback, 401);
} else if (!qs.w) {
return handleError('Missing width (w)', callback);
} else if (!qs.u) {
return handleError('Missing URL (u)', callback);
}
const srcDownloadPath = '/tmp/srcImg';
download(querystring.unescape(qs.u), srcDownloadPath).then(() => {
resize(srcDownloadPath, qs.w, (err, base64ImageResized) => {
callback(null, {
isBase64Encoded: true,
statusCode: 200,
headers: {
'Content-Type': 'image/png'
},
body: base64ImageResized
});
});
}).catch((err) => {
handleError(err);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment