Skip to content

Commit c4c3f6c

Browse files
committed
insert session token when available
1 parent f52c5ad commit c4c3f6c

File tree

1 file changed

+22
-4
lines changed

1 file changed

+22
-4
lines changed

src/utils/helpers.ts

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,10 @@ import * as chains from "viem/chains";
33

44
import type { ApiErr, ApiOk } from "./types";
55

6+
export const ENDPOINT = "http://127.0.0.1:9545";
7+
68
export const ALL_CHAINS: readonly Chain[] = Object.freeze(Object.values(chains) as Chain[]);
9+
710
export const getChainById = (id: number) => ALL_CHAINS.find((c) => c.id === id);
811

912
const parseChainId = (input: unknown): number | undefined => {
@@ -33,19 +36,34 @@ export const applyChainId = (
3336

3437
export const toBig = (h?: `0x${string}`) => (h ? hexToBigInt(h) : undefined);
3538

36-
export const ENDPOINT = "http://127.0.0.1:9545";
37-
3839
export const api = async <T = unknown>(
3940
path: string,
4041
method: "GET" | "POST" = "GET",
4142
body?: unknown,
4243
): Promise<T> => {
44+
const headers: Record<string, string> = {
45+
"Content-Type": "application/json",
46+
};
47+
48+
const token =
49+
typeof window !== "undefined" && (window as any).__SESSION_TOKEN__
50+
? String((window as any).__SESSION_TOKEN__)
51+
: null;
52+
53+
if (token) {
54+
headers["X-Session-Token"] = token;
55+
}
56+
4357
const res = await fetch(`${ENDPOINT}${path}`, {
4458
method,
45-
headers: { "Content-Type": "application/json" },
59+
headers,
4660
body: body === undefined ? undefined : JSON.stringify(body),
4761
});
48-
if (!res.ok) throw new Error(`API request failed: ${res.status} ${res.statusText}`);
62+
63+
if (!res.ok) {
64+
throw new Error(`API request failed: ${res.status} ${res.statusText}`);
65+
}
66+
4967
try {
5068
return (await res.json()) as T;
5169
} catch {

0 commit comments

Comments
 (0)