-
Notifications
You must be signed in to change notification settings - Fork 35
/
index.ts
94 lines (82 loc) · 2.62 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
export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'HEAD' | 'PATCH' | 'OPTIONS'
type BasicHeaders = { [key: string]: string }
export interface AspidaRequest<T = any> {
query?: any
headers?: any
body?: T
}
export interface AspidaResponse<T, U> {
status: number
headers: U
body: any
data: T
}
export interface AspidaClient {
fetch: <T, U = BasicHeaders>(
url: string,
method: HttpMethod,
request?: AspidaRequest
) => {
send(): Promise<AspidaResponse<null, U>>
json(): Promise<AspidaResponse<T, U>>
text(): Promise<AspidaResponse<string, U>>
arrayBuffer(): Promise<AspidaResponse<ArrayBuffer, U>>
blob(): Promise<AspidaResponse<Blob, U>>
formData(): Promise<AspidaResponse<FormData, U>>
}
}
export function headersToObject<T>(headers: Headers) {
return [...headers.entries()].reduce((prev, [key, val]) => ({ ...prev, [key]: val }), {} as T)
}
function dataToFormData(data: { [key: string]: any }) {
const formData = new FormData()
Object.keys(data).forEach(key => {
formData.append(key, data[key])
})
return formData
}
export function dataToURLString(data: { [key: string]: any }) {
const params = new URLSearchParams()
Object.keys(data).forEach(key => {
params.append(key, data[key])
})
return params.toString()
}
type Option<T = any> = { query?: any; headers?: any; data?: T }
function optionToRequest(option: Option, type: 'FormData'): AspidaRequest<FormData>
function optionToRequest(option: Option, type: 'URLSearchParams'): AspidaRequest<URLSearchParams>
function optionToRequest(
option: Option<ArrayBuffer>,
type: 'ArrayBuffer'
): AspidaRequest<ArrayBuffer>
function optionToRequest(option: Option<Blob>, type: 'Blob'): AspidaRequest<Blob>
function optionToRequest(option: Option<string>, type: 'string'): AspidaRequest<string>
function optionToRequest(option: Option): AspidaRequest
function optionToRequest(
option: Option,
type?: 'FormData' | 'URLSearchParams' | 'ArrayBuffer' | 'Blob' | 'string'
): AspidaRequest {
if (!option.data) return option
let body
const headers = { ...option.headers }
switch (type) {
case 'FormData':
body = dataToFormData(option.data)
break
case 'URLSearchParams':
body = dataToURLString(option.data)
headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8'
break
case 'ArrayBuffer':
case 'string':
case 'Blob':
body = option.data
break
default:
body = JSON.stringify(option.data)
headers['Content-Type'] = 'application/json;charset=utf-8'
break
}
return { query: option.query, headers, body }
}
export { optionToRequest }