Skip to content

Commit

Permalink
Merge pull request #24 from leonardodino/serve-async
Browse files Browse the repository at this point in the history
Support async handlers
  • Loading branch information
calavera authored Apr 13, 2018
2 parents 9f6a6d0 + a528e43 commit d1e47ab
Showing 1 changed file with 33 additions and 16 deletions.
49 changes: 33 additions & 16 deletions lib/serve.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,36 @@ function handleErr(err, response) {
return;
}

function createCallback(response) {
return function callback(err, lambdaResponse) {
if (err) {
return handleErr(err, response);
}

response.statusCode = lambdaResponse.statusCode;
for (const key in lambdaResponse.headers) {
response.setHeader(key, lambdaResponse.headers[key]);
}
response.write(
lambdaResponse.isBase64Encoded
? base64.decode(lambdaResponse.body)
: lambdaResponse.body
);
response.end();
}
}

function promiseCallback(promise, callback) {
if (!promise) return;
if (typeof promise.then !== 'function') return;
if (typeof callback !== 'function') return;

promise.then(
function(data) {callback(null, data)},
function(err) {callback(err, null)}
);
}

function createHandler(dir) {
return function(request, response) {
var func = request.path.split("/").filter(function(e) {
Expand All @@ -39,22 +69,9 @@ function createHandler(dir) {
isBase64Encoded: isBase64
};

handler.handler(lambdaRequest, {}, function(err, lambdaResponse) {
if (err) {
return handleErr(err, response);
}

response.statusCode = lambdaResponse.statusCode;
for (const key in lambdaResponse.headers) {
response.setHeader(key, lambdaResponse.headers[key]);
}
response.write(
lambdaResponse.isBase64Encoded
? base64.decode(lambdaResponse.body)
: lambdaResponse.body
);
response.end();
});
var callback = createCallback(response);
var promise = handler.handler(lambdaRequest, {}, callback);
promiseCallback(promise, callback);
};
}

Expand Down

0 comments on commit d1e47ab

Please sign in to comment.