1.7.6 • Published 3 years ago

@kdcio/api-gw-resp v1.7.6

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

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

MethodCodeDescription
OK200Request has succeeded and the message body contains the requested information.
CREATED201Request has succeeded and a new resource has been created. The message body may contain information about the new resource.
NO_CONTENT204Request has succeeded but there is no content to be returned.

Options

OptionTypeRequiredDefaultDescription
bodyobject, string or null:ballot_box_with_check:nullobject 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.
corsbool:ballot_box_with_check:trueIf true, will add cors in header
originstring:ballot_box_with_check:*Set specific origin
headersobject:ballot_box_with_check:{}Specify additional headers

Examples:

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

Redirect responses

MethodCodeDescription
REDIRECT301 or 302The URI of the requested resource has moved. The new URI can be found in the Location header.

Options

OptionTypeRequiredDefaultDescription
permanentbool:ballot_box_with_check:noneIf true, status code will be 301. Otherwise it will be 302.
locationbool:ballot_box_with_check:noneThe new url where the resource has been moved.
headersobject:ballot_box_with_check:{}Specify additional headers

Examples:

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

Client Error responses

MethodCodeDescription
BAD_REQUEST400The server could not understand the request due to invalid syntax or missing parameters.
UNAUTHORIZED401The client must authenticate itself to get the requested response.
FORBIDDEN403The client is not allowed to access the requested resource. Unlike 401, the client's identity is known to the server.
NOT_FOUND404The server can not find the requested resource.
CONFLICT409This response is sent when a request conflicts with the current state of the server. Usually duplicate of data.

Options

OptionTypeRequiredDefaultDescription
errorstring:ballot_box_with_check:Status code nameError name
messagestring:white_check_mark:noneError 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

MethodCodeDescription
SERVER_ERROR500The server has encountered a situation it doesn't know how to handle.

Options

OptionTypeRequiredDefaultDescription
errorstring:ballot_box_with_check:Internal Server ErrorError name
messagestring:white_check_mark:noneError message

Examples:

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

Auto Detect Error responses

MethodDescription
ERRORThis will auto detect which error code to send based on the message.

Options

OptionTypeRequiredDefaultDescription
messagestring:white_check_mark:noneError message

Error Messages

Error ResponseRegex 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

1.7.6

3 years ago

1.7.5

3 years ago

1.7.4

3 years ago

1.7.3

3 years ago

1.7.1

3 years ago

1.7.0

3 years ago

1.6.0

3 years ago

1.4.0

3 years ago

1.3.1

3 years ago

1.3.0

4 years ago

1.2.0

4 years ago