Advertisement
Guest User

Untitled

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