wirejs v0.7.0
Wire
Wire allows you to cache network requests. Wire stores responses from network requests in memory, and returns them when you make a request to the same url twice. It only creates new requests when you make a request to a new URL.
Wire works in Node and in the browser. It requires a working implementation of fetch.
Installation
npm install wirejs --save
Usage
import Wire from 'wirejs';
// Create a new Wire object by passing it
// your favorite implementation of fetch.
const wire = Wire(fetch);
// Make requests
wire('https://api.github.com/users/restlessbit')
.then(response => {
// Get the response body as JSON
return response.json();
}).then(user => {
// Do something cool
console.log(user);
});
The second time a request is made to 'https://api.github.com/users/restlessbit' with Wire, Wire will return the same response from memory, without making a new network request.
API
wire(url, options)
Returns a Promise that resolves to the response of an underlying fetch request made to the specified url.
url: String
The url to send the request to.
options: Object
Hash of options for Wire, and for the underlying fetch request.
Available options
refresh: Boolean
Force a new network request by setting this option to true.
resolve: String ('text' or 'json')
Resolve underlying fetch request to text or JSON.
wire('https://api.github.com/users/restlessbit', {
resolve: 'json'
}).then(user => {
// Do something cool
console.log(user);
});
Examples
Passing options to fetch()
// Enable CORS and Set request headers
wire('https://api.github.com/users/restlessbit', {
mode: 'cors',
headers: {
'Accept': 'application/json'
},
}).then(response => {
// Get JSON from response
return response.json();
}).then(user => {
// Do something cool
console.log(user);
});
Forcing a new network request
// Pass options to fetch() and set 'refresh' to true
wire('https://api.github.com/users/restlessbit', {
mode: 'cors',
headers: {
'Accept': 'application/json'
},
refresh: true,
resolve: 'json'
}).then(user => {
// Do something cool
console.log(user);
});
Handling rejection
// Pass options to fetch() and set 'refresh' to true
wire('https://api.github.com/users/restlessbit', {
mode: 'cors',
headers: {
'Accept': 'application/json'
},
refresh: true,
resolve: 'json'
}).then(user => {
// Do something cool
console.log(user);
}).catch(error => {
// Promise was rejected.
console.log(error);
});