-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathapi-client.ts
More file actions
86 lines (71 loc) · 2.3 KB
/
api-client.ts
File metadata and controls
86 lines (71 loc) · 2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import { env } from "@follow/shared/env.desktop"
import { whoami } from "@follow/store/user/getters"
import { userActions } from "@follow/store/user/store"
import { createDesktopAPIHeaders } from "@follow/utils/headers"
import { FollowClient } from "@follow-app/client-sdk"
import PKG from "@pkg"
import { NetworkStatus, setApiStatus } from "~/atoms/network"
import { setLoginModalShow } from "~/atoms/user"
import { getClientId, getSessionId } from "./client-session"
export const followClient = new FollowClient({
credentials: "include",
timeout: 30000,
baseURL: env.VITE_API_URL,
fetch: async (input, options = {}) =>
fetch(input.toString(), {
...options,
cache: "no-store",
}),
})
export const followApi = followClient.api
followClient.addRequestInterceptor(async (ctx) => {
const { options } = ctx
const header = options.headers || {}
header["X-Client-Id"] = getClientId()
header["X-Session-Id"] = getSessionId()
const apiHeader = createDesktopAPIHeaders({ version: PKG.version })
options.headers = {
...header,
...apiHeader,
}
return ctx
})
followClient.addResponseInterceptor(({ response }) => {
setApiStatus(NetworkStatus.ONLINE)
return response
})
followClient.addErrorInterceptor(async ({ error, response }) => {
// If api is down
if ((!response || response.status === 0) && navigator.onLine) {
setApiStatus(NetworkStatus.OFFLINE)
} else {
setApiStatus(NetworkStatus.ONLINE)
}
if (!response) {
return error
}
return error
})
followClient.addResponseInterceptor(async ({ response }) => {
if (response.status === 401) {
const shouldPromptForLogin = response.url.includes("/better-auth/get-session") || !whoami()
if (!shouldPromptForLogin) {
return response
}
// Or we can present LoginModal here.
// router.navigate("/login")
// If any response status is 401, we can set auth fail. Maybe some bug, but if navigate to login page, had same issues
setLoginModalShow(true)
userActions.removeCurrentUser()
}
try {
const isJSON = response.headers.get("content-type")?.includes("application/json")
if (!isJSON) return response
const _json = await response.clone().json()
const isError = response.status >= 400
if (!isError) return response
} catch {
// ignore
}
return response
})