(
url: string,
method: 'GET' | 'POST' | 'PUT' | 'DELETE',
options: Omit<RequestInit, 'body'> & { body?: unknown } = {}
)
| 4 | import {FetchResponse} from "@/lib/types"; |
| 5 | |
| 6 | export async function fetchClient<T>( |
| 7 | url: string, |
| 8 | method: 'GET' | 'POST' | 'PUT' | 'DELETE', |
| 9 | options: Omit<RequestInit, 'body'> & { body?: unknown } = {} |
| 10 | ): Promise<FetchResponse<T>> { |
| 11 | const { body, ...rest } = options; |
| 12 | const apiUrl = apiConfig.baseUrl; |
| 13 | |
| 14 | if (!apiUrl) throw new Error('Missing API URL'); |
| 15 | const session = await auth(); |
| 16 | |
| 17 | const headers: HeadersInit = { |
| 18 | 'Content-Type': 'application/json', |
| 19 | ...(session?.accessToken |
| 20 | ? { Authorization: `Bearer ${session.accessToken}` } |
| 21 | : {}), |
| 22 | ...(rest.headers || {}) |
| 23 | } |
| 24 | |
| 25 | const response = await fetch(apiUrl + url, { |
| 26 | method, |
| 27 | headers, |
| 28 | ...(body ? { body: JSON.stringify(body) } : {}), |
| 29 | ...rest, |
| 30 | }); |
| 31 | |
| 32 | const contentType = response.headers.get('Content-Type'); |
| 33 | const isJson = contentType?.includes('application/json') |
| 34 | || contentType?.includes('application/problem+json'); |
| 35 | |
| 36 | const parsed = isJson ? await response.json() : await response.text(); |
| 37 | |
| 38 | if (!response.ok) { |
| 39 | console.log(response); |
| 40 | if (response.status === 404) return notFound(); |
| 41 | // if (response.status === 500) throw new Error("Server error. Please try again later."); |
| 42 | |
| 43 | let message = ''; |
| 44 | |
| 45 | if (response.status === 401) { |
| 46 | const authHeader = response.headers.get('WWW-Authenticate'); |
| 47 | if (authHeader?.includes('error_description')) { |
| 48 | const match = authHeader.match(/error_description="(.+?)"/); |
| 49 | if (match) message = match[1]; |
| 50 | } else { |
| 51 | message = "You must be logged in to do that" |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | if (!message) { |
| 56 | if (typeof parsed === 'string') { |
| 57 | message = parsed |
| 58 | } else if (parsed?.message) { |
| 59 | message = parsed?.message; |
| 60 | } else { |
| 61 | message = getFallbackMessage(response.status) |
| 62 | } |
| 63 | } |
no test coverage detected
searching dependent graphs…