Skip to content

Commit

Permalink
Merge pull request #11 from liujinyang1994/master
Browse files Browse the repository at this point in the history
add timeout middleware
  • Loading branch information
starlight36 committed Dec 20, 2017
2 parents d22807d + 3189690 commit f1a0edd
Show file tree
Hide file tree
Showing 4 changed files with 49 additions and 1 deletion.
1 change: 1 addition & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ node_js:
- "4.4"
- "5.11"
- "6.3"
- "8.9"
sudo: false
cache:
bundler: true
Expand Down
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,15 @@ client.post('add', {
});
```

### timeout

Set timeout options to fetch.

```js
// Add timeout middleware
client.addMiddleware(timeout(1000));
```

### credentials

Set credentials options to fetch. If you want to automatically send cookies for the current domain, use this middleware and config it as `same-origin`.
Expand Down
8 changes: 8 additions & 0 deletions modules/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -153,3 +153,11 @@ export const userAgent = ua => request => {
export const credentials = credentials => request => {
request.options.credentials = credentials;
};

export const timeout = (s) => request => {
if (typeof parseInt(s, 10) !== 'number') throw new TypeError('function params not available');

const abort = new Promise((resolve, reject) => setTimeout(reject, s, 'request timeout!'));

return Promise.race([request, abort]);
};
32 changes: 31 additions & 1 deletion test/test.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
import assert from 'assert';
import FetchHttpClient, { query, form, json, header, userAgent, credentials } from '../modules';
import FetchHttpClient, {
query,
form,
json,
header,
userAgent,
credentials,
timeout,
} from '../modules';

describe('FetchHttpClient', () => {
it('should be a class.', () => {
Expand Down Expand Up @@ -247,3 +255,25 @@ describe('Middleware credentials', () => {
assert.equal(request.options.credentials, 'same-origin');
});
});

describe('Middleware timeout', () => {
it('should set timeout options on request.', () => {
const request = new Promise(resolve => {
setTimeout(resolve, 200, 'success!');
});

timeout(300)(request).then(res => {
assert.equal(res, 'success!');
});
});

it('should set timeout options on request. With timeout.', () => {
const request = new Promise(resolve => {
setTimeout(resolve, 200, 'success!');
});

timeout(100)(request).catch(err => {
assert.equal(err, 'request timeout!');
});
});
});

0 comments on commit f1a0edd

Please sign in to comment.