|
| 1 | +"use client"; |
| 2 | + |
| 3 | +import type { CollectionSlug, DataFromCollectionSlug } from "payload"; |
| 4 | +import { createContext, type ReactNode, useState } from "react"; |
| 5 | +import type { PayloadSession } from "./getPayloadSession"; |
| 6 | + |
| 7 | +export interface SessionContext<TSlug extends CollectionSlug> { |
| 8 | + /** |
| 9 | + * The session |
| 10 | + */ |
| 11 | + session: PayloadSession<TSlug> | null; |
| 12 | + /** |
| 13 | + * Function to refresh the session |
| 14 | + */ |
| 15 | + refresh: () => Promise<PayloadSession<TSlug> | null>; |
| 16 | +} |
| 17 | + |
| 18 | +export const Context = createContext<SessionContext<never>>({ |
| 19 | + session: null, |
| 20 | + refresh: () => new Promise(resolve => resolve(null)), |
| 21 | +}); |
| 22 | + |
| 23 | +interface Props<TSlug extends CollectionSlug> { |
| 24 | + /** |
| 25 | + * The slug of the collection that contains the users |
| 26 | + * |
| 27 | + * @default "users" |
| 28 | + */ |
| 29 | + userCollectionSlug?: TSlug; |
| 30 | + /** |
| 31 | + * The session (if available) |
| 32 | + */ |
| 33 | + session: PayloadSession<TSlug> | null; |
| 34 | + /** |
| 35 | + * The children to render |
| 36 | + */ |
| 37 | + children: ReactNode; |
| 38 | +} |
| 39 | + |
| 40 | +/** |
| 41 | + * PayloadSessionProvider (client-side) that provides the session to the context provider |
| 42 | + */ |
| 43 | +export const PayloadSessionProvider = <TSlug extends CollectionSlug = "users">({ |
| 44 | + userCollectionSlug = "users" as TSlug, |
| 45 | + session, |
| 46 | + children, |
| 47 | +}: Props<TSlug>) => { |
| 48 | + const [localSession, setLocalSession] = useState<PayloadSession<TSlug> | null>(session); |
| 49 | + |
| 50 | + /** |
| 51 | + * Function to refresh the session |
| 52 | + */ |
| 53 | + const refresh = async () => { |
| 54 | + // Refresh the session on the server |
| 55 | + const response = await fetch(`/api/${userCollectionSlug}/refresh-token`, { |
| 56 | + method: "POST", |
| 57 | + }); |
| 58 | + const result: { user: DataFromCollectionSlug<TSlug>; exp: number } = await response.json(); |
| 59 | + |
| 60 | + // If the response is not ok or the user is not present, return null |
| 61 | + if (!response.ok || !result.user) { |
| 62 | + return null; |
| 63 | + } |
| 64 | + |
| 65 | + // Update the local session |
| 66 | + const localSession = { |
| 67 | + user: result.user, |
| 68 | + expires: new Date(result.exp * 1000).toISOString(), |
| 69 | + }; |
| 70 | + setLocalSession(localSession); |
| 71 | + |
| 72 | + // Return the session |
| 73 | + return localSession; |
| 74 | + }; |
| 75 | + |
| 76 | + return ( |
| 77 | + <Context |
| 78 | + value={{ |
| 79 | + session: localSession, |
| 80 | + refresh, |
| 81 | + }} |
| 82 | + > |
| 83 | + {children} |
| 84 | + </Context> |
| 85 | + ); |
| 86 | +}; |
0 commit comments