Skip to content

Commit

Permalink
feat: conform to handler function signature (#10)
Browse files Browse the repository at this point in the history
* feat: conform to handler function signature

* chore: improve Promise detection

* chore: return original value from wrapped function if not Promise
  • Loading branch information
eduardoboucas authored Feb 23, 2021
1 parent 3f264be commit 261d4d2
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 11 deletions.
11 changes: 6 additions & 5 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,9 @@
"directories": {
"test": "test"
},
"dependencies": {},
"dependencies": {
"is-promise": "^2.2.2"
},
"devDependencies": {
"@commitlint/cli": "^11.0.0",
"@commitlint/config-conventional": "^11.0.0",
Expand Down
17 changes: 12 additions & 5 deletions src/lib/builder_functions.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
const isPromise = require('is-promise')

const { HTTP_STATUS_METHOD_NOT_ALLOWED, HTTP_STATUS_OK } = require('./consts')

const augmentResponse = (response) => {
Expand All @@ -12,19 +14,24 @@ const augmentResponse = (response) => {
}

// eslint-disable-next-line promise/prefer-await-to-callbacks
const wrapHandler = (handler) => async (event, context, callback) => {
const wrapHandler = (handler) => (event, context, callback) => {
if (event.httpMethod !== 'GET' && event.httpMethod !== 'HEAD') {
return {
return Promise.resolve({
body: 'Method Not Allowed',
statusCode: HTTP_STATUS_METHOD_NOT_ALLOWED,
}
})
}

// eslint-disable-next-line promise/prefer-await-to-callbacks
const wrappedCallback = (error, response) => callback(error, augmentResponse(response))
const response = await handler(event, context, wrappedCallback)
const execution = handler(event, context, wrappedCallback)

if (isPromise(execution)) {
// eslint-disable-next-line promise/prefer-await-to-then
return execution.then(augmentResponse)
}

return augmentResponse(response)
return execution
}

module.exports = { builderFunction: wrapHandler }
18 changes: 18 additions & 0 deletions test/builder_functions.js
Original file line number Diff line number Diff line change
Expand Up @@ -132,3 +132,21 @@ test('Returns a 405 error for requests using the PATCH method', async (t) => {

t.deepEqual(response, { body: 'Method Not Allowed', statusCode: 405 })
})

test('Preserves errors thrown inside the wrapped handler', async (t) => {
const error = new Error('Uh-oh!')

error.someProperty = ':thumbsdown:'

const myHandler = async () => {
const asyncTask = new Promise((resolve) => {
setTimeout(resolve, 0)
})

await asyncTask

throw error
}

await t.throwsAsync(invokeLambda(builderFunction(myHandler)), { is: error })
})

0 comments on commit 261d4d2

Please sign in to comment.