handle-res

2.0.0 • Public • Published

handleRes

JavaScript Style Guide

codecov CircleCI

A small (< 60 loc) helper library to handle response calls in express like frameworks.

Install

npm install handle-res

Usage

The handleRes module is split into 2 main methods, .accept, and .reject.

The reason that .reject sends back the Status: OK http code is to allow developers to create their own failure context. Use .reject when you are able to determine the error. For example, if a user enters a wrong password to your verifyLogin route, you should do:

app.get('/verifyLogin', function (req, res) {
  // check is password is valid somehow
  const passwordValid = false
  if (!passwordValid) {
    return handleRes(res).reject(
      'Password invalid',
      401, // this could be any code you want
      { /* and you can add extra context here */ }
    })
  }
})

Of course the above could be made more sophisticated via automatic error codes, custom error types, etc.

Quick Reference

const express = require('express')
const handleRes = require('handle-res')
 
const app = express()
 
app.get('/success', function (req, res) {
  // .accept appends a truthy ok flag to the response body
  let sent = handleRes(res).accept({
    // json body
    data: {}
  })
 
  // the above will call res.status(200).json({ ok: true, data: {} })
 
  console.log(sent) // true
 
  sent = handle(res).accept({
    data2: {}
  })
 
  // the above will not be sent, because we have already responded to the request
  console.log(sent) // false
})
 
app.get('/known-failure', function (req, res) {
  // .reject accepts a message, code, and trace object
  handleRes(res).reject('Known failure!', 418, {
    route: req.originalUrl,
    code: 102301
  })
 
  /**
   * the above will call
   * res.status(418).json({
   *   ok: false,
   *   message: 'Known failure!',
   *   status: 418,
   *   trace: {
   *     route: '/known-failure'
   *     code: 102301
   *   }
   * })
   */
})

API

Api documentation, generated by jsdoc

Dependencies (0)

    Dev Dependencies (14)

    Package Sidebar

    Install

    npm i handle-res

    Weekly Downloads

    3

    Version

    2.0.0

    License

    MIT

    Unpacked Size

    9.34 kB

    Total Files

    4

    Last publish

    Collaborators

    • jtaks
    • emiphil