hezarfen_frontend
Clone
https://git.tahinli.com/archive/hezarfen_frontend.git
0 watching0 forksTypeScript5.5 MiBdcf123aBurak Boduroğlu2 months ago674 commits
| 1 | import { type Accessor, type ParentProps, createContext, useContext } from "solid-js"; |
| 2 | import { createResource } from "@/lib/create-resource"; |
| 3 | import { getBuilderMe, postBuilderLogout } from "@/api/builder"; |
| 4 | import { ApiError, type Builder } from "@/api/client"; |
| 5 | |
| 6 | type BuilderContextValue = { |
| 7 | /** undefined while resolving, null when this browser holds no builder session. */ |
| 8 | builder: Accessor<Builder | null | undefined>; |
| 9 | loading: Accessor<boolean>; |
| 10 | error: Accessor<unknown>; |
| 11 | refresh: () => void; |
| 12 | logout: () => Promise<void>; |
| 13 | }; |
| 14 | |
| 15 | const BuilderContext = createContext<BuilderContextValue>(); |
| 16 | |
| 17 | /** |
| 18 | * The deployment operator's session. Separate from AuthProvider on purpose: a |
| 19 | * builder cookie is 401 on every school route and a school cookie is 401 here, |
| 20 | * so the two never describe the same browser at once. |
| 21 | */ |
| 22 | export function BuilderProvider(props: ParentProps) { |
| 23 | let failure: unknown = null; |
| 24 | const [me, { refetch, mutate }] = createResource(async () => { |
| 25 | failure = null; |
| 26 | try { |
| 27 | return await getBuilderMe(); |
| 28 | } catch (err) { |
| 29 | if (!(err instanceof ApiError && err.status === 401)) failure = err; |
| 30 | return null; |
| 31 | } |
| 32 | }); |
| 33 | |
| 34 | const value: BuilderContextValue = { |
| 35 | builder: () => me(), |
| 36 | loading: () => me.loading, |
| 37 | error: () => (me() === null ? failure : null), |
| 38 | refresh: () => void refetch(), |
| 39 | logout: async () => { |
| 40 | try { |
| 41 | await postBuilderLogout(); |
| 42 | } finally { |
| 43 | mutate(null); |
| 44 | } |
| 45 | }, |
| 46 | }; |
| 47 | |
| 48 | return <BuilderContext.Provider value={value}>{props.children}</BuilderContext.Provider>; |
| 49 | } |
| 50 | |
| 51 | export function useBuilder(): BuilderContextValue { |
| 52 | const ctx = useContext(BuilderContext); |
| 53 | if (!ctx) throw new Error("useBuilder must be used within BuilderProvider"); |
| 54 | return ctx; |
| 55 | } |