1.0.5 • Published 7 years ago

es6-http-response v1.0.5

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

es6-http-response

npm JavaScript Style Guide

When you need a consistent way to handle HTTP responses. Uses ES6 class and extends keywords which also is the suggested way from Node.Js, as per their docs:

Note: Usage of util.inherits() is discouraged. Please use the ES6 class and extends keywords to get language level inheritance support.

Inspiration from the awesome http-errors module.

Installation

npm install es6-http-response

Usage

const HttpResponse = require('es6-http-response')

// Create a new Internal Server Error response
const error = HttpResponse.InteralServerError()

error instanceof HttpResponse.HttpError // true
error instanceof HttpResponse.Error // true

// Create a new Bad Request error with a custom message
const error = HttpResponse.BadRequest('ID must be a string')

// Create new HTTP status response
const status = HttpResponse.OK()

status instanceof HttpResponse.HttpStatus // true

Example with Express

const HttpResponse = require('es6-http-response')
const express = require('express')
const app = express()

/* ... business logic ... */

// Catch 404 error
app.use((req, res, next) => {
  next(HttpResponse.NotFound())
})

// Log error
app.use((err, req, res, next) => {
  console.error(err)
  next(err)
})

// If not a HTTP error, create an internal server error
app.use((err, req, res, next) => {
  err instanceof HttpResponse.HttpError ? next(err) : next(HttpResponse.InternalServerError())
})

// Handle error and respond to client
app.use((err, req, res, next) => {
  res.status(err.http_status).send(err.message)
})

/* ... */

Example with a custom setup

const HttpResponse = require('es6-http-response')

const errorHandler = error => {
  const checkError = error instanceof HttpResponse.HttpError
  return {
    http_status: checkError ? error.http_status : 500,
    message: checkError ? error.message : 'Internal Server Error',
    data: null
  }
}

const resultHandler = (data, status) => {
  const checkStatus = status instanceof HttpResponse.HttpStatus
  return {
    http_status: checkStatus ? status.http_status : 200,
    message: checkStatus ? status.message : 'OK',
    data
  }
}

/* ... */

return asyncOperation()
  .then(data => resultHandler(data, HttpResponse.Created()))
  .catch(errorHandler)

/* ... */

Methods

All method names are the corresponding HTTP message in PascalCase, e.g. HttpResponse.NotFound() results in a status 404 with message Not Found.

See http-errors for all method names.

Test

npm test

License

MIT

1.0.5

7 years ago

1.0.4

7 years ago

1.0.3

7 years ago

1.0.2

7 years ago

1.0.0

7 years ago