Spaces:
Runtime error
Runtime error
Download apps/webapp/app/utils/json.ts from BTankut/Context-Store-LLM: direct link, hf CLI and curl.
- Browser
- Download file 1.29 kB
-
https://huggingface.co/spaces/BTankut/Context-Store-LLM/resolve/main/apps/webapp/app/utils/json.ts
- Command line
-
hf download hf://spaces/BTankut/Context-Store-LLM/apps/webapp/app/utils/json.ts
-
curl -L -o json.ts https://huggingface.co/spaces/BTankut/Context-Store-LLM/resolve/main/apps/webapp/app/utils/json.ts
1.29 kB
| import { type z } from "zod"; | |
| export function safeJsonParse(json?: string): unknown { | |
| if (!json) { | |
| return; | |
| } | |
| try { | |
| return JSON.parse(json); | |
| } catch (e) { | |
| return null; | |
| } | |
| } | |
| export function safeJsonZodParse<T>( | |
| schema: z.Schema<T>, | |
| json: string, | |
| ): z.SafeParseReturnType<unknown, T> | undefined { | |
| const parsed = safeJsonParse(json); | |
| if (parsed === null) { | |
| return; | |
| } | |
| return schema.safeParse(parsed); | |
| } | |
| export async function safeJsonFromResponse(response: Response) { | |
| const json = await response.text(); | |
| return safeJsonParse(json); | |
| } | |
| export async function safeBodyFromResponse<T>( | |
| response: Response, | |
| schema: z.Schema<T>, | |
| ): Promise<T | undefined> { | |
| const json = await response.text(); | |
| const unknownJson = safeJsonParse(json); | |
| if (!unknownJson) { | |
| return; | |
| } | |
| const parsedJson = schema.safeParse(unknownJson); | |
| if (parsedJson.success) { | |
| return parsedJson.data; | |
| } | |
| } | |
| export async function safeParseBodyFromResponse<T>( | |
| response: Response, | |
| schema: z.Schema<T>, | |
| ): Promise<z.SafeParseReturnType<unknown, T> | undefined> { | |
| try { | |
| const unknownJson = await response.json(); | |
| if (!unknownJson) { | |
| return; | |
| } | |
| const parsedJson = schema.safeParse(unknownJson); | |
| return parsedJson; | |
| } catch (error) {} | |
| } | |