Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import superagentPromise from 'superagent-promise';
- import _superagent from 'superagent';
- // http client
- const superagent = superagentPromise(_superagent, global.Promise);
- // root api url
- const API_ROOT = 'https://conduit.productionready.io/api';
- // callback to extract the body out of a response
- const responseBody = (res) => res.body;
- // variable storing the auth token
- let token = null;
- // attach authorization token to the request so we can make requests which require
- // authorization.
- const tokenPlugin = (req) => {
- if (token) {
- req.set('authorization', `Token ${token}`);
- }
- };
- // http method wrapppers
- // make a request to the given url, attach auth header, parse out body
- const requests = {
- get: (url) =>
- superagent.get(`${API_ROOT}${url}`).use(tokenPlugin).then(responseBody),
- post: (url, body) =>
- superagent.post(`${API_ROOT}${url}`).use(tokenPlugin).then(responseBody),
- };
- // articles methods
- const Articles = {
- // get promise for 10 articles
- all: (page) => requests.get('/articles?limit=10'),
- };
- const Auth = {
- // get current user's user object
- current: () => requests.get('/user'),
- // get promise for login success/failure
- login: (email, password) =>
- requests.post('/users/login', {user: {email, password}}),
- };
- export default {
- Articles,
- Auth,
- // set the token to the passed in parameter
- setToken: (_token) => {
- token = _token;
- },
- };
Advertisement
Add Comment
Please, Sign In to add comment