Coder Social home page Coder Social logo

node-http-status's Introduction

Build Status

HTTP Status codes for Node.js

Utility to interact with HTTP status codes.

Usage

Once you require this module, you may call it with either an HTTP code or a message name. With an HTTP code, you will get the message name while with a message name you will get an HTTP code.

HTTP Status codes

HTTP code names, messages, and classes are respectively accessible with the property {code}_NAME, {code}_MESSAGE and {code}_CLASS. This includes all statuses in the IANA HTTP Status Code Registry, with the only addition being 418 I'm a teapot.

Extra status code are also made available that are not defined in the IANA registry, but used by popular software. They are grouped by category. Specific properties are exported by http-status under the property extra followed by the category name. Also, extra codes are merge with regular status codes and made available as modules available inside http-status/lib/{category}.

Available categories are:

unofficial
This represent a list of codes which are not specified by any standard.
iis
Microsoft's Internet Information Services (IIS) web server expands the 4xx error class to signal errors with the client's request.
nginx
The NGINX web server software expands the 4xx error class to signal issues with the client's request.
cloudflare
Cloudflare's reverse proxy service expands the 5xx error class to signal issues with the origin server.

HTTP Status code classes

In addition to HTTP status codes, this module also contains status code classes under the classes property. Similar to HTTP codes, you can access class names and messages with the property {class}_NAME and {class}_MESSAGE

API

The API is structured as follows:

100
100_NAME
100_MESSAGE
100_CLASS
CONTINUE
101
101_NAME
101_MESSAGE
101_CLASS
SWITCHING_PROTOCOLS
…
classes.
├── 1xx
├── 1xx_NAME
├── 1xx_MESSAGE
├── INFORMATIONAL
├── 2xx
├── 2xx_NAME
├── 2xx_MESSAGE
├── SUCCESSFUL
├── …
extra.
├── unofficial.
│   ├── 103
│   ├── 103_NAME
│   ├── 103_MESSAGE
│   ├── 103_CLASS
│   ├── CHECKPOINT
│   ├── …
├── iis.
│   ├── 440
│   ├── 440_NAME
│   ├── 440_MESSAGE
│   ├── 440_CLASS
│   ├── LOGIN_TIME_OUT
│   ├── …
├── nginx.
│   ├── 444
│   ├── 444_NAME
│   ├── 444_MESSAGE
│   ├── 444_CLASS
│   ├── NO_RESPONSE
│   ├── …
├── cloudflare.
│   ├── 520
│   ├── 520_NAME
│   ├── 520_MESSAGE
│   ├── 520_CLASS
│   ├── UNKNOWN_ERROR
│   ├── …

For additional information, please refer to original code.

Example usage

const status = require('http-status');

console.info(status.INTERNAL_SERVER_ERROR);
// Output: 500

console.info(status[500]);
console.info(status[status.INTERNAL_SERVER_ERROR]);
// Both output: "Internal Server Error"

console.info(status['500_NAME']);
console.info(status[`${status.INTERNAL_SERVER_ERROR}_NAME`]);
// Both output: "INTERNAL_SERVER_ERROR"

console.info(status['500_MESSAGE']);
console.info(status[`${status.INTERNAL_SERVER_ERROR}_MESSAGE`]);
// Both output: "A generic error message, given when an unexpected condition was encountered and no more specific message is suitable."

console.info(status['500_CLASS']);
console.info(status[`${status.INTERNAL_SERVER_ERROR}_CLASS`]);
// Both output: "5xx"

Example using classes

const status = require('http-status');

const responseCode = status.INTERNAL_SERVER_ERROR;

switch (status[`${responseCode}_CLASS`]) {
  case status.classes.INFORMATIONAL:
    // The responseCode is 1xx
    break;
  case status.classes.SUCCESSFUL:
    // The responseCode is 2xx
    break;
  case status.classes.REDIRECTION:
    // The responseCode is 3xx
    break;
  case status.classes.CLIENT_ERROR:
    // The responseCode is 4xx
    break;
  case status.classes.SERVER_ERROR:
    // The responseCode is 5xx
    break;

  default:
    // Unknown
    break;
}

Example using the extra property

// Accessing property from the NGINX category
const status = require('http-status');
console.info(status.extra.nginx.NO_RESPONSE)
// Accessing default HTTP status merged with NGINX status
const status = require('http-status/lib/nginx');
console.info(status.IM_A_TEAPOT);
console.info(status.NO_RESPONSE)

Example integrating Express

const express = require('express'),
      redis   = require('redis'),
      status  = require('http-status');
