Last active
October 29, 2020 14:12
-
-
Save anttti/4016e9ee0e73a3fff77c8d7b4591483c to your computer and use it in GitHub Desktop.
Reading and parsing a JSON file using Purify
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { EitherAsync } from "purify-ts/EitherAsync"; | |
import { identity } from "purify-ts/Function"; | |
import { | |
Codec, | |
string, | |
number, | |
date, | |
boolean, | |
nullType, | |
array, | |
oneOf, | |
} from "purify-ts/Codec"; | |
import path from "path"; | |
const fs = require("fs").promises; | |
const Season = Codec.interface({ | |
href: string, | |
number: number, | |
}); | |
const ListingEpisode = Codec.interface({ | |
updated_at: date, | |
type: string, | |
token: string, | |
title: string, | |
status: string, | |
slug: string, | |
season: Season, | |
scheduled_for: nullType, | |
published_at: date, | |
number: number, | |
is_hidden: boolean, | |
image_url: oneOf([string, nullType]), | |
image_path: oneOf([string, nullType]), | |
id: string, | |
href: string, | |
guid: string, | |
enclosure_url: string, | |
duration: number, | |
description: string, | |
days_since_release: number, | |
audio_status: string, | |
analytics: nullType, | |
}); | |
const ListingEpisodes = Codec.interface({ collection: array(ListingEpisode) }); | |
interface IStringifiable { | |
toString: () => string; | |
} | |
function getFile(filename: string) { | |
return () => { | |
const filePath = path.join("./", filename); | |
return fs.readFile(filePath); | |
}; | |
} | |
function toString(obj: IStringifiable) { | |
return obj.toString(); | |
} | |
async function loadData(loader: () => Promise<Buffer>) { | |
return EitherAsync(loader) | |
.map(toString) | |
.map(JSON.parse) | |
.chain((val) => EitherAsync.liftEither(ListingEpisodes.decode(val))); | |
} | |
async function main() { | |
const data = await loadData(getFile("episodes.json.tmp")); | |
const r = data.caseOf({ | |
Left: (_) => ({ collection: [] }), | |
Right: identity, | |
}); | |
console.log(r); | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment