MCPcopy Index your code
hub / github.com/TryCatchLearn/Overflow / fetchClient

Function fetchClient

webapp/src/lib/fetchClient.ts:6–69  ·  view source on GitHub ↗
(
    url: string,
    method: 'GET' | 'POST' | 'PUT' | 'DELETE',
    options: Omit<RequestInit, 'body'> & { body?: unknown } = {}
)

Source from the content-addressed store, hash-verified

4import {FetchResponse} from "@/lib/types";
5
6export 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 }

Callers 13

searchQuestionsFunction · 0.90
updateQuestionFunction · 0.90
deleteQuestionFunction · 0.90
editAnswerFunction · 0.90
deleteAnswerFunction · 0.90
acceptAnswerFunction · 0.90
addVoteFunction · 0.90
testAuthFunction · 0.90
getTagsFunction · 0.90
getTrendingTagsFunction · 0.90
getUserProfilesFunction · 0.90
getProfileByIdFunction · 0.90

Calls 1

getFallbackMessageFunction · 0.85

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…