use lossless-json for api calls

This commit is contained in:
Braydon 2024-09-18 21:44:14 -04:00
parent 7bb85dc2ca
commit c8eae3330a
4 changed files with 21 additions and 3 deletions

BIN
bun.lockb

Binary file not shown.

@ -16,14 +16,20 @@
"dependencies": {
"@heroicons/react": "^2.1.5",
"@hookform/resolvers": "^3.9.0",
"@radix-ui/react-dialog": "^1.1.1",
"@radix-ui/react-icons": "^1.3.0",
"@radix-ui/react-popover": "^1.1.1",
"@radix-ui/react-separator": "^1.1.0",
"@radix-ui/react-slot": "^1.1.0",
"@radix-ui/react-tooltip": "^1.1.2",
"@tabler/icons-react": "^3.17.0",
"@types/canvas-confetti": "^1.6.4",
"canvas-confetti": "^1.9.3",
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.1",
"cmdk": "1.0.0",
"framer-motion": "^11.5.4",
"lossless-json": "^4.0.2",
"lucide-react": "^0.441.0",
"next": "14.2.8",
"next-client-cookies": "^1.1.1",

@ -1,5 +1,6 @@
import { Session } from "@/app/types/user/session";
import { ApiError } from "@/app/types/api-error";
import { parseJson } from "@/lib/json";
type ApiRequestProps = {
/**
@ -59,9 +60,9 @@ export const apiRequest = async <T>({
},
}
);
const data: T = await response.json();
const json: any = parseJson(await response.text()); // Parse the Json response from the API
if (response.status !== 200) {
return { data: undefined, error: data as ApiError };
return { data: undefined, error: json as ApiError };
}
return { data: data as T, error: undefined };
return { data: json as T, error: undefined };
};

11
src/lib/json.ts Normal file

@ -0,0 +1,11 @@
import { isInteger, parse } from "lossless-json";
/**
* Parse the given input as JSON.
*
* @param input the input to parse
*/
export const parseJson = (input: string): any =>
parse(input, null, (value: string): string | number =>
isInteger(value) ? String(value) : parseInt(value)
);