-
-
Notifications
You must be signed in to change notification settings - Fork 38
/
index.ts
374 lines (317 loc) · 11.7 KB
/
index.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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
import type { Elysia, InputSchema } from 'elysia'
import { EdenFetchError } from '../errors'
import { composePath } from './utils'
import type { EdenTreaty } from './types'
export type { EdenTreaty } from './types'
// @ts-ignore
const isServer = typeof FileList === 'undefined'
const isFile = (v: any) => {
// @ts-ignore
if (isServer) {
return v instanceof Blob
} else {
// @ts-ignore
return v instanceof FileList || v instanceof File
}
}
// FormData is 1 level deep
const hasFile = (obj: Record<string, any>) => {
if (!obj) return false
for (const key in obj) {
if (isFile(obj[key])) return true
else if (
Array.isArray(obj[key]) &&
(obj[key] as unknown[]).find((x) => isFile(x))
)
return true
}
return false
}
// @ts-ignore
const createNewFile = (v: File) =>
isServer
? v
: new Promise<File>((resolve) => {
// @ts-ignore
const reader = new FileReader()
reader.onload = () => {
const file = new File([reader.result!], v.name, {
lastModified: v.lastModified,
type: v.type
})
resolve(file)
}
reader.readAsArrayBuffer(v)
})
export class EdenWS<Schema extends InputSchema<any> = InputSchema> {
ws: WebSocket
url: string
constructor(url: string) {
this.ws = new WebSocket(url)
this.url = url
}
send(data: Schema['body'] | Schema['body'][]) {
if (Array.isArray(data)) {
data.forEach((datum) => this.send(datum))
return this
}
this.ws.send(
typeof data === 'object' ? JSON.stringify(data) : data.toString()
)
return this
}
on<K extends keyof WebSocketEventMap>(
type: K,
listener: (event: EdenTreaty.WSEvent<K, Schema['response']>) => void,
options?: boolean | AddEventListenerOptions
) {
return this.addEventListener(type, listener, options)
}
off<K extends keyof WebSocketEventMap>(
type: K,
listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any,
options?: boolean | EventListenerOptions
) {
this.ws.removeEventListener(type, listener, options)
return this
}
subscribe(
onMessage: (
event: EdenTreaty.WSEvent<'message', Schema['response']>
) => void,
options?: boolean | AddEventListenerOptions
) {
return this.addEventListener('message', onMessage, options)
}
addEventListener<K extends keyof WebSocketEventMap>(
type: K,
listener: (event: EdenTreaty.WSEvent<K, Schema['response']>) => void,
options?: boolean | AddEventListenerOptions
) {
this.ws.addEventListener(
type,
(ws) => {
if (type === 'message') {
let data = (ws as MessageEvent).data.toString() as any
const start = data.charCodeAt(0)
if (start === 47 || start === 123)
try {
data = JSON.parse(data)
} catch {
// Not Empty
}
else if (!Number.isNaN(+data)) data = +data
else if (data === 'true') data = true
else if (data === 'fase') data = false
listener({
...ws,
data
} as any)
} else listener(ws as any)
},
options
)
return this
}
removeEventListener<K extends keyof WebSocketEventMap>(
type: K,
listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any,
options?: boolean | EventListenerOptions
) {
this.off(type, listener, options)
return this
}
close() {
this.ws.close()
return this
}
}
const createProxy = (
domain: string,
path = '',
config: EdenTreaty.Config
): Record<string, unknown> =>
new Proxy(() => {}, {
get(target, key, value) {
return createProxy(domain, `${path}/${key.toString()}`, config)
},
// @ts-ignore
apply(
target,
_,
[initialBody, options = {}]: [
{
[x: string]: any
$fetch?: RequestInit
$headers?: HeadersInit
$query?: Record<string, string>
},
{
fetch?: RequestInit
transform?: EdenTreaty.Transform
headers?: Record<string, string>
query?: Record<string, string | number>
}
] = [{}, {}]
) {
let bodyObj: any =
initialBody !== undefined &&
(typeof initialBody !== 'object' || Array.isArray(initialBody))
? initialBody
: undefined
const { $query, $fetch, $headers, $transform, ...restBody } =
initialBody ?? {}
bodyObj ??= restBody
const i = path.lastIndexOf('/'),
method = path.slice(i + 1).toUpperCase(),
url = composePath(
domain,
i === -1 ? '/' : path.slice(0, i),
Object.assign(options.query ?? {}, $query)
)
const fetcher = config.fetcher ?? fetch
let transforms = config.transform
? Array.isArray(config.transform)
? config.transform
: [config.transform]
: undefined
const $transforms = $transform
? Array.isArray($transform)
? $transform
: [$transform]
: undefined
if ($transforms) {
if (transforms) transforms = $transforms.concat(transforms)
else transforms = $transforms as any
}
if (method === 'SUBSCRIBE')
return new EdenWS(
url.replace(
/^([^]+):\/\//,
url.startsWith('https://') ? 'wss://' : 'ws://'
)
)
const execute = async () => {
let body: any
const headers = {
...config.$fetch?.headers,
...$fetch?.headers,
...options.headers,
...$headers
} as Record<string, string>
if (method !== 'GET' && method !== 'HEAD') {
body = Object.keys(bodyObj).length
? bodyObj
: Array.isArray(bodyObj)
? bodyObj
: undefined
const isObject =
typeof body === 'object' || Array.isArray(bodyObj)
const isFormData = isObject && hasFile(body)
if (isFormData) {
const newBody = new FormData()
// FormData is 1 level deep
for (const [key, field] of Object.entries(body)) {
if (isServer) {
newBody.append(key, field as any)
} else {
// @ts-ignore
if (field instanceof File)
newBody.append(
key,
await createNewFile(field as any)
)
// @ts-ignore
else if (field instanceof FileList) {
// @ts-ignore
for (let i = 0; i < field.length; i++) {
newBody.append(
key as any,
await createNewFile(
(field as any)[i]
)
)
}
} else if (Array.isArray(field)) {
for (let i = 0; i < field.length; i++) {
const value = (field as any)[i]
newBody.append(
key as any,
value instanceof File
? createNewFile(value)
: value
)
}
} else newBody.append(key, field as string)
}
}
body = newBody
} else {
headers['content-type'] = isObject
? 'application/json'
: 'text/plain'
body = isObject ? JSON.stringify(body) : bodyObj
}
}
const response = await fetcher(url, {
method,
body,
...config.$fetch,
...options.fetch,
...$fetch,
headers
})
let data
switch (response.headers.get('Content-Type')?.split(';')[0]) {
case 'application/json':
data = await response.json()
break
default:
data = await response.text().then((data) => {
if (!Number.isNaN(+data)) return +data
if (data === 'true') return true
if (data === 'false') return false
return data
})
}
const error =
response.status >= 300 || response.status < 200
? new EdenFetchError(response.status, data)
: null
if (transforms)
for (const transform of transforms) {
let temp = transform({
data,
status: response.status,
headers: response.headers,
response,
error
})
if (temp instanceof Promise) temp = await temp
if (temp !== undefined && temp !== null) data = temp
}
return {
data,
error,
response: response,
status: response.status,
headers: response.headers
}
}
return execute()
}
}) as unknown as Record<string, unknown>
export const edenTreaty = <App extends Elysia<any, any, any, any, any, any>>(
domain: string,
config: EdenTreaty.Config = {
fetcher: fetch
}
): EdenTreaty.Create<App> =>
new Proxy(
{},
{
get(target, key) {
return createProxy(domain, key as string, config)
}
}
) as any