Skip to content

Commit

Permalink
feat: add onRetry hook (#79)
Browse files Browse the repository at this point in the history
  • Loading branch information
nijitaro authored and pi0 committed Nov 2, 2019
1 parent 55b8975 commit 3d0aa27
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 1 deletion.
7 changes: 7 additions & 0 deletions docs/guide/advanced.md
Original file line number Diff line number Diff line change
Expand Up @@ -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!')
Expand Down
4 changes: 4 additions & 0 deletions lib/plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@ class HTTP {
this._hook('beforeRequest', fn)
}

onRetry(fn) {
this._hook('beforeRetry', fn)
}

onResponse(fn) {
this._hook('afterResponse', fn)
}
Expand Down
9 changes: 8 additions & 1 deletion types/index.d.ts
Original file line number Diff line number Diff line change
@@ -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>>;
Expand Down Expand Up @@ -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)
*
Expand Down

0 comments on commit 3d0aa27

Please sign in to comment.