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

@unruly-software/value-object

v0.0.2

Published

<p> <a href="https://www.npmjs.com/package/@unruly-software/result"> <img src="https://img.shields.io/npm/v/%40unruly-software%2Fresult" alt="npm package"> </a> </p>

Downloads

1

Readme

@unruly-software/result

Getting started

Installation

yarn add @unruly-software/result

pnpm i @unruly-software/result

npm i @unruly-software/result

Usage

Until full documentation is written most methods have hoverable documentation written in JSDoc comments.

import { Result } from '@unruly-software/result'

Result.invokeAsync(getUser, userId) // AsyncResult<User, Error>
Result.wrapAsync(getUser) // (string) => AsyncResult<User, Error>

Why?

Result is an elegant sync/async error wrapper similar to the Either Monad but intended for practical use in most Typescript codebases.

Encode error types for methods

Errors can be explicitly typed allowing consumers of your module to know exactly what can go wrong when they use your code.

In the following example it's clear that we may want to explicitly handle the NotFound error thrown by find and if we hit a rate limit we may want to retry after some amount of time has passed.

interface UserRepo {
    all(): AsyncResult<User[], RateLimitError>
    find(userId: string): AsyncResult<User, NotFound | RateLimitError>
}

Simplify error handling

Error handling can quickly become complex when writing to interfaces such as the classic Express request/response handler.

Here is a slightly complex handler:


const getUserPosts = async (req, res) => {
    let user: User
    try {
        user = await authorize(req)
    } catch(e) {
        console.error(e)
        res.status(500).send('Something went wrong')
        return;
    }

    let posts: Post[]
    try {
        posts = await getPostsForUser(user)
    } catch(e) {
        console.error(e)
        res.status(500).send('Something went wrong')
        return;
    }

    res.send(200).json({ posts })
}

We can use the Result.invokeAsync method to wrap errors as part of our normal flow instead.

const getUserPosts = async (req, res) => {
  await Result.invokeAsync(authorize, req)
    .mapAsync(getPostsForUser)
    .tap(
        (posts) => res.send(200).json({ posts }),
        (error) => {
            console.error(error)
            res.send(500).send('Something went wrong') 
        }
    )
}

Map between async and sync code seamlessly

The most unique aspect of this library is its first class treatment of async errors. The types Result<T, E> and AsyncResult<T, E> can be converted to on the fly using helper methods.

Since AsyncResult is a Thenable it works anywhere promises do and we can simply await the result for it to run to completion.

const getUserAsync = Result.wrapAsync(getUser)

getUser(userId) // AsyncResult<User>

// Awaiting the result converts it to normal result
const userResult = await getUser(userId) // Result<User>


const posts = userResult.mapAsync(loadPostsForUser) // AsyncResult<Post[]>

// We can explicitly unwrap the result causing it to throw
await posts.get() // Post[]

// We could also safely return an error or the value
await posts.getEither() // Post[] | Error

// We can call .map() to synchronously transform the value
await posts.map(post => p.name) // AsyncResult<string>

const awaited = await posts // Result<Post[]>

// Calling .mapAsync() turns the result back into an AsyncResult allowing
further chaining.
awaited.mapAsync(getAuthorForPosts) // AsyncResult<Author[]>