LambdaWrap
Simple async function wrapper for AWS lambda and serverless library
- allows using common middlewares (before, catch)
- allows to set common error response format
- supports generator functions using
co
(optional)
const { lambdaWrap } = require('lambda-wrap');
const wrap = lambdaWrap({
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': 'true',
},
callbackWaitsForEmptyEventLoop: false,
verboseError: true
verboseLog: true
});
wrap.before((event) => {
if (event.body && `${event.headers['content-type']}`.match(/^application\/json/)) {
event.body = JSON.parse(event.body);
}
});
wrap.logger = console;
wrap.finally((error, response) => {
});
module.exports.myHandler = wrap(async (event) => {
return {
body: {
objectAttribute: true
}
};
})
API
Classes
- lambdaWrap
Functions
- error(message, code)
Return new error object.
lambdaWrap
Kind: global class
new lambdaWrap([options])
lambdaWrap
function. You can pass options to override or assign new
attributes to event
object. For example add custom headers:
const headers = {
'X-Auth-Token': 'my-token'
};
const wrap = lambdaWrap({ headers });
It returns an instance of LambdaWrap
- wrap
object. This object can
be used for specifying additional properties:
wrap.responseHandler = customResponseFunction;
Finally, wrap
object can be used as a function to wrap any generator
function and thus create lambda handler:
const handler = wrap(async (event) => {
return {
body: 'Hello world'
};
});
Returns: wrapFn
- - the wrap function
Param | Type | Description |
---|
[options] | LambdaWrapOptions | Use to override or assign new attributes to event object. E.g. headers. |
lambdaWrap~wrap(fn) ⇒ lambdaHandler
Kind: inner method of lambdaWrap
Returns: lambdaHandler
- - Lambda handler.
Param | Type | Description |
---|
fn | function | Function to be wrapped and used as a lambda handler. |
wrap.responseHandler
Override default response function
Kind: static property of wrap
wrap.errorResponseHandler
Override default error response function
Kind: static property of wrap
wrap.logger
Override default logger object - console
.
MUST implement log
, warn
and error
methods.
Kind: static property of wrap
wrap.before(fn)
Add new middleware.
Kind: static method of wrap
Param | Type | Description |
---|
fn | function | Middleware function. |
wrap.catch(fn)
Add new catch.
Kind: static method of wrap
Param | Type | Description |
---|
fn | function | Catch function. |
wrap.finally(fn)
Add finally method, which will be called after each request
Kind: static method of wrap
Param | Type | Description |
---|
fn | function | Middleware function. |
error(message, code)
Return new error object.
Kind: global function
Param | Type | Description |
---|
message | string | Error message. |
code | integer | Error code. |