Advertisement
dimitrix85

requester

Dec 5th, 2019
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const appKey = 'kid_SycLh9U6H';
  2. const appSecret = '6f5b62403ad94bd8899065e144910306';
  3. const baseUrl = 'https://baas.kinvey.com';
  4.  
  5. function createAuthorization(type) {
  6.     return type === "Basic"
  7.         ? `Basic ${btoa(`${appKey}:${appSecret}`)}`
  8.         : `Kinvey ${sessionStorage.getItem('authtoken')}`
  9. }
  10.  
  11. function makeHeaders(type, httpMethod, data) {
  12.  
  13.     const headers = {
  14.         method: httpMethod,
  15.         headers: {
  16.             'Authorization': createAuthorization(type),
  17.             'Content-Type': 'application/json'
  18.         }
  19.     };
  20.  
  21.     if (httpMethod === 'POST' || httpMethod === 'PUT') {
  22.         headers.body = JSON.stringify(data)
  23.     }
  24.     return headers;
  25. }
  26.  
  27. function serializeData(x) {
  28.     if (x.status === 204) {
  29.         return x;
  30.     }
  31.     return x.json();
  32. }
  33.  
  34. function handleError(e) {
  35.     if (!e.ok) {
  36.         console.log(e);
  37.         throw new Error(e.statusText);
  38.     }
  39.     return e;
  40. }
  41.  
  42. function createPromise(kinveyModule, endpoint, headers) {
  43.     const url = `${baseUrl}/${kinveyModule}/${appKey}/${endpoint}`;
  44.  
  45.     return fetch(url, headers)
  46.         .then(handleError)
  47.         .then(serializeData)
  48. }
  49.  
  50. export function get(kinveyModule, endpoint, type) {
  51.     const headers = makeHeaders(type,'GET');
  52.     return createPromise(kinveyModule, endpoint, headers)
  53. }
  54.  
  55. export function post(kinveyModule, endpoint, data, type) {
  56.     const headers = makeHeaders(type, 'POST', data);
  57.     return createPromise(kinveyModule, endpoint, headers)
  58. }
  59.  
  60. export function put(kinveyModule, endpoint, data, type) {
  61.     const headers = makeHeaders(type, 'PUT', data);
  62.     return createPromise(kinveyModule, endpoint, headers)
  63. }
  64.  
  65. export function del(kinveyModule, endpoint, type) {
  66.     const headers = makeHeaders(type, 'DELETE');
  67.     return createPromise(kinveyModule, endpoint, headers)
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement