Advertisement
EntropyStarRover

requester

Nov 25th, 2019
212
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const baseUrl = 'https://baas.kinvey.com';
  2. const appKey = 'kid_Sy6caBwnB';  
  3. const appSecret = '59ea654c53c1492cb5a59cd5cddc5962';
  4.  
  5. function makeAuth(type) {
  6.     return type === 'Basic'
  7.         ? 'Basic ' + btoa(`${appKey}:${appSecret}`)
  8.         : 'Kinvey ' + sessionStorage.getItem('authtoken');
  9. }
  10.  
  11. function makeHeaders(method, data, type) {
  12.     const headers = {
  13.         method,
  14.         headers: {
  15.             'Content-Type': 'application/json',
  16.             Authorization: makeAuth(type),
  17.         },
  18.     };
  19.  
  20.     if(method === 'POST' || method === 'PUT'){
  21.         headers.body = JSON.stringify(data);
  22.     }
  23.  
  24.     return headers;
  25. }
  26.  
  27. function handleError(res){
  28.     if(res.status === 409) {
  29.         alert('This username is already used!');
  30.     }
  31.     if (!res.ok) {
  32.         throw new Error(`Something went wrong! Status: ${res.status}, Status text: ${res.statusText}`);
  33.     }
  34.     if(res.status === 204){
  35.         return res;
  36.     }
  37.     return res.json();
  38. }
  39.  
  40. function fetchData(module, endpoint, headers) {
  41.     return fetch(`${baseUrl}/${module}/${appKey}/${endpoint}`, headers)
  42.         .then(handleError);
  43. }
  44.  
  45. export function get(module, endpoint, type) {
  46.     const headers = makeHeaders('GET', type);
  47.     return fetchData(module, endpoint, headers);
  48. }
  49.  
  50. export function post(module, endpoint, data, type) {
  51.     const headers = makeHeaders('POST', data, type);
  52.     return fetchData(module, endpoint, headers);
  53. }
  54.  
  55. export function put(module, endpoint, data, type) {
  56.     const headers = makeHeaders('PUT', data, type);
  57.     return fetchData(module, endpoint, headers);
  58. }
  59.    
  60. export function del(module, endpoint, type) {
  61.     const headers = makeHeaders('DELETE', type);
  62.     return fetchData(module, endpoint, headers);
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement