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

1.7.6 • Public • Published

API Gateway Response Builder

This module will help you build a valid API Gateway response from your lambda function.

ver size build Known Vulnerabilities Quality Gate Status Code Smells Coverage license

Install

npm i @kdcio/api-gw-resp

Usage

import response from '@kdcio/api-gw-resp';

export const listMovies = (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\"}]}"
}

API

Successful responses

Method Code Description
OK 200 Request has succeeded and the message body contains the requested information.
CREATED 201 Request has succeeded and a new resource has been created. The message body may contain information about the new resource.
NO_CONTENT 204 Request has succeeded but there is no content to be returned.

Options

Option Type Required Default Description
body object, string or null ☑️ null
  • object will be converted into JSON string and will have a Content-Type of application/json in the header.
  • string will have a Content-Type of text/plain in the header.
cors bool ☑️ true If true, will add cors in header
origin string ☑️ * Set specific origin
headers object ☑️ {} Specify additional headers

Examples:

response.OK({ body: { name: 'John Doe' } });
response.CREATED({ body: { id: 1 } });
response.NO_CONTENT();

Redirect responses

Method Code Description
REDIRECT 301 or 302 The URI of the requested resource has moved. The new URI can be found in the Location header.

Options

Option Type Required Default Description
permanent bool ☑️ none If true, status code will be 301. Otherwise it will be 302.
location bool ☑️ none The new url where the resource has been moved.
headers object ☑️ {} Specify additional headers

Examples:

response.REDIRECT({
  permanent: true,
  location: 'https://www.google.com',
});

Client Error responses

Method Code Description
BAD_REQUEST 400 The server could not understand the request due to invalid syntax or missing parameters.
UNAUTHORIZED 401 The client must authenticate itself to get the requested response.
FORBIDDEN 403 The client is not allowed to access the requested resource. Unlike 401, the client's identity is known to the server.
NOT_FOUND 404 The server can not find the requested resource.
CONFLICT 409 This response is sent when a request conflicts with the current state of the server. Usually duplicate of data.

Options

Option Type Required Default Description
error string ☑️ Status code name Error name
message string none Error message

Examples:

response.BAD_REQUEST({ message: 'Missing username' });
response.UNAUTHORIZED({
  message: 'You need to login to access this resource.',
});
response.FORBIDDEN({ message: 'You are not allowed to access this resource.' });
response.NOT_FOUND({ message: 'Resource not found.' });
response.CONFLICT({ message: 'Duplicate username.' });

Server Error responses

Method Code Description
SERVER_ERROR 500 The server has encountered a situation it doesn't know how to handle.

Options

Option Type Required Default Description
error string ☑️ Internal Server Error Error name
message string none Error message

Examples:

response.SERVER_ERROR({ message: 'Internal server error.' });

Auto Detect Error responses

Method Description
ERROR This will auto detect which error code to send based on the message.

Options

Option Type Required Default Description
message string none Error message

Error Messages

Error Response Regex matcher
BAD_REQUEST /missing|invalid/i
UNAUTHORIZED /unauthorized/i
FORBIDDEN /forbidden|not allowed/i
NOT_FOUND /not found/i
CONFLICT /conflict|duplicate/i

Examples:

try {
  throw new Error('Missing username');
} catch (e) {
  // This will return status code 400 (BAD_REQUEST)
  return response.ERROR({ message: e.message });
}

More Examples

import parser from '@kdcio/api-gw-resp';
import response from '@kdcio/api-gw-resp';
import db from './db';

export const movie = async (event) => {
  const request = parser(event);
  let body = null;

  if (event.method === 'GET') {
    try {
      const movies = db.listMovies();
      return response.OK({ body: { movies } });
    } catch (e) {
      return response.BAD_REQUEST({ message: e.message });
    }
  } else if (event.method === 'POST') {
    try {
      const id = await db.insertMove(request.body);
      return response.OK({ body: { id } });
    } catch (e) {
      return response.BAD_REQUEST({ message: e.message });
    }
  } else if (event.method === 'PUT') {
    try {
      await db.updateMove(request.body);
      return response.NO_CONTENT();
    } catch (e) {
      return response.CONFLICT({ message: e.message });
    }
  }

  return response.BAD_REQUEST({
    message: 'Invalid method',
  });
};

Using ERROR method:

import parser from '@kdcio/api-gw-resp';
import response from '@kdcio/api-gw-resp';
import db from './db';

export const movie = async (event) => {
  const request = parser(event);
  let body = null;

  try {
    if (event.method === 'GET') {
      const movies = db.listMovies();
      return response.OK({ body: { movies } });
    } else if (event.method === 'POST') {
      const id = await db.insertMove(request.body);
      return response.OK({ body: { id } });
    } else if (event.method === 'PUT') {
      await db.updateMove(request.body);
      return response.NO_CONTENT();
    } else {
      throw new Error('Invalid method');
    }
  } catch (e) {
    // Will determine the correct status code based on the error message
    return response.ERROR({ message: e.message });
  }
};

Star Me

If you find this project useful, please consider giving a star. I would really appreciate it.

You can also:

Buy Me A Coffee

See also

@kdcio/api-gw-resp

License

MIT

Package Sidebar

Install

npm i @kdcio/api-gw-resp

Weekly Downloads

3

Version

1.7.6

License

MIT

Unpacked Size

23 kB

Total Files

14

Last publish

Collaborators

  • ianpogi5
  • mbungalso