@eeue56/adeilad
TypeScript icon, indicating that this package has built-in type declarations

0.0.2 • Public • Published

adeilad

Ensure JSON has the correct structure at runtime, inspired by Elm's decoders and the pipeline decoder package.

These functions are best used at the surface points where JSON comes into your program: either via an API call, user input, or some untyped library.

Part of the Hiraeth collection.

Installation

npm install --save @eeue56/adeilad

Example usage

Imagine you have some API that gives you JSON, for example:

import { decode, pipeline, required, string, number, array } from "@eeue56/adeilad";


// fetched via a http request
const someExampleData = {
    name: "Noah",
    age: 28,
    pets: [
        { name: "Frodo", age: 8 },
        { name: "Fiver", age: 3 },
    ]
};

type Pet = {
    name: string;
    age: number;
}

function Pet(name: string, age: number): Pet {
    return {
        name,
        age
    }
}

type Person = {
    name: string;
    age: number;
    pets: Pet[]
}

function Person(name: string, age: number, pets: Pet[]): Person{
    return {
        name,
        age,
        pets
    }
}

const petDecoder = pipeline([
    required("name", string()),
    required("age", number())
])

const personDecoder = pipeline([
    required("name", string()),
    required("age", number()),
    required(pets, array(petDecoder))
]))

const result = decode(personDecoder, person);

switch (result.kind) {
    "ok": {
        console.log("Got a valid person:", result.value);
    },
    "err": {
        console.error("Invalid person:", res.error);
    }
}

Docs

See docs

You may also want to see the Result type from coed

Name

Adeilad is the Welsh word for buildings. For English speakers it'd be pronounced similar to "ah-dey-lad".

Package Sidebar

Install

npm i @eeue56/adeilad

Weekly Downloads

5

Version

0.0.2

License

BSD-3-Clause

Unpacked Size

103 kB

Total Files

18

Last publish

Collaborators

  • eeue56