Skip to content

Instantly share code, notes, and snippets.

@lteacher
Created May 18, 2017 23:51
Show Gist options
  • Save lteacher/9ef1c7bc5908418b30a18719521ff3c7 to your computer and use it in GitHub Desktop.
Save lteacher/9ef1c7bc5908418b30a18719521ff3c7 to your computer and use it in GitHub Desktop.
const _ = require('lodash');
const Busboy = require('busboy');
const getContentType = (event) => {
// Serverless offline is passing 'Content-Type', AWS is passing 'content-type'
let contentType = _.get(event, 'headers.content-type');
if (!contentType) contentType = _.get(event, 'headers.Content-Type');
return contentType;
};
exports.parseForm = (event) => new Promise((resolve, reject) => {
const busboy = new Busboy({
headers: {
'content-type': getContentType(event),
},
});
const result = {};
busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
file.on('data', data => {
result.file = data;
});
file.on('end', () => {
result.filename = filename;
result.contentType = mimetype;
});
});
busboy.on('field', (fieldname, value) => {
result[fieldname] = value;
});
busboy.on('error', error => reject(`Parse error: ${error}`));
busboy.on('finish', () => resolve(_.set(event, 'body', result)));
busboy.write(event.body, event.isBase64Encoded ? 'base64' : 'binary');
busboy.end();
});
exports.fromJson = (event) => {
if (event && event.body && _.isString(event.body)) {
return _.set(event, 'body', JSON.parse(event.body));
}
};
exports.toJson = (event, context, response) => {
if (response && response.body) {
return _.set(response, 'body', JSON.stringify(response.body));
}
};
exports.parseRequest = (options) => {
const defaults = _.assign({}, {
json: true,
forms: true,
}, options);
// Return the parse handler -> (event, context, response)
return (event) => {
if (!event || !event.body) return;
const contentType = getContentType(event);
// Mutate the event based on the content type
if (_.includes(contentType, '/json') && defaults.json) {
return exports.fromJson(event);
}
if (_.includes(contentType, 'multipart/form-data') && defaults.forms) {
return exports.parseForm(event);
}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment