-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathplugin.js
243 lines (200 loc) · 5.87 KB
/
plugin.js
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
import defu from 'defu'
import destr from 'destr'
import KY from 'ky'
class HTTP {
constructor(defaults, ky = KY) {
this._defaults = {
hooks: {},
...defaults
}
this._ky = ky
}
getBaseURL () {
return this._defaults.prefixUrl
}
setBaseURL (baseURL) {
this._defaults.prefixUrl = baseURL
}
setHeader(name, value) {
if (!value) {
delete this._defaults.headers[name];
} else {
this._defaults.headers[name] = value
}
}
setToken(token, type) {
const value = !token ? null : (type ? type + ' ' : '') + token
this.setHeader('Authorization', value)
}
_hook(name, fn) {
if (!this._defaults.hooks[name]) {
this._defaults.hooks[name] = []
}
this._defaults.hooks[name].push(fn)
}
onRequest(fn) {
this._hook('beforeRequest', fn)
}
onRetry(fn) {
this._hook('beforeRetry', fn)
}
onResponse(fn) {
this._hook('afterResponse', fn)
}
onError(fn) {
this._hook('onError', fn)
}
create(options) {
const { retry, timeout, prefixUrl, headers, searchParams } = this._defaults
return createHttpInstance(defu(options, { retry, timeout, prefixUrl, headers, searchParams }))
}
}
for (let method of ['get', 'head', 'delete', 'post', 'put', 'patch']) {
const hasBody = ['post', 'put', 'patch'].includes(method)
HTTP.prototype[method] = async function (url, arg1, arg2) {
let options
if (!hasBody) {
options = arg1
} else {
options = arg2 || {}
if (arg1 !== undefined) {
if (arg1.constructor === Object || Array.isArray(arg1)) {
options.json = arg1
} else {
options.body = arg1
}
}
}
const _options = defu(options, this._defaults)
// Merge searchParams (mix strings, objects, and URLSearchParams instances)
if (this._defaults.searchParams && options && options.searchParams) {
const params1 = new URLSearchParams(this._defaults.searchParams);
const params2 = new URLSearchParams(options.searchParams);
for (let [key] of params2.entries()) {
// params2 overrides params1 to let's remove any param with the same key
params1.delete(key)
}
for (let [key, val] of params2.entries()) {
params1.append(key, val);
}
_options.searchParams = params1
}
if (/^https?/.test(url)) {
delete _options.prefixUrl
} else if (_options.prefixUrl && typeof url === 'string' && url.startsWith('/')) {
// Prevents `ky` from throwing "`input` must not begin with a slash when using `prefixUrl`"
url = url.substr(1)
}
try {
const response = await this._ky[method](url, _options)
return response
} catch (error) {
// Try to fill error with useful data
if (error.response) {
error.statusCode = error.response.status
try {
const text = await error.response.text()
error.response.text = () => Promise.resolve(text)
const json = destr(text)
error.response.json = () => Promise.resolve(json)
error.response.data = json
} catch (_) { }
}
// Call onError hook
if (_options.hooks.onError) {
for (const fn of _options.hooks.onError) {
const res = fn(error)
if (res !== undefined) {
return res
}
}
}
// Throw error
throw error
}
}
HTTP.prototype['$' + method] = function (url, arg1, arg2) {
return this[method](url, arg1, arg2)
.then(response => (response && response.text) ? response.text() : response)
.then(body => destr(body))
}
}
const createHttpInstance = options => {
// Create new HTTP instance
const http = new HTTP(options)
// Setup interceptors
<% if (options.debug) { %>setupDebugInterceptor(http) <% } %>
return http
}
<% if (options.debug) { %>
const log = (level, ...messages) => console[level]('[Http]', ...messages)
const setupDebugInterceptor = http => {
// request
http.onRequest(req => {
log(
'info',
'Request:',
'[' + req.method.toUpperCase() + ']',
req.url
)
if (process.browser) {
console.log(req)
} else {
console.log(JSON.stringify(req, undefined, 2))
}
})
// response
http.onResponse((req, options, res) => {
log(
'info',
'Response:',
'[' + (res.status + ' ' + res.statusText) + ']',
'[' + req.method.toUpperCase() + ']',
res.url,
)
if (process.browser) {
console.log(req, options, res)
} else {
console.log(JSON.stringify({ req, options, res }, undefined, 2))
}
return res
})
// error
http.onError(error => {
log('error', 'Error:', error)
})
}<% } %>
export default (ctx, inject) => {
// runtimeConfig
const runtimeConfig = ctx.$config && ctx.$config.http || {}
// prefixUrl
const prefixUrl = process.browser
? (runtimeConfig.browserBaseURL || '<%= options.browserBaseURL || '' %>')
: (runtimeConfig.baseURL || process.env._HTTP_BASE_URL_ || '<%= options.baseURL || '' %>')
const headers = <%= JSON.stringify(options.headers, null, 2) %>
// Defaults
const defaults = {
retry: <%= options.retry %>,
timeout: process.server ? <%= options.serverTimeout %> : <%= options.clientTimeout %>,
prefixUrl,
headers
}
<% if (options.proxyHeaders) { %>
// Proxy SSR request headers headers
if (process.server && ctx.req && ctx.req.headers) {
const reqHeaders = { ...ctx.req.headers }
for (let h of <%= serialize(options.proxyHeadersIgnore) %>) {
delete reqHeaders[h]
}
defaults.headers = { ...reqHeaders, ...defaults.headers }
}
<% } %>
if (process.server) {
// Don't accept brotli encoding because Node can't parse it
defaults.headers['accept-encoding'] = 'gzip, deflate'
}
const http = createHttpInstance(defaults)
// Inject http to the context as $http
ctx.$http = http
inject('http', http)
}