npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

http-result

v0.5.6

Published

Rust+Go like error handling in typescript, simple, extensible and tweakable.

Downloads

648

Readme

http-result

http-result is a Typescript library that provides type-safe error handling and result types inspired by patterns used in Rust and Go. It originally was designed to complement ts-rest by offering a consistent and type-safe way to handle both successful responses and errors in API calls or service methods.

But it can be used for any backend TS application to represent internal error.

build and tests status badge

NPM Version JSR JSR Score


Features

  • Type-safe error handling: Guarantees correct error types through Typescript’s type system.
  • No surprises: Errors are not thrown, but are returned as normal values enabling lot more ways to handle errors and not be surprised.
  • Result type pattern: Emulates the result types from languages like Rust and Go, making error handling more predictable.
  • Easy integration with frameworks:
    • [x] ts-rest library for RESTful service calls.
    • [ ] express
    • [ ] fastify
    • [ ] koa

Optimised

  • [x] Tree shakeable
  • [x] No dependencies
  • [x] Small size

bundle phobia optimised


Installation

Install the http-result package via npm or yarn:

npm install http-result

Or with yarn:

yarn add http-result

Basic Usage

The core idea of http-result is to handle method responses as a Result type, which can either be a successful result with data or an error. This avoids unhandled errors and allows for more precise control over how errors are processed.

Example

Here’s an example using http-result to handle errors in a method that creates an organization:

Internal Service code

import { HttpErrorResults, Ok, Result } from 'http-result'

class OrganisationService {
 async createOrg({
  userId,
  name,
 }: {
  userId: ID
  name: string
 }): Promise<Result<Organisation, 'InternalServer' | 'NotFound'>> {
  // Simulate error handling
  if (!userId) {
   return Err('NotFound', 'User does not exist')
   // You can also use
   // return HttpErrorResults.NotFound('User does not exist')
  }

  if (name === 'Rick Astley') {
   return HttpErrorResults.InternalServerError('Server got rick rolled')
  }

  // error can be BadRequest | NotFound
  const [letter, letterError] = await this.letterService.sendLetter(name)

  if (letterError) {
   // repackage, preserves message from letterError in messages array
   // send better more relevant errors to users even if generic code fails.
   return HttpErrorResults.InternalServerError(
    'Failed to send letter',
    letterError,
   )
  }

  // Simulate successful organization creation
  const org = { id: '123', name }

  return Ok(org)
 }
}

API Gateway/Handler code

// caller function, API request handler in this case
import { tsRestError, TsRestResponse } from 'http-result/ts-rest'

const organisationService = new OrganisationService()

const [org, error] = await organisationService.createOrg({
 userId: '123',
 name: 'My Organization',
})

if (error.kind === 'NotFound') {
 // special handling, repackage the error to hid original
 return TsRestResponse.BadRequest('You made a mistake!')
}

if (error) {
 // forwar
 return tsRestError(error) // Return a structured error response
}

return TsRestResponse.Created(org) // Return a successful response

Explanation

  • The createOrg method returns a Result type with two possible outcomes:
    • Success: The result contains the created organization data (Organisation).
    • Error: The result contains an error, which can be either 'InternalServer' or 'NotFound'.

Format response according to frameworks:

  • If an error occurs, it is handled and passed to tsRestError() for a structured error response.
  • If successful, the organization data is passed to TsRestResponse.Created() to return a successful response. Status code is mostly manual.

Result Type

The result is returned as an object with the following structure:

export type Result<
 T,
 ErrorUnion extends 'NotFound' | 'InternalServer' | '...',
> = Success<T> | ErrType<ErrorUnion>

ErrorPayload

Error returned by the service has following structure.

export type ErrPayload<S extends IHttpErrorKind> = {
 status: IHttpErrorStatusSpecific<S>
 kind: S
 messages: string[]
}

Where:

  • T is the type of the successful data (e.g., Organisation).
  • E is the type of the error (e.g., 'InternalServer' | 'NotFound').

Handling Errors with ts-rest

http-result works seamlessly with ts-rest to provide a structured and type-safe error response in API calls. In the case of an error, you can pass the error message to tsRestError() to create a proper response.

import { TsRestResponse, tsRestError } from 'http-result'

async function getUserInfo(userId: ID) {
 const [user, error] = await getUserFromDatabase(userId)

 if (error) {
  return tsRestError(error) // format into ts-rest error
 }

 return TsRestResponse.Created(user) // format into ts-rest response
}

In the above example:

  • If there is an error (e.g., "User not found"), it’s passed to tsRestError(), ensuring the response is correctly structured and type-safe.
  • If the user is found, TsRestResponse.Ok() returns the successful result.

API

  • Result<T, E>: Represents the result of an operation, where:
    • T is the type of the successful result (data).
    • E is the type of the error.
  • TsRestResponse.(functions)<T>(data: T): Returns a successful response with the data of type T, for ts-rest
  • tsRestError<E>(error: E): Creates a structured error response with the given error, for ts-rest

Typescript Support

http-result leverages Typescript’s powerful type system to provide full type safety for both success and error scenarios. This ensures you catch any mismatches or unexpected behavior at compile time.


License

This project is licensed under the MIT License - see the LICENSE file for details.


Contributing

Feel free to open issues or submit pull requests for improvements, bug fixes, or new features!