1.1.8 • Published 4 years ago

respuesta v1.1.8

Weekly downloads
2
License
GPL-3.0-or-later
Repository
github
Last release
4 years ago

respuesta

HTTP Responses, status codes and errors.

Using status codes

import { CONTINUE, OK, BAD_REQUEST } from 'respuesta/Codes';

console.log(CONTINUE); // 100
console.log(OK); // 200
console.log(BAD_REQUEST); // 400

Using responses

All function has the shape:

function httpOk(payload?: Payload): HttpResponse {}

// With Payload and HttpResponse being
interface Payload {
  message?: string;
  data?: Record<string, unknown>; // an object
}

interface HttpResponse {
  statusCode: number;
  statusText: string;
  message?: string;
  errors?: string[];
  data?: Record<string, unknown>; // an object
}

Examples:

import { OK, CREATED } from 'respuesta/Codes';
import { httpOk, httpCreated } from 'respuesta';

router.get('/ok', (req, res) => {
  res.status(OK).json(httpOk());
});

router.get('/ok-with-data', (req, res) => {
  res.status(OK).json(httpOk({ data: { some: 'data' } }); // 'data' is optional
});

router.post('/created', (req, res) => {
  res.status(CREATED).json(httpCreated());
});

router.post('/created-with-message', (req, res) => {
  res.status(CREATED).json(httpCreated({ message: 'New element created.' }); // 'message' is optional
});

Using errors

All errors has the shape:

abstract class HttpException extends Error {
  readonly statusCode!: number;
  readonly name!: string;
  readonly isServer!: boolean;
  readonly errors!: string[];

  constructor(errors: string[], message: string) {
    // ...
  }
}

// Example
class HttpNotFound extends HttpException {
  readonly statusCode = NOT_FOUND;
  readonly name = 'NotFound';
  readonly isServer = false;

  constructor(errors: string[], message = 'Not found.') {
    super(errors, message);
  }
}

Examples:

import { HttpNotFound, HttpBadRequest } from 'respuesta/Errors';

router.get('/not-found', (req, res, next) => {
  try {
    throw new HttpNotFound(['Not Found']);
  } catch(err) {
    return next(err)
  }
}

// With custom message
router.get('/not-found-with-message', (req, res, next) => {
  try {
    throw new HttpNotFound(['Not found'], 'Custom Not Found message');
  } catch(err) {
    return next(err);
  }
}

// With more than one error
router.post('/bad-request', (req, res, next) => {
  try {
    throw new HttpBadRequest(['Username too long', 'Password too short']);
  } catch(err) {
    return next(err)
  }
}
1.1.8

4 years ago

1.1.7

4 years ago

1.1.6

4 years ago

1.1.5

4 years ago

1.1.4

4 years ago

1.1.3

4 years ago

1.1.2

4 years ago

1.1.1

4 years ago

1.1.0

4 years ago

1.0.0

4 years ago