2.0.1 • Published 2 years ago

standard-rest-response v2.0.1

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

NPM Version CI codecov

Standard REST Response

Tools for building standard responses for REST APIs.

Table of Contents

Features

  • 💥 Simple classes for http status codes.
  • 🚀 Middleware to catch errors.
  • 🔎 Detect http errors with instanceof.
  • 🏄‍♂️ Zero dependencies.
  • 🎉 Written in TypeScript.

Installation

npm install standard-rest-response --save

Usage

Errors

Predefined classes for common HTTP status codes.

import { BadRequest } from 'standard-rest-response';

throw new BadRequest(`That doesn't work`);
StatusClass
400BadRequest
401Unauthorized
403Forbidden
404NotFound
405MethodNotAllowed
406NotAcceptable
408RequestTimeout
409Conflict
410Gone
412PreconditionFailed
413PayloadTooLarge
415UnsupportedMediaType
418ImATeaPotSupported
421Misdirected
422UnprocessableEntity
500InternalServerError
501NotImplemented
502BadGateway
503ServiceUnavailable
504GatewayTime
505HttpVersionNotSupported

You can also use the base HttpError class to return any status.

import { HttpError } from 'standard-rest-response';

throw new HttpError(999, 'Something crazy!');

Middleware

Provide catch and response to HTTP errors with frameworks like ExpressJS.

Note: In Express v5, this works with routes that return a promise, like async functions. In older versions of Express, use express-async-errors.

import { catchHttpErrors, UnprocessableEntity } from 'standard-rest-response';

app.use(catchHttpErrors);

app.get('/', async (res, req) => {
  if (!res.user) {
    throw new Unauthorized('Nice try');
  }

  // ...
});

Development

npm install
npm run build