Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@reflet/http

Package Overview
Dependencies
Maintainers
1
Versions
7
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@reflet/http

Low-level TypeScript HTTP-related modules

  • 1.0.0
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
813
increased by24.88%
Maintainers
1
Weekly downloads
 
Created
Source

@reflet/http 🌠

Ultra typed, (over) documented, and neatly organised HTTP primitives. Built with a simple and discoverable API surface, for a great developper experience.

  • Getting started
  • Status 🎰
  • Header 📰
  • HttpError 💢

Getting started

Requires at least typescript 4.0.

npm i @reflet/http

Status 🎰

Ultra typed, over documented, and neatly organised HTTP status enums, to use for a great developper experience.

Usage

import { Status } from '@reflet/http'

res.sendStatus(Status.Created)

Enums

Status enum has every status and also the following sub enums:

  • Information for 1xx responses.
  • Success for 2xx responses.
  • Redirection for 3xx responses.
  • ClientError for 4xx responses.
  • ServerError for 5xx responses.
  • Error for 4xx and 5xx responses.
import { Status, HttpError } from '@reflet/http'

throw HttpError(Status.ClientError.Forbidden)

These enums are actually object litterals with a const assertion.`

Unions

When use as a type, each category is a union of corresponding status codes.

import { Status } from '@reflet/http'

function redirect(status: Status.Redirection, url: string) {
  // ...
}

Header 📰

Usage

import { Header } from '@reflet/http'

const type = req.header(Header.ContentType)

Enums

Header enum is composed of the following exported enums:

  • RequestHeader for the HTTP request headers.
  • ResponseHeader for the HTTP response headers.
import { RequestHeader, ResponseHeader } from '@reflet/http'

req.get(RequestHeader.XForwardedFor)
res.set(ResponseHeader.Allow, 'GET')

These enums are actually object litterals with a const assertion.`

Unions

When use as a type, each category is a union of corresponding headers.

import { Header, ResponseHeader } from '@reflet/http'

function setHeader(name: ResponseHeader, value: string) {
  //...
}

Augmentations

If your application has custom headers, you can augment the union type (but not directly the enum value) with the dedicated global namespace RefletHttp:

declare global {
  namespace RefletHttp {
    interface RequestHeader {
      XCustom: 'x-custom'
    }

    interface ResponseHeader {
      XCustom: 'x-custom'
    }
  }
}

HttpError 💢

Usage

import { HttpError } from '@reflet/http'

throw HttpError(400)
throw HttpError(500, 'My bad')

Attached properties

status

The resulting error has a status property that will be used, for example by Express and Fastify error handlers, to properly set the HTTP response status.

name

The resulting error name property will be inferred from status: e.g. "NotFound" for 404.

If you use a unknown error status code, the error name will be "HttpError".

Need more?

Have a look at the Augmentations section.

Enumerability

To respect the inherited Error, non-enumerable properties are kept non-enumerable: name, message, stack.
They won't be serialized by JSON.stringify (MDN reference).

Dedicated static methods

Instead of passing the status code, the known HTTP errors are exposed as static methods: List of HTTP errors.

throw HttpError.Unauthorized('Get out')
// HttpError { status: 400, name: 'Unauthorized', message: 'Get out' }

throw HttpError.InternalServerError('My bad') 
// HttpError { status: 500, name: 'InternalServerError', message: 'My bad' }

Optional new keyword

You can instantiate HttpError with or without the new keyword, just like the built-in Error constructor.

throw HttpError(401)

The compiler is okay with both. 👌

Augmentations

By default, the only parameter you can pass besides the status code is message?: string. You might want your error objects to have more details.

The global namespace RefletHttp gives the possibility, for each different status, to change the optional message parameter to a required data object parameter. This object's properties will be attached to the resulting error (at runtime and compile time).

export {} // necessary to be in a module file

declare global {
  namespace RefletHttp {
    interface Forbidden {
      access: 'read' | 'create' | 'update' | 'delete'
      target: string
    }

    // Could be useful for custom headers since frameworks usually set the response headers with the error headers property:
    interface MethodNotAllowed {
      headers: {
        allow: ('GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE')[]
      }
    }
  }
}

throw new HttpError(403, { access: 'read', target: 'user' })
// HttpError { status: 400, name: 'Forbidden', access: 'read', target: 'user' }

throw HttpError.MethodNotAllowed({ headers: { allow: ['GET'] } })
// HttpError { status: 505, name: 'MethodNotAllowed', headers: { allow: ['GET'] } }

Every known HTTP error is available for augmentation under its own name: List of HTTP errors.

Custom Errors

Use both the CustomErrors interface and the defineCustomErrors function to create new static methods associated with their status.

declare global {
  namespace RefletHttp {
    interface CustomErrors {
      299: 'Aborted'
      420: 'EnhanceYourCalm'
    }
  }
}

// You must define the new errors at runtime, in order for the static methods to exist.
defineCustomErrors({ 299: 'Aborted', 420: 'EnhanceYourCalm' })
Constraints

With the ErrorConstraint interface, you can whitelist the errors you application uses.

declare global {
  namespace RefletHttp {
    interface ErrorConstraint {
      status: 400 | 401 | 403 | 404 | 405 | 422 | 500
      // or widen to all numbers with `status: number`
    }
  }
}
message property stringification

If you define a message property with different type than string, like so:

declare global {
  namespace RefletHttp {
    interface BadRequest {
      message: Record<string, any>
    }
  }
}

it will always be stringified to respect the original Error interface (at runtime and compile time).

So:

throw HttpError(400, { message: { about: 'thing' } })

gives the following stack trace:

BadRequest: {"about":"thing"} # instead of "BadRequest: [Object object]"
    at ...
Protections

Since these augmentations affect the error object itself, you cannot define the following properties: name, status, stack, __proto__, constructor, prototype.

List of HTTP errors

StatusName
400BadRequest
401Unauthorized
402PaymentRequired
403Forbidden
404NotFound
405MethodNotAllowed
406NotAcceptable
407ProxyAuthenticationRequired
408RequestTimeout
409Conflict
410Gone
411LengthRequired
412PreconditionFailed
413PayloadTooLarge
414URITooLong
415UnsupportedMediaType
416RequestedRangeNotSatisfiable
417ExpectationFailed
418ImATeapot
421MisdirectedRequest
422UnprocessableEntity
423Locked
424FailedDependency
425UnorderedCollection
426UpgradeRequired
428PreconditionRequired
429TooManyRequests
431RequestHeaderFieldsTooLarge
451UnavailableForLegalReasons
500InternalServerError
501NotImplemented
502BadGateway
503ServiceUnavailable
504GatewayTimeout
505HTTPVersionNotSupported
506VariantAlsoNegotiates
507InsufficientStorage
508LoopDetected
509BandwidthLimitExceeded
510NotExtended
511NetworkAuthenticationRequired

Keywords

FAQs

Package last updated on 30 Jul 2023

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

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc