API
Gambit provides the GambitApi
class to help you connect your ActionCreators to your API. With our sample application, we need a layer that calls the Github API to search for users.
Create a file src/Api.js
:
import { GambitApi } from 'gambit';
export default new GambitApi({
user: {
search({ query }) {
return this.get({
url: `search/users?q=${query}`,
});
},
},
}, 'https://api.github.com/');
The first argument passed to GambitApi
is a nested object that describes the API you want to access. The second is the API base URL.
Each method you declare can make use of this.post
, this.get
, this.del
and this.put
which will each send the relevant method to the url you have declared.
Properties passed to this.get
etc are the same as you will find in the fetch
or node-fetch
library.
setHeaders
A useful method for the GambitApi class is setHeaders
. This takes an object that will be added on to the headers of any request you make. For instance:
const MyApi = new GambitApi({
users: {
getAll() {
return this.get({
url: `users`,
})
},
},
}, 'https://myapi.website.com');
MyApi.setHeaders({ Authorization: 'Bearer TOKEN'; });
MyApi.users.getAll();
// -> { url: `users`, headers: { Authorization: 'Bearer TOKEN' } }
This can be helpful when you have an action that needs to set an authorization token for all future API calls.
setFetchLib
All HTTP request libraries are awful and so you may have on that you feel is less awful (request-promise
, superagent
etc). As such you can change what the underlying http engine for GambitApi
is:
import rp from 'request-promise';
const api = new GambitApi({...});
api.setFetchLib(rp);
When the internal fetch library is called it is called with two parameters:
- The first is the url. (This will be combined with your initial baseUrl)
- The second is the rest of the object parameters you've passed into
this.post
,this.get
etc. (By default this also getsmethod
andheaders
where you have usedsetHeaders
.
This is because most common libraries support the url as the first parameter and an object of options as the second. If you're using something that requires the url to be passed as part of the object you can easily do something like this:
import fancyLibrary from 'fancy-library';
const api = new GambitApi({...});
const lib = (url, props) => fancyLibrary({ url, ...props });
api.setFetchLib(lib);