AllenYuan

auth - agent update

Apr 24th, 2020
795
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import superagentPromise from 'superagent-promise';
  2. import _superagent from 'superagent';
  3.  
  4. // http client
  5. const superagent = superagentPromise(_superagent, global.Promise);
  6.  
  7. // root api url
  8. const API_ROOT = 'https://conduit.productionready.io/api';
  9.  
  10. // callback to extract the body out of a response
  11. const responseBody = (res) => res.body;
  12.  
  13. // variable storing the auth token
  14. let token = null;
  15. // attach authorization token to the request so we can make requests which require
  16. // authorization.
  17. const tokenPlugin = (req) => {
  18.   if (token) {
  19.     req.set('authorization', `Token ${token}`);
  20.   }
  21. };
  22.  
  23. // http method wrapppers
  24. // make a request to the given url, attach auth header, parse out body
  25. const requests = {
  26.   get: (url) =>
  27.     superagent.get(`${API_ROOT}${url}`).use(tokenPlugin).then(responseBody),
  28.   post: (url, body) =>
  29.     superagent.post(`${API_ROOT}${url}`).use(tokenPlugin).then(responseBody),
  30. };
  31.  
  32. // articles methods
  33. const Articles = {
  34.   // get promise for 10 articles
  35.   all: (page) => requests.get('/articles?limit=10'),
  36. };
  37.  
  38. const Auth = {
  39.   // get current user's user object
  40.   current: () => requests.get('/user'),
  41.   // get promise for login success/failure
  42.   login: (email, password) =>
  43.     requests.post('/users/login', {user: {email, password}}),
  44. };
  45.  
  46. export default {
  47.   Articles,
  48.   Auth,
  49.   // set the token to the passed in parameter
  50.   setToken: (_token) => {
  51.     token = _token;
  52.   },
  53. };
Advertisement
Add Comment
Please, Sign In to add comment