(
api: string,
options: FetchInit = {}
)
| 15 | export type FetchInit = RequestInit & { user?: UserSession }; |
| 16 | |
| 17 | export async function fetchResult<T>( |
| 18 | api: string, |
| 19 | options: FetchInit = {} |
| 20 | ): Promise<T> { |
| 21 | const { user, ...fetchOptions } = options; |
| 22 | const sessionToken = await user?.getSessionToken(); |
| 23 | |
| 24 | const res = await fetch(`${API_BASE}${api}`, { |
| 25 | ...fetchOptions, |
| 26 | headers: { |
| 27 | Accept: "application/json", |
| 28 | "User-Agent": `partykit/${packageVersion}`, |
| 29 | "X-PartyKit-Version": packageVersion, |
| 30 | "X-CLOUDFLARE-ACCOUNT-ID": process.env.CLOUDFLARE_ACCOUNT_ID || "", |
| 31 | "X-CLOUDFLARE-API-TOKEN": process.env.CLOUDFLARE_API_TOKEN || "", |
| 32 | ...(typeof fetchOptions.body === "string" |
| 33 | ? { "Content-Type": "application/json" } |
| 34 | : {}), |
| 35 | ...(user && sessionToken |
| 36 | ? { |
| 37 | Authorization: `Bearer ${sessionToken}`, |
| 38 | "X-PartyKit-User-Type": user.type |
| 39 | } |
| 40 | : {}), |
| 41 | ...(fetchOptions.headers ?? {}) |
| 42 | } |
| 43 | }); |
| 44 | if (res.ok) { |
| 45 | const resJson = (await res.json()) as T; |
| 46 | return resJson; // TODO: check json success/error response |
| 47 | } else { |
| 48 | let errorText; |
| 49 | try { |
| 50 | errorText = await res.text(); |
| 51 | } catch (e) { |
| 52 | errorText = `${res.status} ${res.statusText}`; |
| 53 | } |
| 54 | throw new Error(errorText); |
| 55 | } |
| 56 | } |
no test coverage detected