Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/eeue56/adeilad
Ensure JSON has the correct structure at runtime
https://github.com/eeue56/adeilad
Last synced: 3 months ago
JSON representation
Ensure JSON has the correct structure at runtime
- Host: GitHub
- URL: https://github.com/eeue56/adeilad
- Owner: eeue56
- License: bsd-3-clause
- Created: 2021-05-31T16:22:24.000Z (over 3 years ago)
- Default Branch: main
- Last Pushed: 2022-07-22T12:21:06.000Z (over 2 years ago)
- Last Synced: 2024-09-30T05:22:46.325Z (3 months ago)
- Language: TypeScript
- Size: 69.3 KB
- Stars: 4
- Watchers: 3
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# adeilad
Ensure JSON has the correct structure at runtime, inspired by Elm's [decoders](https://package.elm-lang.org/packages/elm/json/latest/Json-Decode) and the [pipeline decoder](https://package.elm-lang.org/packages/NoRedInk/elm-json-decode-pipeline/latest) 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](https://github.com/eeue56/hiraeth) collection.
## Installation
```
npm install --save @eeue56/adeilad
```## Example usage
Imagine you have some API that gives you JSON, for example:
```typescript
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](./docs/src/adeilad.md)
You may also want to see the Result type from [coed](https://github.com/eeue56/coed)
## Name
Adeilad is the Welsh word for buildings. For English speakers it'd be pronounced similar to "ah-dey-lad".