Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 22 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
const fetch = require('react-native-cancelable-fetch');
const uuidv4 = require('uuid/v4');
const promiseTimeout = require('promise-timeout');
const timeout = promiseTimeout.timeout;
const TimeoutError = promiseTimeout.TimeoutError;

export default class RestClient {
constructor (baseUrl = '', { headers = {}, devMode = false, simulatedDelay = 0 } = {}) {
constructor (baseUrl = '', { headers = {}, devMode = false, simulatedDelay = 0, timeout = 0 } = {}) {
if (!baseUrl) throw new Error('missing baseUrl');
this.headers = {
'Accept': 'application/json',
Expand All @@ -9,6 +15,7 @@ export default class RestClient {
this.baseUrl = baseUrl;
this.simulatedDelay = simulatedDelay;
this.devMode = devMode;
this.timeout = timeout;
}

_simulateDelay () {
Expand Down Expand Up @@ -39,15 +46,27 @@ export default class RestClient {
if (body) {
Object.assign(opts, { body: JSON.stringify(body) });
}
const fetchPromise = () => fetch(fullRoute, opts);
const uuid = uuidv4();
let fetchPromise;
if (this.timeout) {
fetchPromise = () => timeout(fetch(fullRoute, opts, uuid), this.timeout);
} else {
fetchPromise = () => fetch(fullRoute, opts);
}
if (this.devMode && this.simulatedDelay > 0) {
// Simulate an n-second delay in every request
return this._simulateDelay()
.then(() => fetchPromise())
.then(response => response.json());
} else {
return fetchPromise()
.then(response => response.json());
.then(response => response.json())
.catch(e => {
if (e instanceof TimeoutError) {
fetch.abort(uuid);
}
throw e;
});
}
}

Expand Down
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@
},
"homepage": "https://github.com/javorosas/react-native-rest-client#readme",
"dependencies": {
"qs": "^6.3.0"
"promise-timeout": "^1.3.0",
"qs": "^6.3.0",
"react-native-cancelable-fetch": "^0.1.1",
"uuid": "^3.2.1"
}
}