-
Notifications
You must be signed in to change notification settings - Fork 3
/
client.ts
291 lines (249 loc) · 6.13 KB
/
client.ts
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
/*
* Copyright (c) 2020, J2 Innovations. All Rights Reserved
*/
/* eslint prefer-const: "off" */
import { useState, useEffect, createContext, useContext, useRef } from 'react'
import { Client } from 'haystack-nclient'
import { HGrid, HRef, HList, HFilterBuilder } from 'haystack-core'
interface Callback {
(): void
}
/**
* The grid result.
*/
export interface GridResult {
/**
* The grid result.
*/
grid: HGrid
/**
* True if the grid's data is loading.
*/
isLoading: boolean
/**
* The number of times a grid has been loaded.
*/
loads: number
/**
* Truthy if the grid's data didn't load properly and threw an error.
*/
error?: Error
}
/**
* A grid result that can be refreshed.
*/
export interface GridRefreshResult extends GridResult {
/**
* Called to refresh any backing data queries.
*/
refresh: () => void
}
interface GridData {
grid: HGrid
isLoading: boolean
loads: number
error?: Error
}
/**
* A hook that asynchronously resolves to a grid.
*
* @param options.getGrid An asynchronous method that resolves to a grid.
* @param options.dependencies The dependencies that cause the grid to be refetched.
* @returns A result that wraps the data.
*/
export function useGrid({
getGrid,
dependencies,
}: {
getGrid: () => Promise<HGrid>
dependencies: ReadonlyArray<unknown>
}): GridResult {
const data = useRef<GridData>()
const gridData =
data.current ??
(data.current = { grid: new HGrid(), isLoading: true, loads: 0 })
let [updates, setUpdates] = useState(0)
const forceUpdate = (): void => setUpdates(++updates)
useEffect(
(): Callback => {
let cancel = false
async function doGetGrid(): Promise<void> {
try {
const wasLoading = gridData.isLoading
gridData.isLoading = true
// If a grid wasn't loading before it is now so force an
// update in the UI.
if (!wasLoading) {
forceUpdate()
}
const grid = await getGrid()
if (!cancel) {
gridData.grid = grid
}
} catch (err) {
if (!cancel) {
gridData.error = err as Error
}
} finally {
if (!cancel) {
++gridData.loads
gridData.isLoading = false
}
// Force an update after everything has completed.
forceUpdate()
}
}
doGetGrid()
return (): void => {
cancel = true
gridData.isLoading = false
gridData.error = undefined
}
},
dependencies // Effect re-runs if any of these parameters change.
)
return gridData
}
/**
* The client context to be used.
*/
export const ClientContext = createContext<Client>(
new Client({
base: new URL(globalThis?.location?.href || 'http://localhost'),
})
)
ClientContext.displayName = 'Client'
/**
* @returns The client to use for network communication.
*/
export function useClient(): Client {
return useContext(ClientContext)
}
/**
* A hook that restricts network communcations only to ops.
*/
export const OnlyOpsContext = createContext<boolean>(true)
OnlyOpsContext.displayName = 'OnlyOps'
/**
* @returns true if only ops should be used for network communication.
*/
export function useOnlyOps(): boolean {
return useContext(OnlyOpsContext)
}
/**
* A hook that resolves a some ids into a grid.
*
* @param ids The ids to read from the server.
* @returns A result that wraps the grid.
*/
export function useReadByIds(
ids: string[] | HRef[] | HList<HRef>
): GridRefreshResult {
const client = useClient()
const ops = useOnlyOps()
const [refreshes, setRefreshes] = useState(0)
if (ops) {
let builder: HFilterBuilder | undefined
for (const id of ids) {
if (!builder) {
builder = new HFilterBuilder()
} else {
builder.or()
}
builder.equals('id', HRef.make(id))
}
return useReadByFilter(builder?.build() ?? '')
} else {
const result = useGrid({
getGrid: async (): Promise<HGrid> => {
return ids.length ? client.record.readByIds(ids) : new HGrid()
},
dependencies: [JSON.stringify(ids), client, ops, refreshes],
})
return {
...result,
refresh: () => setRefreshes(refreshes + 1),
}
}
}
/**
* A hook that resolves an id into a grid.
*
* @param id The id to read to read from the server.
* @returns A result that wraps the grid.
*/
export function useReadById(id: string | HRef): GridRefreshResult {
const client = useClient()
const ops = useOnlyOps()
const [refreshes, setRefreshes] = useState(0)
const dependencies = [JSON.stringify(id), client, ops, refreshes]
let result: GridResult
if (ops) {
const filter = new HFilterBuilder().equals('id', HRef.make(id)).build()
result = useGrid({
getGrid: async (): Promise<HGrid> =>
String(id) ? client.ops.read(filter) : new HGrid(),
dependencies,
})
} else {
result = useGrid({
getGrid: async (): Promise<HGrid> =>
String(id)
? (await client.record.readById(id)).toGrid()
: new HGrid(),
dependencies,
})
}
return {
...result,
refresh: () => setRefreshes(refreshes + 1),
}
}
/**
* A hook that resolves a haystack filter into a grid.
*
* @param filter The haystack filter to query from the server.
* @returns A result that wraps the grid.
*/
export function useReadByFilter(filter: string): GridRefreshResult {
const client = useClient()
const ops = useOnlyOps()
const [refreshes, setRefreshes] = useState(0)
const dependencies = [filter, client, ops, refreshes]
let result: GridResult
if (ops) {
result = useGrid({
getGrid: async (): Promise<HGrid> =>
filter ? client.ops.read(filter) : new HGrid(),
dependencies,
})
} else {
result = useGrid({
getGrid: async (): Promise<HGrid> =>
filter ? client.record.readByFilter(filter) : new HGrid(),
dependencies,
})
}
return {
...result,
refresh: () => setRefreshes(refreshes + 1),
}
}
/**
* A hook that responses an expression into a grid.
*
* @param expr The expression to evalulate.
* @returns The result that wraps the grid.
*/
export function useEval(expr: string): GridRefreshResult {
const client = useClient()
const [refreshes, setRefreshes] = useState(0)
const result = useGrid({
getGrid: async (): Promise<HGrid> => client.ext.eval(expr),
dependencies: [expr, client, refreshes],
})
return {
...result,
refresh: () => setRefreshes(refreshes + 1),
}
}