-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
95 lines (88 loc) · 3 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
var hasAcceptHeader = require('./hasAcceptHeader.js');
var supportedMimeTypes = require('./supportedMimetypes.js');
var queryString = require('query-string');
if (process.env.NODE_ENV === 'test')
var fetch = require('node-fetch');
/**
* This function adds some functionality to React Native's fetch. It will
* automatically detect the Content-type of the response and return it.
* That way, you don't need to have an additional .then call in order to
* parse the response body.
* @param {string} uri - The uri being requested.
* @param {object} title - The exact same object you would pass to regular
* react native fetch.
* @param {object} author - A cache configuration object. It can contain two
* properties: type (session or persistent) and
* duration (ms). Duration will be ignored if cache
* type is session.
*/
var cache = {};
module.exports = function(uri, fetchConfig, cacheConfig){
//false if no accept header, header name if accept header is present:
var acceptHeader = hasAcceptHeader(fetchConfig.headers);
if (!fetchConfig.headers || !acceptHeader){
console.warn('In order to use fetch with caching, you must specify an accept header. Calls to react-native-fetch-cache without an accept header return the regular Fetch.');
return fetch(uri, fetchConfig);
}
var reqBody = fetchConfig.body;
if (reqBody && typeof reqBody !== 'string') {
try{
//automatic conversion to string
reqBody = JSON.stringify(reqBody);
}
catch(e){
throw {
message: 'Exception when stringifying request body',
details: e
}
}
fetchConfig.body = reqBody;
}
//cache layer
if (cache[uri]){
return new Promise(function(resolve, reject){
resolve(cache[uri]);
});
}
return new Promise(function(resolve, reject){
var failed = false;
fetch(uri, fetchConfig)
.then(function(res){
if (res.status < 200 || res.status > 299){
failed = true;
}
return res.text();
})
.then(function(responseBody){
if (failed){
reject(responseBody);
return;
}
var responseToSend = responseBody;
if (fetchConfig.headers[acceptHeader].toLowerCase() === 'application/json'){
try{
responseToSend = JSON.parse(responseToSend);
}
catch(e){
throw {
message: 'error parsing expected JSON response',
details: e
}
}
}
if (fetchConfig.headers[acceptHeader].toLowerCase() === 'application/x-www-form-urlencoded'){
try{
responseToSend = queryString.parse(responseBody);
}
catch(e){
throw {
message: 'error parsing expected url-encoded response',
details: e
}
}
}
cache[uri] = responseToSend;
resolve(responseToSend);
});
});
}