-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: media won't load when token needs refreshing (#15)
- Loading branch information
Showing
3 changed files
with
17 additions
and
9 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,17 +1,27 @@ | ||
import { atom } from "jotai"; | ||
import { Api } from "../__generated__/media"; | ||
import { Authed, AuthState } from "../auth"; | ||
|
||
export const apiAtom = atom<Api<unknown> | null>(null); | ||
export function getApi(token: string) { | ||
export function getApi(authState: AuthState) { | ||
return new Api({ | ||
baseUrl: "https://media.djoamersfoort.nl/api", | ||
baseApiParams: { | ||
credentials: "same-origin", | ||
headers: { | ||
authorization: `Bearer ${token}`, | ||
}, | ||
redirect: "follow", | ||
referrerPolicy: "no-referrer", | ||
}, | ||
async customFetch(...fetchParams: Parameters<typeof fetch>) { | ||
if (authState.authenticated !== Authed.AUTHENTICATED) | ||
throw new Error("Unauthenticated"); | ||
if (!fetchParams[1]) fetchParams[1] = {}; | ||
if (!fetchParams[1].headers) fetchParams[1].headers = {}; | ||
|
||
Object.assign(fetchParams[1].headers, { | ||
authorization: `Bearer ${await authState.token}`, | ||
}); | ||
|
||
return fetch(...fetchParams); | ||
}, | ||
}); | ||
} |