-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadapter.ts
196 lines (179 loc) · 4.69 KB
/
adapter.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
import axios from 'axios';
import type {AxiosResponse, InternalAxiosRequestConfig, AxiosAdapter} from 'axios';
import type {default as Router} from './index'
import {Context} from './index'
// const Qs = await import('qs').then(module => module.default).catch(err => null)
function parseUrlencoded(data: string) {
// if (Qs) return Qs.parse(data)
let query: any = {}
for (let [k, v] of new URLSearchParams(data).entries()) {
let ms: any = /^(.+)(?:\[(.*)\])$/.exec(k)
if (ms) {
k = ms[1]
ms = ms[2]
if (!query[k]) {
query[k] = []
}
}
if (k in query) {
if (ms === null) {
query[k] = v
} else if (ms) {
query[k][ms] = v
} else {
query[k].push(v)
}
} else {
query[k] = v
}
}
return query
}
function buildRegex(path: string) {
let isReg = false
let temp: any[] = []
path = path.replace(/(\W):(?:(\w+)\(([^/]+)\)|(\w+))/g, (...ms) => {
ms[1] = ms[1].replace(/([.*+{}()\[\]|])/, '\\$1')
if (ms[4]) {
temp.push(`${ms[1]}(?<${ms[4]}>[^/]+)`)
} else {
temp.push(`${ms[1]}(?<${ms[2]}>${ms[3]})`)
}
return '#' + (temp.length - 1) + '#'
})
path = path.replace('**', () => {
temp.push('.*')
return '#' + (temp.length - 1) + '#'
})
path = path.replace('*', () => {
temp.push('[^/]*')
return '#' + (temp.length - 1) + '#'
})
path = path.replace('?', () => {
temp.push('?')
return '#' + (temp.length - 1) + '#'
})
path = path.replace('+', () => {
temp.push('+')
return '#' + (temp.length - 1) + '#'
})
path = path.replace(/\(.+?\)/, (ms) => {
temp.push(ms)
return '#' + (temp.length - 1) + '#'
})
path = path.replace('.', () => {
temp.push('\\.')
return '#' + (temp.length - 1) + '#'
})
if (temp.length) {
isReg = true
for (let [ix, str] of temp.entries()) {
path = path.replace('#' + ix + '#', str)
}
}
return {isReg, path}
}
interface Options {
router?: Router | Promise<any>,
beforeResponse?: (ctx: Context) => any
}
async function use(this: Adapter, router: Router | Promise<any>): Promise<Adapter> {
if ((<Promise<any>>router).then) {
router = await router
router = (<any>router).default || router
}
for (let route of (<Router>router).routes) {
if (route[1].charAt) {
let result = buildRegex(route[1])
if (result.isReg) {
route[1] = new RegExp('^' + result.path + '$')
}
} else if (route[1].push) {
let flags = ''
let arr = []
for (let item of route[1]) {
if (item.exec) {
arr.push(item.toString().replace(/^\/\^?|\$?\/(\w*)$/g, (...ms) => {
if (ms[1] && ms[1].includes('i')) {
flags = 'i'
}
return ''
}))
} else {
arr.push(buildRegex(item).path)
}
}
arr.unshift('^')
arr.push('$')
route[1] = new RegExp(arr.join(''), flags)
}
this.routes.push(route)
}
return this
}
export default async function create(opts: Options): Promise<Adapter & AxiosAdapter> {
let that = {opts, routes: [], use}
let fn = adapter.bind(that)
Object.assign(fn, that)
if (opts.router) {
await fn.use(opts.router)
}
return fn
}
interface Adapter {
opts: Options,
routes: any[][],
use: (router: Router | Promise<Router>) => Promise<Adapter>
}
async function adapter(this: Adapter, config: InternalAxiosRequestConfig): Promise<AxiosResponse> {
let urlSplit = config.url.split('?')
let query = Object.assign(urlSplit[1] ? parseUrlencoded(urlSplit[1]) : {}, config.params)
let body: {}
let contentType = config.headers.getContentType()
if (!contentType || !config.data) {
body = config.data || {}
} else if (contentType.includes('json')) {
body = JSON.parse(config.data)
} else if (contentType.includes('urlenc')) {
body = parseUrlencoded(config.data)
} else {
body = config.data || {}
}
let ctx = new Context(config, query, body, urlSplit[0], urlSplit[1])
out: for (let [method, path, ...cbs] of this.routes) {
if (method && method !== config.method) continue
let ms
if (!path || (path.exec && (ms = path.exec(urlSplit[0]))) || (path === urlSplit[0])) {
ctx.req.regExp = path
ctx.req.regMatch = ms || []
ctx.req.regNamed = (ms && ms.groups) || {}
for (let cb of cbs) {
let next = false
let rt = cb(ctx, () => (next = true))
if (next) {
continue
} else {
await rt
}
if (next) {
continue
}
if (this.opts.beforeResponse) {
await this.opts.beforeResponse(ctx)
}
if (ctx.bypass) {
break out
}
// @ts-ignore
return {
config: config,
status: ctx.status,
headers: ctx.headers,
data: ctx.body,
}
}
}
}
delete config.adapter
return axios(config)
}