// New Express HTTP server
const app = express.createServer();
// Regster a route
app.get('/', (req, res) => {
  const client = redis.createClient();
  client.ping((err, msg) => {
    if (err) {
      return res.send(status.INTERNAL_SERVER_ERROR);
    }
    res.send(msg, status.OK);
  });
});
// Start the HTTP server
app.listen(3000);

Contributors

This package is developed by Adaltas.

Developers

To automatically generate a new version:

yarn run release

Package publication is handled by the CI/CD with GitHub action.

node-http-status's People

Contributors

aronmal avatar chrishelgert avatar ckeboss avatar coryallegory avatar daxadal avatar denizdogan avatar doong-jo avatar gasi avatar gokaygurcan avatar iandotkelly avatar jamsesso avatar johdougss avatar jonatancolussi avatar knor-el-snor avatar onchainguy-eth avatar osdiab avatar retro64 avatar schantaraud avatar tomfun avatar wdavidw avatar wolfgang42 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

node-http-status's Issues

Error TS2714 with TypeScript definition file

I think there's an issue with the TS definition file that was added recently in 1.1.1. I did an npm update today and now I'm getting the following build error. This error does not occur in using version 1.1.0.

We're using TypeScript 2.8.3.

C:/Work/Journeys/radar/client/node_modules/http-status/lib/index.d.ts(1,10): error TS2714: The expression of an export assignment must be an identifier or qualified name in an ambient context.

add 424 status

FAILED_DEPENDENCY - 424

424 Failed Dependency (WebDAV; RFC 4918)
The request failed due to failure of a previous request (e.g., a PROPPATCH).[17]
from here

17 is

Unable to properly infer numeric keys in TypeScript type with mixed key types

Describe the bug

When utilizing the http-status package, there is a bug related to inferring numeric keys in TypeScript when working with a mixed type declaration within the HttpStatus interface in index.d.ts.

To Reproduce

To reproduce the issue, consider the following TypeScript code snippet:

import httpStatus from "http-status"; // object itself
import type { HttpStatus } from "http-status"; // interface

// example for comparison
const testStatus = {
  100: "",
  "100_NAME": "",
  "100_MESSAGE": "",
  CONTINUE: 100,
  101: "",
  "101_NAME": "",
  "101_MESSAGE": "",
  SWITCHING_PROTOCOLS: 101,
  102: "",
  "102_NAME": "",
  "102_MESSAGE": "",
  PROCESSING: 102,
  103: "",
  "103_NAME": "",
  "103_MESSAGE": "",
  EARLY_HINTS: 103,
};

// Define a custom type to extract numeric keys
type NumberKeys<T> = {
  [K in keyof T]: T[K] extends number ? (string extends K ? never : K) : never;
}[keyof T];

// Define a function with a parameter that should only accept numeric keys
export function Response(code: NumberKeys<HttpStatus>) {
  const thisCode = httpStatus[code];
  // Rest of your function logic
}

In this case, the types do not work correctly and autocompletion does show any possible string in the ide
image

When changing the type input to the example object:

