New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details →
Socket
Book a DemoSign in
Socket

handle-res

Package Overview
Dependencies
Maintainers
1
Versions
4
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

handle-res

A small helper library to handle response calls in express-like frameworks

latest
Source
npmnpm
Version
2.0.0
Version published
Maintainers
1
Created
Source

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

Keywords

express

FAQs

Package last updated on 19 Apr 2018

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts