npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@kdcio/api-gw-resp

v1.7.6

Published

API Gateway response builder

Downloads

19

Readme

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 | :ballot_box_with_check: | 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 | :ballot_box_with_check: | true | If true, will add cors in header | | origin | string | :ballot_box_with_check: | * | Set specific origin | | headers | object | :ballot_box_with_check: | {} | 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 | :ballot_box_with_check: | none | If true, status code will be 301. Otherwise it will be 302. | | location | bool | :ballot_box_with_check: | none | The new url where the resource has been moved. | | headers | object | :ballot_box_with_check: | {} | 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 | :ballot_box_with_check: | Status code name | Error name | | message | string | :white_check_mark: | 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 | :ballot_box_with_check: | Internal Server Error | Error name | | message | string | :white_check_mark: | 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 | :white_check_mark: | 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