|
1 | 1 | import { cookies } from "next/headers"; |
2 | | -import { CollectionSlug, DataFromCollectionSlug } from "payload"; |
| 2 | +import { CollectionSlug } from "payload"; |
| 3 | +import { User } from "./types"; |
3 | 4 |
|
4 | | -type Options<TSlug extends CollectionSlug> = { |
| 5 | +type Options = { |
| 6 | + /** |
| 7 | + * The URL of the server |
| 8 | + * |
| 9 | + * @default process.env.NEXT_PUBLIC_SERVER_URL |
| 10 | + */ |
| 11 | + serverUrl?: string; |
5 | 12 | /** |
6 | 13 | * The slug of the collection that contains the users |
7 | 14 | * |
8 | 15 | * @default "users" |
9 | 16 | */ |
10 | | - userCollectionSlug?: TSlug; |
| 17 | + userCollectionSlug?: CollectionSlug; |
11 | 18 | }; |
12 | 19 |
|
13 | | -export const getPayloadUser = async <TSlug extends CollectionSlug = "users">({ |
14 | | - userCollectionSlug = "users" as TSlug, |
15 | | -}: Options<TSlug> = {}) => { |
| 20 | +/** |
| 21 | + * Get the user payload from the server (only works on the server side) |
| 22 | + */ |
| 23 | +export const getPayloadUser = async <T extends object = User>({ |
| 24 | + serverUrl = process.env.NEXT_PUBLIC_SERVER_URL, |
| 25 | + userCollectionSlug = "users", |
| 26 | +}: Options = {}) => { |
| 27 | + if (serverUrl === undefined) { |
| 28 | + throw new Error( |
| 29 | + "getPayloadUser requires a server URL to be provided, either as an option or in the 'NEXT_PUBLIC_SERVER_URL' environment variable", |
| 30 | + ); |
| 31 | + } |
| 32 | + |
16 | 33 | const cookieStore = cookies(); |
17 | 34 |
|
18 | | - const meUserReq = await fetch( |
19 | | - `${process.env.NEXT_PUBLIC_SERVER_URL}/api/${userCollectionSlug}/me`, |
20 | | - { |
21 | | - headers: { |
22 | | - Cookie: cookieStore.toString(), |
23 | | - }, |
| 35 | + const meUserReq = await fetch(`${serverUrl}/api/${userCollectionSlug}/me`, { |
| 36 | + headers: { |
| 37 | + Cookie: cookieStore.toString(), |
24 | 38 | }, |
25 | | - ); |
| 39 | + }); |
26 | 40 |
|
27 | | - const { user }: { user: DataFromCollectionSlug<TSlug> } = await meUserReq.json(); |
| 41 | + const { user }: { user: T } = await meUserReq.json(); |
28 | 42 |
|
29 | 43 | if (!meUserReq.ok || !user) return; |
30 | 44 |
|
|
0 commit comments