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

elm-decoders

v6.1.2

Published

A powerful, well tested, data decoder for Typescript.

Downloads

443

Readme

Decoder

A powerful, well tested, data decoder for Typescript.

API Documentation: Decoder Github: Decoder

Coverage Status Build Status

Table of Content

Install

Simply run

npm i elm-decoders

Or

yarn add elm-decoders

Then at the top of your file add:

import { Decoder } from 'elm-decoders';

Motivation

Typescript is great, however it provides no tools for checking runtime data. This means that we need a tool to check that incoming data follows the correct typings. If we do not validate the data, errors can occur anywhere in the code, introducing odd behaviors and tracking down where the error comes from becomes difficult. By instead validating our data at the start (for example when receiving an incoming request), we can handle the error early and give better error messages to the developer. This creates a better developer experience and gives us stronger guarantees that the code works correctly.

Another benefit of using Decoders is that you can pick the best data model for your problem and convert all incoming data sources to fit that model. This makes it easier to write business logic separately from the acquisition of the data.

Decoders are great for validating and converting data from various sources: Kafka, request bodies or APIs to name a few examples.

For more motivation, see this blog post

Tutorial

Decoder provides us with a few primitive decoders and a few methods to craft new ones. Let's say we have the following data:

const incomingData: any = {
  name: 'Nick',
  age: 30,
};

And we have an interface User:

interface User {
  name: string;
  age: number;
}

To validate that incomingData is a User, Decoder provides an object primitive.

import { Decoder } from 'elm-decoders';

const userDecoder: Decoder<User> = Decoder.object({
  name: Decoder.string,
  age: Decoder.number,
});

Now we can validate incomingData and ensure the data is correct.

const result = userDecoder.run(incomingData);

run returns a Discriminated union, meaning is returns either {type: "OK", value: T} or {type: "FAIL": error: string}. This means that we are forced to check if the data received is correct or contains an error. Doing so is as simple as a switch case:

switch (result.type) {
  case 'OK':
    doUserThing(result.value);
  case 'FAIL':
    handleError(result.error);
}

Decoder also provides a few methods for creating new decoders. For example, if we want to create a set decoder, we can use the map method.

const intSetDecoder: Decoder<Set<number>> = Decoder.array(Decoder.number).map(
  (numberArray) => new Set(numberArray)
);

If there is an error, Decoder will also generate a helpful error report:

> let userDecoder = Decoder.object({
    name: Decoder.string,
    auth: Decoder.object({
        jwt: Decoder.string
    })
})
> JSON.stringify(userDecoder.run({wrong: 'hi', auth: {wrongAgain: 'hi'}}))
'{"type":"FAIL","error":{"name":"Not a string","auth":{"jwt":"Not a string"}}}'

This was a brief introduction. From here, please check the API documentation to find out more what you can do and try it for yourself!

Credit

This library is essentially a rewrite of Nvie's decoders.js with some small changes. decoders.js is inspired by Elm's decoders.

Alternatives

  • Joi. The currently most popular validator for data. While it is useful for Javascript, it's Typescript support is lackluster as it has no way of ensuring that a validator actually adheres to a certain type. This means that on top of writing the validator, you will have to also manually write unit tests to ensure that your validator adheres to your type or interface. This creates way too much boilerplate or relies on the developer to not make mistakes. See also this blog post.
  • decoders.js. Features a different syntax but has a similar goal. It also contains two more dependencies compared to this library which has none.

Local Development

Below is a list of commands you will probably find useful.

npm start or yarn start

Runs the project in development/watch mode. Your project will be rebuilt upon changes. TSDX has a special logger for you convenience. Error messages are pretty printed and formatted for compatibility VS Code's Problems tab.

Your library will be rebuilt if you make edits.

npm run build or yarn build

Bundles the package to the dist folder. The package is optimized and bundled with Rollup into multiple formats (CommonJS, UMD, and ES Module).

npm test or yarn test

Runs the test watcher (Jest) in an interactive mode. By default, runs tests related to files changed since the last commit.