@itcutives/serverless-helpers
v5.0.2
Published
Serverless Helper Functions
Downloads
22
Maintainers
Readme
serverless-helpers
Serverless Request/Response Handlers
Usage
Request
, Response
, and LambdaResponseFormatter
Require
const Request = require('@itcutives/serverless-helpers/src/request');
const Response = require('@itcutives/serverless-helpers/src/response');
const LambdaResponseFormatter = require('@itcutives/serverless-helpers/src/lambdaResponseFormatter');
Usage
module.exports.handler = async () => {
const request = REQ.normaliseLambdaRequest(event);
const response = new RES();
try {
//... open db connection, handle request etc ...
const resp = await handleEvent(request, response);
// response.respond(<status-code>, <response-body>, <headers>);
// eg. response.respond(200, JSON.stringify({test: 1}), { 'content-type': 'application/json' });
return LambdaResponseFormatter.responseHandler(resp);
} catch (e) {
return LambdaResponseFormatter.errorHandler(e);
}
};
LambdaResponseFormatter
middleware
To handle the clean up operations before responding. such as close db connection etc...
const LambdaResponseFormatter = require('@itcutives/serverless-helpers/src/lambdaResponseFormatter');
class ResponseHandler extends LambdaResponseFormatter {
static async middleware(response) {
// add remove header etc.
// close db connection
return true;
}
}
module.exports = ResponseHandler;
Once you have above, your handler
function should use ResponseHandler
class instead of LambdaResponseFormatter
boom-to-jsonapi
Require
const boomToJsonAPI = require('@itcutives/serverless-helpers/src/boom-to-jsonapi');
Unclassified Error
boomToJsonAPI(new Error('random error'));
// {
// errors: [{
// status: '500',
// title: 'Internal Server Error',
// detail: 'An internal server error occurred',
// code: undefined
// }]
// }
Boom Error
boomToJsonAPI(Boom.badRequest('BAD Request'));
// {
// errors: [{
// status: '400',
// title: 'Bad Request',
// detail: 'BAD Request',
// code: undefined
// }]
// }
Boom Error with Code
boomToJsonAPI(Boom.badRequest('CODE :Some Error:it happened'));
// {
// errors: [{
// status: '400',
// title: 'Bad Request',
// detail: 'Some Error:it happened',
// code: 'CODE'
// }]
// }
Example
cd example
# install dependencies
npm i
# run api offline
npm run offline
to see Success Response:
http://localhost:3000/v1/success
to see Error Response:
http://localhost:3000/v1/error