@kdcsoftware/api-gw-resp
TypeScript icon, indicating that this package has built-in type declarations

1.1.0 • Public • Published

API Gateway Response Builder

ver build codecov size license

Maintainability Code Issues Technical Debt

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

  1. OK
  2. CREATED
  3. NO_CONTENT
  4. REDIRECT
  5. BAD_REQUEST
  6. UNAUTHORIZED
  7. FORBIDDEN
  8. NOT_FOUND
  9. CONFLICT
  10. SERVER_ERROR
  11. GET (alias of OK)
  12. POST (alias of CREATED)
  13. PUT (alias of NO_CONTENT)
  14. 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',
    },
  });
};

See also

@kdcsoftware/api-gw-req

Package Sidebar

Install

npm i @kdcsoftware/api-gw-resp

Weekly Downloads

1

Version

1.1.0

License

MIT

Unpacked Size

17 kB

Total Files

13

Last publish

Collaborators

  • mbungalso
  • ianpogi5