@kdcsoftware/api-gw-resp
v1.1.0
Published
API Gateway response builder
Downloads
14
Readme
API Gateway Response Builder
This module will help you build a valid API Gateway response from your lambda function.
Install
npm i @kdcsoftware/api-gw-resp
Usage
const response = require('@kdcsoftware/api-gw-resp');
module.exports = (event) => {
const body = {
movies: [
{ name: 'Lord of the Rings' },
{ name: 'Forest Gump' },
{ name: 'Breaveheart' },
],
};
return response.OK({ body });
};
The function above will return
{
"statusCode": 200,
"isBase64Encoded": false,
"headers": {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials": true,
"Access-Control-Allow-Headers": "*"
},
"body": "{\"movies\":[{\"name\":\"Lord of the Rings\"},{\"name\":\"Forest Gump\"},{\"name\":\"Breaveheart\"}]}"
}
Methods
- OK
- CREATED
- NO_CONTENT
- REDIRECT
- BAD_REQUEST
- UNAUTHORIZED
- FORBIDDEN
- NOT_FOUND
- CONFLICT
- SERVER_ERROR
- GET (alias of OK)
- POST (alias of CREATED)
- PUT (alias of NO_CONTENT)
- DELETE (alias of NO_CONTENT)
API
All of the methods have the same API.
| Option | Default | Description | | ------- | ------- | ------------------------------------------------------------------------------------------------------------------------------- | | body | null | JS object that will converted into JSON string. If present, a Content-Type of application/json will be added to the header. | | cors | true | Add cors in header | | headers | {} | Additional headers |
Examples
const parser = require('@kdcsoftware/api-gw-req');
const response = require('@kdcsoftware/api-gw-resp');
const db = require('./db');
module.exports = async (event) => {
const request = parser(event);
let body = null;
if (event.method === 'GET') {
try {
const movies = db.listMovies();
return response.GET({ body: { movies } });
} catch (e) {
return response.BAD_REQUEST({ body: e });
}
} else if (event.method === 'POST') {
try {
const id = await db.insertMove(request.body);
return response.POST({ body: { id } });
} catch (e) {
return response.BAD_REQUEST({ body: e });
}
} else if (event.method === 'PUT') {
try {
await db.updateMove(request.body);
return response.PUT();
} catch (e) {
return response.CONFLICT({ body: e });
}
}
return response.BAD_REQUEST({
body: {
message: 'Invalid method',
},
});
};