ErolKZ

Untitled

Apr 29th, 2022
34
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.16 KB | None | 0 0
  1.  
  2. // host url
  3. const host = 'http://localhost:3030';
  4.  
  5. // function accepts Method, url (not host) and data (Object - {})
  6. async function request(method, url, data) {
  7. // creating options
  8. const options = {
  9. method,
  10. headers: {},
  11. };
  12. // if there is no data then don't do the next step, 'cause you won't need it
  13. if (data != undefined) {
  14. options.headers['Content-Type'] = 'application/json';
  15. options.body = JSON.stringify(data);
  16. }
  17. // get user information from Local Storage
  18. const user = JSON.parse(localStorage.getItem('user'));
  19. if (user) {
  20. // Get Access Token and put it into the header
  21. const token = user.accessToken;
  22. options.headers['X-Authorization'] = token;
  23. };
  24. // try the fetch, if fails throw an Error and catch it
  25. try {
  26. // getting response
  27. const response = await fetch(host + url, options);
  28.  
  29. // if response status isn't OK (a.k.a. status != 200) throw an error
  30. if (response.ok !== true) {
  31. if (response.status == 403) localStorage.removeItem('user');
  32. const error = await response.json();
  33. throw new Error(error.message);
  34. }
  35.  
  36. // check if status is == 204, if true then return only the response, otherways return response.json()
  37. // logging out returns an object, which if tried to be parsed from JSON will throw an error (CHECK SERVER DOCUMENTATION!!)
  38. if (response.status == 204) {
  39. return response;
  40. } else {
  41. return response.json();
  42. }
  43. } catch (error) {
  44. // If Error is thrown, throw it again... like the hot ball game.. (a.k.a. Goresht Kartoff)...
  45. // so the function using the api would be able to decide what to do with that exact error (show it to the User or sth else)
  46. // alert(error.message);
  47. throw error;
  48. }
  49. }
  50. // creating copies for all the methods
  51. const get = request.bind(null, 'get');
  52. const post = request.bind(null, 'post');
  53. const put = request.bind(null, 'put');
  54. const del = request.bind(null, 'delete');
  55.  
  56. export {
  57. get,
  58. post,
  59. put,
  60. del as delete,
  61. };
Advertisement
Add Comment
Please, Sign In to add comment