Last active
July 19, 2024 16:40
-
-
Save wpcarro/6006726828251cf200d12f472d8d5cbb to your computer and use it in GitHub Desktop.
Parse. Don't validate. - https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/
This file contains 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
// HINT: Definitely use ts-result for this. | |
type Result<A, B> = { success: true, data: A } | { success: false, error: B }; | |
function Ok<A>(x: A): { success: true; data: A; } { | |
return { success: true, data: x }; | |
} | |
function Err<B>(e: B): { success: false; error: B; } { | |
return { success: false, error: e }; | |
} | |
function parseString(x: any): string { | |
if (typeof x !== "string") { | |
throw new Error(`Expected a string and got ${JSON.stringify(x)} (${typeof x})`); | |
} | |
return x; | |
} | |
type Person = { fname: string, lname: string; }; | |
function get<A>(url: string, payload: A): Promise<A> { | |
return new Promise((resolve) => setTimeout(() => resolve(payload), 1000 + Math.random() * 2500)); | |
} | |
// HINT: Maybe use Zod for this. | |
function parsePerson(x: any): Result<Person, string> { | |
if (typeof x !== "object") { | |
return Err(`Expected object got ${JSON.stringify(x)} (${typeof x})`); | |
} | |
try { | |
const supported = ["fname", "lname"]; | |
if (Object.keys(x).every((k) => supported.includes(k))) { | |
const fname = parseString(x["fname"]); | |
const lname = parseString(x["lname"]); | |
return Ok({ fname, lname }); | |
} else { | |
return Err("Unexpected keys in object"); | |
} | |
} catch (e) { | |
if (e instanceof Error) { | |
return Err(e.message); | |
} else { | |
return Err("Unsupported error"); | |
} | |
} | |
} | |
async function fetchPerson(payload: any): Promise<Result<Person, string>> { | |
const x = await get("https://potato.com", payload); | |
const parsed = parsePerson(x); | |
if (parsed.success) { | |
return Ok(parsed.data); | |
} else { | |
return Err(`Failed to parse into Person: ${parsed.error}`); | |
} | |
} | |
async function main() { | |
const payloads = [ | |
12, | |
{fname: "William", lname: "Carroll"}, | |
{fname: "William", lname: "Carroll", age: 32}, | |
]; | |
for (const payload of payloads) { | |
console.log("Fetching..."); | |
const result = await fetchPerson(payload) | |
if (result.success) { | |
console.log(`Success: ${JSON.stringify(result.data)}`); | |
} else { | |
console.log(`Failed to fetch Person: ${result.error}`); | |
} | |
} | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment