1.1.0 • Published 4 years ago

@kdcsoftware/api-gw-resp v1.1.0

Weekly downloads
1
License
MIT
Repository
github
Last release
4 years ago

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.

OptionDefaultDescription
bodynullJS object that will converted into JSON string. If present, a Content-Type of application/json will be added to the header.
corstrueAdd 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

1.1.0

4 years ago

1.0.1

4 years ago

0.5.0

4 years ago

0.4.0

4 years ago

0.3.0

4 years ago

0.2.0

4 years ago

0.1.6

4 years ago

0.1.5

4 years ago

0.1.3

4 years ago

0.1.2

4 years ago