Created
August 19, 2024 13:41
-
-
Save VldMrgnn/abdb07d18f78d7f6afc6e6ceec976692 to your computer and use it in GitHub Desktop.
parse Recursive unknown to latest Result<T>
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 type { Result } from 'starfx'; | |
export function isJSONString(str) { | |
try { | |
const obj = JSON.parse(str); | |
return typeof obj === 'object' && obj !== null; | |
} catch (error) { | |
return false; | |
} | |
} | |
export function isOk<T>( | |
result: Result<T>, | |
): result is { readonly ok: true; value: T } { | |
return result.ok === true; | |
} | |
export function isErr<T>( | |
result: Result<T>, | |
): result is { readonly ok: false; error: Error } { | |
return result.ok === false; | |
} | |
export function isResult(p: unknown): boolean { | |
return (p as Result<unknown>).ok !== undefined; | |
} | |
export function parseRecursive<T>(result: Result<T> | unknown): T | Error { | |
if (result === undefined || result === null) { | |
return result as T; | |
} | |
if (typeof result === 'string') { | |
if (isJSONString(result)) { | |
const parsedResult = JSON.parse(result); | |
return parseRecursive(parsedResult); | |
} | |
return result as T; | |
} | |
if (isResult(result)) { | |
const _result = result as Result<T>; | |
if (isOk(_result)) { | |
const { value } = _result; | |
return parseRecursive(value); | |
} else { | |
const { error } = _result; | |
return error; | |
} | |
} | |
if (result instanceof Error) { | |
return result; | |
} | |
return result as T; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment