http/lib/plugin.js

100 lines
2.3 KiB
JavaScript

import KY from 'ky-universal'
class HTTP {
constructor(defaults, ky = KY) {
this._defaults = {
hooks: {},
headers: {},
retry: 0,
...defaults
}
this._ky = ky
}
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)
}
onResponse(fn) {
this._hook('afterResponse', fn)
}
onError(fn) {
this._hook('onError', fn)
}
}
for (let method of ['get', 'post', 'put', 'patch', 'head', 'delete']) {
HTTP.prototype[method] = async function (input, options) {
const _options = { ...this._defaults, ...options }
if (/^https?/.test(input)) {
delete _options.prefixUrl
}
try {
const response = await this._ky[method](input, _options)
return response
} catch (error) {
// Call onError hook
if (_options.hooks.onError) {
_options.hooks.onError.forEach(fn => fn(error))
}
// Throw error
throw error
}
}
HTTP.prototype['$' + method] = function (input, options) {
return this[method](input, options).then(res => res.json())
}
}
export default (ctx, inject) => {
// prefixUrl
const prefixUrl = process.browser
? '<%= options.browserBaseURL %>'
: (process.env._HTTP_BASE_URL_ || '<%= options.baseURL %>')
// Defaults
const defaults = { prefixUrl }
<% if (options.proxyHeaders) { %>
// Proxy SSR request headers headers
defaults.headers = (ctx.req && ctx.req.headers) ? { ...ctx.req.headers } : {}
<% for (let h of options.proxyHeadersIgnore) { %>delete defaults.headers['<%= h %>']
<% } %><% } %>
if (process.server) {
// Don't accept brotli encoding because Node can't parse it
defaults.headers['Accept-Encoding'] = 'gzip, deflate'
}
// Create new HTTP instance
const http = new HTTP(defaults)
// Inject http to the context as $http
ctx.$http = http
inject('http', http)
}