Skip to content

Commit 261d4d2

Browse files
feat: conform to handler function signature (#10)
* feat: conform to handler function signature * chore: improve Promise detection * chore: return original value from wrapped function if not Promise
1 parent 3f264be commit 261d4d2

File tree

4 files changed

+39
-11
lines changed

4 files changed

+39
-11
lines changed

package-lock.json

+6-5
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

+3-1
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,9 @@
4949
"directories": {
5050
"test": "test"
5151
},
52-
"dependencies": {},
52+
"dependencies": {
53+
"is-promise": "^2.2.2"
54+
},
5355
"devDependencies": {
5456
"@commitlint/cli": "^11.0.0",
5557
"@commitlint/config-conventional": "^11.0.0",

src/lib/builder_functions.js

+12-5
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
const isPromise = require('is-promise')
2+
13
const { HTTP_STATUS_METHOD_NOT_ALLOWED, HTTP_STATUS_OK } = require('./consts')
24

35
const augmentResponse = (response) => {
@@ -12,19 +14,24 @@ const augmentResponse = (response) => {
1214
}
1315

1416
// eslint-disable-next-line promise/prefer-await-to-callbacks
15-
const wrapHandler = (handler) => async (event, context, callback) => {
17+
const wrapHandler = (handler) => (event, context, callback) => {
1618
if (event.httpMethod !== 'GET' && event.httpMethod !== 'HEAD') {
17-
return {
19+
return Promise.resolve({
1820
body: 'Method Not Allowed',
1921
statusCode: HTTP_STATUS_METHOD_NOT_ALLOWED,
20-
}
22+
})
2123
}
2224

2325
// eslint-disable-next-line promise/prefer-await-to-callbacks
2426
const wrappedCallback = (error, response) => callback(error, augmentResponse(response))
25-
const response = await handler(event, context, wrappedCallback)
27+
const execution = handler(event, context, wrappedCallback)
28+
29+
if (isPromise(execution)) {
30+
// eslint-disable-next-line promise/prefer-await-to-then
31+
return execution.then(augmentResponse)
32+
}
2633

27-
return augmentResponse(response)
34+
return execution
2835
}
2936

3037
module.exports = { builderFunction: wrapHandler }

test/builder_functions.js

+18
Original file line numberDiff line numberDiff line change
@@ -132,3 +132,21 @@ test('Returns a 405 error for requests using the PATCH method', async (t) => {
132132

133133
t.deepEqual(response, { body: 'Method Not Allowed', statusCode: 405 })
134134
})
135+
136+
test('Preserves errors thrown inside the wrapped handler', async (t) => {
137+
const error = new Error('Uh-oh!')
138+
139+
error.someProperty = ':thumbsdown:'
140+
141+
const myHandler = async () => {
142+
const asyncTask = new Promise((resolve) => {
143+
setTimeout(resolve, 0)
144+
})
145+
146+
await asyncTask
147+
148+
throw error
149+
}
150+
151+
await t.throwsAsync(invokeLambda(builderFunction(myHandler)), { is: error })
152+
})

0 commit comments

Comments
 (0)