feat: add `onRetry` hook (#79)

master
Kotaro Imai 2019-11-02 20:02:50 +09:00 committed by Pooya Parsa
parent 55b8975b8c
commit 3d0aa272d2
3 changed files with 19 additions and 1 deletions

View File

@ -29,11 +29,18 @@ For registering hooks, you have to create a nuxt plugin:
**plugins/http.js**
```js
import ky from 'ky-universal'
export default function ({ $http }) {
$http.onRequest(config => {
console.log('Making request to ' + config.url)
})
$http.onRetry(async (request, options, errors, retryCount) => {
const token = await ky('https://example.com/refresh-token')
options.header.set('Authorization', `Bearer ${token}`)
})
$http.onError(error => {
if(error.response.status === 500) {
alert('Request Error!')

View File

@ -34,6 +34,10 @@ class HTTP {
this._hook('beforeRequest', fn)
}
onRetry(fn) {
this._hook('beforeRetry', fn)
}
onResponse(fn) {
this._hook('afterResponse', fn)
}

9
types/index.d.ts vendored
View File

@ -1,5 +1,5 @@
import Vue from 'vue'
import { ResponsePromise, Options, BeforeRequestHook, AfterResponseHook, HTTPError } from 'ky'
import { ResponsePromise, Options, BeforeRequestHook, BeforeRetryHook, AfterResponseHook, HTTPError } from 'ky'
import './vuex'
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
@ -126,6 +126,13 @@ interface NuxtHTTPInstance {
*/
onRequest(hook: BeforeRequestHook): void
/**
* Set a hook on `beforeRetry` (Before request is sent)
*
* This hook enables you to modify the request right before retry. It will make no further changes to the request after this. The hook function receives the normalized input and options, an error instance and the retry count as arguments. You could, for example, modify `options.headers` here.
*/
onRetry(hook: BeforeRetryHook): void
/**
* Set a hook on `afterResponse` (After the response is received)
*