Skip to content

Instantly share code, notes, and snippets.

@anttti
Last active October 29, 2020 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anttti/4016e9ee0e73a3fff77c8d7b4591483c to your computer and use it in GitHub Desktop.
Save anttti/4016e9ee0e73a3fff77c8d7b4591483c to your computer and use it in GitHub Desktop.
Reading and parsing a JSON file using Purify
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