- export function Response(code: NumberKeys<HttpStatus>) {
+ export function Response(code: NumberKeys<typeof test>) {
    const thisCode = httpStatus[code];
    // Rest of your function logic
  }

it then works and shows the correct types

image

Additionally, the unnecessary declaration readonly [key: number]: string | undefined; in the HttpStatus interface contributes to the issue and might be impacting TypeScript type inference.

Additional context

The issue seems to be associated with the mixed type declaration within the HttpStatus interface in index.d.ts, specifically:

export = httpStatus;

declare const httpStatus: httpStatus.HttpStatus;

declare namespace httpStatus {
  interface HttpStatus {
    // not important for this issue, but I still see no sense in this either
    readonly [key: number]: string | undefined;

    // this causes the issue
    readonly [key: string]:
    | string
    | number
    | HttpStatusClasses
    | HttpStatusExtra
    | undefined;

This declaration allows for both string and number keys, leading to unexpected behavior in TypeScript type inference. The bug impacts TypeScript type inference in projects utilizing the http-status package, particularly when trying to enforce strict typing for numeric keys. The unnecessary readonly [key: number] declaration are causing the issue and should be considered for removal.

Support for unofficial codes?

Would this project be willing to include non-standard codes as well? I recently ran into a 521 HTTP response, which is apparently Cloudflare's custom HTTP status code for when the origin server is down.

Chasing that status down, I discovered that both nginx and ISS also use their own custom codes. Seeing as how the users of this module are already doing it to lookup status messages for codes, I think there's value in including those as well.

More about the codes here - https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#Unofficial_codes

Can I send a PR?

Modify interface typing

Hello, Thanks for your great work.

I followed up your example.

const status = require('http-status');
 
console.info(status.INTERNAL_SERVER_ERROR);
// Output: 500
 
console.info(status[500]);
console.info(status[status.INTERNAL_SERVER_ERROR]);
// Both output: "Internal Server Error"
 
console.info(status['500_NAME']);
console.info(status[`${status.INTERNAL_SERVER_ERROR}_NAME`]);
// Both output: "INTERNAL_SERVER_ERROR"
 
console.info(status['500_MESSAGE']);
console.info(status[`${status.INTERNAL_SERVER_ERROR}_MESSAGE`]);
// Both output: "A generic error message, given when an unexpected condition was encountered and no more specific message is suitable."
 
console.info(status['500_CLASS']);
console.info(status[`${status.INTERNAL_SERVER_ERROR}_CLASS`]);
// Both output: "5xx"

but I met the error below in typescript.

// in typescript
import httpStatus from 'http-status'

httpStatus[httpStatus.BAD_REQUEST] // error
httpStatus[`${httpStatus.BAD_REQUEST}`],  // error
httpStatus[400],  // fine
/* 
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'HttpStatus'.
  No index signature with a parameter of type 'string' was found on type 'HttpStatus'
*/
// in javascript
import httpStatus from 'http-status'

httpStatus[httpStatus.BAD_REQUEST] // fine
httpStatus[`${httpStatus.BAD_REQUEST}`],  // fine

Do you have any other ideas? In my expectation, to fix this, I think the type defined in the interface needs to be modified. Your typing is great. However, I think it should be modified as below so that JavaScript and TypeScript can behave the same in the same code.

export = httpStatus;

declare const httpStatus: httpStatus.HttpStatus;

declare namespace httpStatus {
	
	interface HttpStatus {
          [key:string] : string | number; // like this..
          ...

Types are incorrect - lib returns undefined for unknown status codes

The library returns undefined for unknown status codes, which is not reflected in the types.

import * as HttpStatus from 'http-status';

const ok = HttpStatus[200];
const thisIsUndefinedAndNotAString = HttpStatus[777];

console.log(typeof ok); // prints string
console.log(ok); // prints ok
console.log(typeof thisIsUndefinedAndNotAString); // this prints undefined
console.log(thisIsUndefinedAndNotAString); // this prints undefined

So I guess this would be a rather correct type:

declare namespace httpStatus {
  interface HttpStatus {
    readonly [key: number]: string | undefined

    readonly [key: string]:
      | string
      | number
      | HttpStatusClasses
      | HttpStatusExtra
      | undefined;

For convenience - as the lib might quite often be used to trace foreign messages, where you might not rely on correct content - the types might even be extended (last lines to give concrete values priority) with:

readonly [key: undefined]: undefined

or

readonly [key: unknown]: undefined

But these are really optional and opinionated.

I might provide a PR with the fix and/or the feature, if it is accepted

Double 420

// 420 (Spring Framework) - A deprecated response used by the Spring Framework when a method has failed.
420: 'Method Failure',
'420_NAME': 'METHOD_FAILURE',
'420_MESSAGE': 'A deprecated response used by the Spring Framework when a method has failed.',
METHOD_FAILURE: 420,
// 420 (Twitter) - Returned by version 1 of the Twitter Search and Trends API when the client is being rate limited; versions 1.1 and later use the 429 Too Many Requests response code instead.
420: 'Enhance Your Calm',
'420_NAME': 'ENHANCE_YOUR_CALM',
'420_MESSAGE': 'Returned by version 1 of the Twitter Search and Trends API when the client is being rate limited; versions 1.1 and later use the 429 Too Many Requests response code instead.',
ENHANCE_YOUR_CALM: 420,

Good luck to deal with that

Expose status code series?

Would you be interested in a pull request including the status code series? Spring does this with it's HttpStatus utility: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/HttpStatus.Series.html

Something like

{
  100: 'Continue',
  '100_NAME': 'CONTINUE',
  '100_MESSAGE': 'The server has received the request headers and the client should proceed to send the request body.',
  '100_SERIES': extra.series.INFORMATIONAL
  CONTINUE: 100,
}

Would allow functionality such as:

const responseStatus = status.METHOD_NOT_ALLOWED

if (status[`${responseStatus}_SERIES`] === status.extra.series.CLIENT_ERROR) {

}

doc bug: s/_CODE/_NAME/

Doc example:

console.info(status['500_CODE']);

When in fact need to use 500_NAME key.

Thx

intl

Any plan on supporting multi-language? Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.