AreWe

Untitled

Nov 9th, 2020
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.18 KB | None | 0 0
  1. const api = (() => {
  2. const make = async (func, callback) => {
  3. let res;
  4. try {
  5. res = await func();
  6. if (typeof callback === 'function') {
  7. await callback(res);
  8. }
  9. } catch (error) {
  10. notify(error.message);
  11. }
  12.  
  13. return res; // ako vuobshte na nqkoimu trqbva sled callback-a moje da si awaitne v async func
  14. };
  15.  
  16. const request = async (options, endpoint = '') => {
  17. const res = await fetch(`https://fisher-game.firebaseio.com/catches/${endpoint}.json`, options);
  18. if (res.ok) {
  19. return res.json();
  20. }
  21.  
  22. throw new Error(`${options.method}: ${res.statusText}`);
  23. };
  24.  
  25. return {
  26. get: (callback) => make(() => request({ method: 'GET' }), callback),
  27. create: (data, callback) => make(() => request({ method: 'POST', body: data }), callback),
  28. // PATCH bi bilo udachno, no mnogo potrebiteli clickat na edni i sushti neshta, zaradi tova PUT s celiq obekt
  29. update: (data, id, callback) => make(() => request({ method: 'PUT', body: data }, id), callback),
  30. delete: (id, callback) => make(() => request({ method: 'DELETE' }, id), callback),
  31. };
  32. })();
Advertisement
Add Comment
Please, Sign In to add comment