AreWe

02. FISHER-GAME

Nov 10th, 2020
778
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. (() => {
  2.   const elements = document.querySelectorAll('#catches, aside > button, #addForm > input');
  3.   const [catches, loadBtn, ...inputs] = elements;
  4.  
  5.   const notify = (() => {
  6.     const container = document.createElement('div');
  7.     container.style = 'position: fixed; width: 100%; bottom: 0; left: 0; text-align: center;';
  8.     document.querySelector('body').appendChild(container);
  9.  
  10.     return (message = '', isError = true) => {
  11.       const notification = document.createElement('span');
  12.       notification.textContent = message;
  13.       notification.style = `display: block;
  14.       color: ${isError ? '#cc3300' : '#33cc33'};
  15.       padding: 3px 15px 5px 15px;
  16.       background: #ffffff;
  17.       border: 1px solid #000000;
  18.       margin: 0 auto;
  19.       margin-bottom: 10px;
  20.       width: fit-content;
  21.       font-size: 14px;
  22.       text-align: center;
  23.       text-shadow: 0.5px 0.5px 0px #000000;
  24.       cursor: pointer;`;
  25.       container.insertBefore(notification, container.firstChild);
  26.       notification.addEventListener('click', () => {
  27.         container.removeChild(notification);
  28.         console[isError ? 'error' : 'log'](message);
  29.       });
  30.       setTimeout(() => (container.contains(notification) ? container.removeChild(notification) : null), 5000);
  31.     };
  32.   })();
  33.  
  34.   const api = (() => {
  35.     const make = async (func, callback) => {
  36.       let res;
  37.       try {
  38.         res = await func();
  39.         if (typeof callback === 'function') {
  40.           await callback(res);
  41.         }
  42.       } catch (error) {
  43.         notify(error.message);
  44.       }
  45.  
  46.       return res; // ako vuobshte na nqkoimu trqbva sled callback-a moje da si awaitne v async func
  47.     };
  48.  
  49.     const request = async (options, endpoint = '') => {
  50.       const res = await fetch(`https://fisher-game.firebaseio.com/catches/${endpoint}.json`, options);
  51.       if (res.ok) {
  52.         return res.json();
  53.       }
  54.  
  55.       throw new Error(`${options.method}: ${res.statusText}`);
  56.     };
  57.  
  58.     return {
  59.       get: (callback) => make(() => request({ method: 'GET' }), callback),
  60.       create: (data, callback) => make(() => request({ method: 'POST', body: data }), callback),
  61.       // PATCH bi bilo udachno, no mnogo potrebiteli clickat na edni i sushti neshta, zaradi tova PUT s celiq obekt
  62.       update: (data, id, callback) => make(() => request({ method: 'PUT', body: data }, id), callback),
  63.       delete: (id, callback) => make(() => request({ method: 'DELETE' }, id), callback),
  64.     };
  65.   })();
  66.  
  67.   const setLoadedData = (data) => {
  68.     catches.innerHTML = Object.entries(data || {})
  69.       .map(([id, { angler = '', weight = '', species = '', location = '', bait = '', captureTime = '' }]) => {
  70.         return `<div class="catch" data-id="${id}">
  71.             <label>Angler</label>
  72.             <input type="text" class="angler" value="${angler}">
  73.             <hr>
  74.             <label>Weight</label>      
  75.             <input type="number" class="weight" value="${weight}">
  76.             <hr>
  77.             <label>Species</label>
  78.             <input type="text" class="species" value="${species}">
  79.             <hr>
  80.             <label>Location</label>
  81.             <input type="text" class="location" value="${location}">
  82.             <hr>
  83.             <label>Bait</label>
  84.             <input type="text" class="bait" value="${bait}">
  85.             <hr>
  86.             <label>Capture Time</label>
  87.             <input type="number" class="captureTime" value="${captureTime}">
  88.             <hr>
  89.             <button class="update">Update</button>
  90.             <button class="delete">Delete</button>
  91.         </div>`;
  92.       })
  93.       .join('');
  94.   };
  95.  
  96.   const loadData = () => api.get(setLoadedData);
  97.  
  98.   const createData = (data) => {
  99.     api.create(JSON.stringify(data), ({ name }) => {
  100.       notify(`Successfully created entry with id: ${name}`, false);
  101.       inputs.forEach((el) => (el.value = ''));
  102.       loadData();
  103.     });
  104.   };
  105.  
  106.   const updateData = (data, id) => {
  107.     api.update(JSON.stringify(data), id, () => {
  108.       notify(`Successfully updated entry with id: ${id}`, false);
  109.       loadData();
  110.     });
  111.   };
  112.  
  113.   const deleteData = (id) => {
  114.     api.delete(id, () => {
  115.       notify(`Successfully deleted entry with id: ${id}`, false);
  116.       loadData();
  117.     });
  118.   };
  119.  
  120.   catches.addEventListener('click', (event) => {
  121.     const target = event.target;
  122.     if (target.tagName === 'BUTTON') {
  123.       const id = target.parentElement.getAttribute('data-id');
  124.       if (target.textContent === 'Update') {
  125.         const inputs = [...target.parentElement.querySelectorAll('input')];
  126.         const [angler, weight, species, location, bait, captureTime] = inputs.map((el) => el.value.trim());
  127.         if ([angler, weight, species, location, bait, captureTime].findIndex((val) => !val) !== -1) {
  128.           return notify(`Please fill all fields in the form in order to update entry ${id}`);
  129.         }
  130.  
  131.         updateData({ angler, weight, species, location, bait, captureTime }, id);
  132.       } else if (target.textContent === 'Delete') {
  133.         deleteData(id);
  134.       }
  135.     }
  136.   });
  137.  
  138.   loadBtn.addEventListener('click', () => loadData());
  139.  
  140.   document.querySelector('#addForm > button').addEventListener('click', () => {
  141.     const [angler, weight, species, location, bait, captureTime] = inputs.map((el) => el.value.trim());
  142.     if ([angler, weight, species, location, bait, captureTime].findIndex((val) => !val) !== -1) {
  143.       return notify(`Please fill all fields in the form in order to create a new entry`);
  144.     }
  145.  
  146.     createData({ angler, weight, species, location, bait, captureTime });
  147.   });
  148.  
  149.   loadBtn.click();
  150. })();
  151.  
Advertisement
Add Comment
Please, Sign In to add comment