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

computer-says-no

v0.3.0

Published

Super simple type-safe and serializable error management in TypeScript.

Downloads

92

Readme

Install

npm add computer-says-no
yarn add computer-says-no

Features

  • Easy Error definitions and type assertions
  • Works for errors that have been serialized (via an API as JSON)
  • i18n friendly

Usage

Let's pretend we have a login function.

function login(emailAddress: string, password: string) {
  ...
}

Before we implement it, let's define some errors this function could return.

import { defineError } from 'computer-says-no';

const InvalidCredentialsError = defineError(
  'INVALID_CREDENTIALS',
  'Invalid E-mail and Password combination'
);

const FieldRequiredError = defineError(
  'FIELD_REQUIRED',
  (fieldName: string) => `${fieldName} is required`)
);

Now we can write our login function. Notice we are returning the errors rather than throwing them, but if you prefer to throw errors that's cool too!

function login(emailAddress: string, password: string) {
  if (!emailAddress) {
    return new FieldRequiredError('Email');
  }

  if (!password) {
    return new FieldRequiredError('Password');
  }

  const userId = getMatchingUserId(emailAddress, password);
  if (!userId) {
    return new InvalidCredentialsError();
  }

  const authToken = getAuthTokenForUser(userId);
  return { authToken };
}

Note the return type of our login function will be (more or less):

| { code: 'FIELD_REQUIRED', message: string }
| { code: 'INVALID_CREDENTIALS', message: string }
| { authToken: string }

This makes it easy to check which result we got back when we call our login function (ignore the alert calls, this is just an example 😛).

import { isError } from 'computer-says-no';

function handleLoginSubmit() {
  const loginResult = login(emailAddress, password);

  if (isError(loginResult)) {
    alert(loginResult.message);
    return;
  }

  localStorage.setItem('authToken', loginResult.authToken);
  alert('Login successful');
}

Checking for specific error types

We can improve our login function validation if we set focus the field that has an issue.

Let's change our FieldRequiredError to include the name of the field.

const FieldRequiredError = defineError(
  'FIELD_REQUIRED',
  (fieldName: string) => ({
    message: `${fieldName} is required`,
    fieldName
  })
);

Now the FieldRequiredError will include a fieldName property. Let's update our login handler function.

function handleLoginSubmit() {
  const loginResult = login(emailAddress, password);

  if (FieldRequiredError.is(loginResult)) {
    const input = document.getElementById(loginResult.fieldName);
    input.focus();
  }

  if (isError(loginResult)) {
    alert(loginResult.message);
    return;
  }

  localStorage.setItem('authToken', loginResult.authToken);
  alert('Login successful');
}

But why?

Why not just create Error sub-classes and use the instanceof operator instead?

class FieldRequiredError extends Error {
    constructor(readonly fieldName: string) {
        super(`${fieldName} is required`);
    }
}

...

function handleLoginSubmit() {
  const loginResult = login(emailAddress, password);

  if (loginResult instanceof FieldRequiredError) {
    const input = document.getElementById(loginResult.fieldName);
    input.focus();
  }

  if (loginResult instanceof Error) {
    alert(loginResult.message);
    return;
  }

  localStorage.setItem('authToken', loginResult.authToken);
  alert('Login successful');
}

Well, the above is pretty elegant and requires no library. But sadly it doesn't scale if you're working on a monorepo and return errors from your API that you need to check for in your client. The instanceof operator will stop working.

This is where computer-says-no shines. Errors can be serialized to JSON and parsed back into plain old JS objects and all the type assertions will still work.

Using with GraphQL / Rest APIs

Errors instantiated by computer-says-no will include a property named csn. This is a signature the library includes that is essential for internally asserting that an error is a computer-says-no error.

You don't normally need to worry about it, except that this property must be included during any serialization. For example when resolving errors in GraphQL you must be sure GraphQL knows about and includes the csn property on the error type it resolves.

Contributing

Got an issue or a feature request? Log it.

Pull-requests are also welcome. 😸