-
-
Notifications
You must be signed in to change notification settings - Fork 69
/
resource.js
82 lines (74 loc) · 1.77 KB
/
resource.js
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
const clientFetchMap = new Map()
const clientResourceMap = new Map()
export function waitResource(
path,
id,
promise,
resourceMap = clientResourceMap,
) {
const resourceId = `${path}:${id}`
const loaderStatus = resourceMap.get(resourceId)
if (loaderStatus) {
if (loaderStatus.error) {
throw loaderStatus.error
}
if (loaderStatus.suspended) {
throw loaderStatus.promise
}
resourceMap.delete(resourceId)
return loaderStatus.result
}
const loader = {
suspended: true,
error: null,
result: null,
promise: null,
}
loader.promise = promise()
.then((result) => {
loader.result = result
})
.catch((loaderError) => {
loader.error = loaderError
})
.finally(() => {
loader.suspended = false
})
resourceMap.set(resourceId, loader)
return waitResource(path, id)
}
export function waitFetch(path, options = {}, fetchMap = clientFetchMap) {
const loaderStatus = fetchMap.get(path)
if (loaderStatus) {
if (loaderStatus.error || loaderStatus.data?.statusCode === 500) {
if (loaderStatus.data?.statusCode === 500) {
throw new Error(loaderStatus.data.message)
}
throw loaderStatus.error
}
if (loaderStatus.suspended) {
throw loaderStatus.promise
}
fetchMap.delete(path)
return loaderStatus.data
}
const loader = {
suspended: true,
error: null,
data: null,
promise: null,
}
loader.promise = fetch(path, options)
.then((response) => response.json())
.then((loaderData) => {
loader.data = loaderData
})
.catch((loaderError) => {
loader.error = loaderError
})
.finally(() => {
loader.suspended = false
})
fetchMap.set(path, loader)
return waitFetch(path, options, fetchMap)
}