-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmod.ts
More file actions
298 lines (284 loc) · 8.42 KB
/
mod.ts
File metadata and controls
298 lines (284 loc) · 8.42 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
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
292
293
294
295
296
297
298
/**
* Type-safe HTTP API Client.
*
* Builds a strongly-typed client from server route definitions. For each
* declared route it provides:
* - fetch(input?, options?): Promise<Output>
* - signal(): a reactive RequestState wrapper powered by @preact/signals
*
* Features:
* - End-to-end input/output typing from your route defs
* - Abortable requests with `.reset()` and deduping via a shared AbortController
* - Helpful errors: `ErrorWithData` (JSON error payload) and `ErrorWithBody` (invalid JSON)
*
* @example Basic usage
* ```ts
* import { makeClient } from '@01edu/api-client'
* import type { RoutesDefinitions } from '/api/routes.ts'
* // Important, only import types from your backend
*
* const api = makeClient<RoutesDefinitions>('/api')
* const res = await api['GET/hello'].fetch({ name: 'Ada' })
* ```
*
* @example Reactive usage
* ```ts
* const hello = api['GET/hello'].signal()
* hello.fetch({ name: 'Ada' })
* hello.$.subscribe(v => console.log(v.pending, v.data, v.error))
* ```
*
* @module
*/
import { Signal } from '@preact/signals'
import type { Asserted } from '@01edu/types/validator'
import type { GenericRoutes, Handler, HttpMethod } from '@01edu/types/router'
/**
* Error thrown when the server returns a JSON error payload.
* The parsed error metadata is available on `data`.
*
* @example
* ```ts
* try {
* await api['POST/login'].fetch({ user, pass });
* } catch (e) {
* if (e instanceof ErrorWithData) {
* console.error(e.message, e.data);
* }
* }
* ```
*/
export class ErrorWithData extends Error {
public data: Record<string, unknown>
constructor(message: string, data: Record<string, unknown>) {
super(message)
this.name = 'ErrorWithData'
this.data = data
}
}
/**
* Error thrown when the response body cannot be parsed as JSON.
* The raw body is available on `body`, and extra context on `data`.
*
* @example
* ```ts
* try {
* await api['GET/debug'].fetch();
* } catch (e) {
* if (e instanceof ErrorWithBody) {
* console.error('Invalid JSON:', e.body, e.data);
* }
* }
* ```
*/
export class ErrorWithBody extends ErrorWithData {
public body: string
constructor(body: string, data: Record<string, unknown>) {
super('Failed to parse body', data)
this.name = 'ErrorWithBody'
this.body = body
}
}
// I made the other field always explicitly undefined and optional
// this way we do not have to check all the time that they exists
type RequestState<T> =
| {
data: T
pending?: undefined
promise?: undefined
controller?: undefined
error?: undefined
at: number
}
| {
data?: T | undefined
pending: number
promise?: Promise<T>
controller?: AbortController
error?: undefined
at?: number
}
| {
data?: T | undefined
pending?: undefined
promise?: undefined
controller?: undefined
error: ErrorWithBody | ErrorWithData | Error
at: number
}
type ReplacerType = (key: string, value: unknown) => unknown
type Options = {
headers?: HeadersInit
signal?: AbortSignal
replacer?: ReplacerType
}
const withoutBody = new Set([
204, // NoContent
205, // ResetContent
304, // NotModified
])
type HandlerIO<T, K extends keyof T> = T[K] extends // deno-lint-ignore no-explicit-any
Handler<any, infer TInput, infer TOutput>
? [Asserted<TInput>, Asserted<TOutput>]
: never
/**
* Creates a typed API client from a `GenericRoutes` declaration.
*
* Each route key maps to:
* - `fetch(input?, options?)`: Promise<Output>
* - `signal()`: reactive RequestState with `$.value`, `fetch`, `reset`, and getters
*
* @param baseUrl - Optional prefix applied to every route path (e.g. `/api`).
* @returns A proxy object keyed by route pattern, exposing typed `fetch` and `signal` helpers.
*
* @example
* ```ts
* import { makeClient } from '@01edu/api-client'
* import type { RouteDefinitions } from '/api/routes.ts'
*
* const api = makeClient<RouteDefinitions>('/api')
*
* // One-shot call
* const result = await api['GET/hello'].fetch({ name: 'Ada' })
*
* // Reactive usage
* const hello = api['GET/hello'].signal()
* hello.fetch({ name: 'Ada' })
* hello.$.subscribe(v => console.log(v.pending, v.data, v.error))
* ```
*/
export const makeClient = <T extends GenericRoutes>(baseUrl = ''): {
[K in keyof T]: {
fetch: (
input?: HandlerIO<T, K>[0] | undefined,
options?: Options | undefined,
) => Promise<HandlerIO<T, K>[1]>
signal: (
options?: { replacer?: ReplacerType },
) => RequestState<HandlerIO<T, K>[1]> & {
$: Signal<RequestState<HandlerIO<T, K>[1]>>
reset: () => void
fetch: (
input?: HandlerIO<T, K>[0] | undefined,
headers?: HeadersInit | undefined,
) => Promise<void>
at: number
}
}
} => {
function makeClientCall<K extends keyof T>(urlKey: K) {
type IO = HandlerIO<T, K>
type Input = IO[0]
type Output = IO[1]
const key = urlKey as string
const slashIndex = key.indexOf('/')
const method = key.slice(0, slashIndex) as HttpMethod
const path = key.slice(slashIndex)
const defaultHeaders = { 'Content-Type': 'application/json' }
async function fetcher(input?: Input, options?: Options | undefined) {
const { replacer, ...fetchOptions } = options || {}
let url = `${baseUrl}${path}`
let headers = options?.headers
if (!headers) {
headers = defaultHeaders
} else {
headers instanceof Headers || (headers = new Headers(headers))
for (const [key, value] of Object.entries(defaultHeaders)) {
headers.set(key, value)
}
}
let bodyInput: string | undefined = undefined
if (input) {
method === 'GET'
? (url += `?${new URLSearchParams(input as Record<string, string>)}`)
: (bodyInput = JSON.stringify(input))
}
const response = await fetch(
url,
{ ...fetchOptions, method, headers, body: bodyInput },
)
if (withoutBody.has(response.status)) return null as unknown as Output
const body = await response.text()
let payload
const contentType = response.headers.get('content-type')
try {
payload = contentType?.includes('application/json')
? JSON.parse(body, replacer)
: body
if (response.ok) return payload as Output
} catch {
throw new ErrorWithBody(body, { response })
}
const { message, ...data } = payload
throw new ErrorWithData(message, data)
}
const signal = (options: { replacer?: ReplacerType } = {}) => {
const $ = new Signal<RequestState<Output>>({ pending: 0 })
return {
$,
reset: () => {
$.peek().controller?.abort()
$.value = { pending: 0 }
},
fetch: async (input, headers) => {
const prev = $.peek()
try {
const controller = new AbortController()
prev.controller?.abort()
const { replacer } = options
const { signal } = controller
const promise = fetcher(input, {
replacer,
signal,
headers,
})
$.value = {
pending: Date.now(),
promise,
controller,
data: prev.data,
}
$.value = {
data: await promise,
at: Date.now(),
}
} catch (err) {
$.value = (err instanceof DOMException && err.name === 'AbortError')
? { pending: 0, data: prev.data }
: {
error: err as (ErrorWithBody | ErrorWithData | Error),
data: prev.data,
at: Date.now(),
}
}
},
get data() {
return $.value.data
},
get error() {
return $.value.error
},
get pending() {
return $.value.pending
},
get at() {
return $.value.at ?? 0
},
} as RequestState<Output> & {
$: Signal<RequestState<Output>>
reset: () => void
fetch: (
input?: Input,
headers?: HeadersInit | undefined,
) => Promise<void>
at: number
}
}
return { fetch: fetcher, signal }
}
const client = {} as { [K in keyof T]: ReturnType<typeof makeClientCall<K>> }
const lazy = (k: keyof T) => client[k] || (client[k] = makeClientCall(k))
return new Proxy(client, {
get: (_, key: string) => lazy(key as keyof T),
})
}