Advertisement
bebo231312312321

Untitled

Jun 30th, 2023
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // window.addEventListener('load', onLoad)
  2.  
  3. document.querySelectorAll('a').forEach(element => element.classList.remove('active'));
  4. document.getElementById('home').classList.add('active');
  5.  
  6. const catches = document.getElementById('catches');
  7.  
  8. const addBtn = document.querySelector('.add')
  9.  
  10. const loadBtn = document.querySelector('.load');
  11. loadBtn.addEventListener('click', loadCatches)
  12.  
  13. const formAdd = document.querySelector("#addForm")
  14. // function onLoad(e) {
  15.   const dataUser = JSON.parse(sessionStorage.getItem('dataUser'))
  16.   catches.innerHTML = '';
  17. if (dataUser !== null) {
  18.     document.getElementById('user').style.display = "inline-block"
  19.     document.getElementById('guest').style.display = "none"
  20.     document.querySelector("p.email span").textContent = dataUser.email
  21.     addBtn.disabled = false
  22.     loadCatches()
  23. } else {
  24.     addBtn.disabled = true
  25.     document.getElementById('user').style.display = 'none'
  26.     document.getElementById('guest').style.display = "inline-block"
  27. }
  28. //  }
  29.  
  30. document.querySelector('#main').addEventListener('click', onButtons)
  31.  
  32. function onButtons(e) {
  33.     const currentBtn = e.target.textContent
  34.     const id = e.target.id === "" ? e.target.dataset.id : e.target.id
  35.     const currentEl = e.target.parentElement
  36.     if (currentBtn === "Delete") {
  37.         onDelete(id)
  38.     } else if (currentBtn === 'Update') {
  39.         onUpdate(id, currentEl)
  40.     }
  41.  
  42.  }
  43. async function onDelete(id) {
  44.     const url = `http://localhost:3030/data/catches/${id}`
  45.     const response = await fetch(url, {
  46.         method: 'DELETE',
  47.         headers: {
  48.             'Content-Type': 'application/json',
  49.             'X-Authorization': dataUser.accessToken
  50.         },
  51.     })
  52.     const data = await response.json()
  53.     loadCatches()
  54. }
  55.  
  56. async function onUpdate(id, currentEl) {
  57.     let [angler, weight, species, location, bait, captureTime] = currentEl.querySelectorAll('input')
  58.     const url = `http://localhost:3030/data/catches/${id}`
  59.     const body = JSON.stringify({
  60.         angler: angler.value,
  61.         weight: Number(weight.value),
  62.         species: species.value,
  63.         location: location.value,
  64.         bait: bait.value,
  65.         captureTime: Number(captureTime.value)
  66.     })
  67.  
  68.     try {
  69.         const response = await fetch(url, {
  70.             method: 'PUT',
  71.             headers: {
  72.                 'Content-Type': 'application/json',
  73.                 'X-Authorization': dataUser.accessToken
  74.             },
  75.             body,
  76.  
  77.         })
  78.         const data = await response.json()
  79.         if (!response.ok) throw new Error(data.message)
  80.  
  81.     } catch (e) {
  82.  
  83.         alert(e.message)
  84.     }
  85.     loadCatches()
  86. }
  87.  
  88.  
  89.  
  90.  
  91.  
  92.  
  93. formAdd.addEventListener('submit', (e) => {
  94.     e.preventDefault();
  95.     const formData = new FormData(e.target);
  96.     onAdd([...formData.entries()].reduce((a, [k, v]) => Object.assign(a, { [k]: v }), {}))
  97.     e.target.reset()
  98. });
  99.  
  100. async function onAdd(body) {
  101.     // console.log(body)
  102.  
  103.     const url = `http://localhost:3030/data/catches`
  104.  
  105.     try {
  106.         if (Object.values(body).some(x => x === "")) throw new Error("Some fields are empty")
  107.  
  108.         const response = await fetch(url, {
  109.  
  110.             method: 'POST',
  111.             headers: {
  112.                 'Content-Type': 'application/json',
  113.                 'X-Authorization': `${dataUser.accessToken}`
  114.             },
  115.             body: JSON.stringify(body)
  116.         })
  117.         const data = await response.json()
  118.         console.log(data)
  119.         if (!response.ok) throw new Error(data.message)
  120.         loadCatches()
  121.     } catch (e) {
  122.         alert(e.message)
  123.  
  124.     }
  125.  
  126. }
  127.  
  128. async function loadCatches() {
  129.     const url = `http://localhost:3030/data/catches`
  130.     const response = await fetch(url)
  131.     const data = await response.json()
  132.     console.log(data)
  133.     document.getElementById('catches').replaceChildren(...data.map(createInfo));
  134.  
  135. }
  136. function createInfo(data) {
  137.  
  138.     let isDisabled = (dataUser && data._ownerId === dataUser.id) ? false : true
  139.     const divCatches = createElements('div', { class: 'catch' },
  140.         createElements('label', {}, 'Angler'),
  141.         createElements('input', { type: 'text', class: 'angler', value: data.angler, disabled: isDisabled }),
  142.         createElements('label', {}, 'Weight'),
  143.         createElements('input', { type: 'text', class: 'weight', value: data.weight, disabled: isDisabled }),
  144.         createElements('label', {}, 'Species'),
  145.         createElements('input', { type: 'text', class: 'species', value: data.species, disabled: isDisabled }),
  146.         createElements('label', {}, 'Location'),
  147.         createElements('input', { type: 'text', class: 'location', value: data.location, disabled: isDisabled }),
  148.         createElements('label', {}, 'Bait'),
  149.         createElements('input', { type: 'text', class: 'bait', value: data.bait, disabled: isDisabled }),
  150.         createElements('label', {}, 'Capture Time'),
  151.         createElements('input', { type: 'text', class: 'captureTime', value: data.captureTime, disabled: isDisabled }),
  152.         createElements('button', { class: "update", id: data._id, disabled: isDisabled }, "Update"),
  153.         createElements('button', { class: "delete", id: data._id, disabled: isDisabled }, "Delete"),
  154.     )
  155.     return divCatches
  156. }
  157. document.getElementById('logout').addEventListener('click', async (e) => {
  158.  
  159.     const url = `http://localhost:3030/users/logout`
  160.     const response = await fetch(url)
  161.     const data = await response.json();
  162.     sessionStorage.clear();
  163.     window.location = '/src/index.html'
  164. });
  165.  
  166.  
  167. function createElements(type, atr, ...content) {
  168.     const element = document.createElement(type)
  169.     for (const at in atr) {
  170.         if (at === "class") {
  171.             element.classList.add(atr[at])
  172.         } else if (at === 'disable') {
  173.             element.disabled = atr[at]
  174.         } else {
  175.             element[at] = atr[at]
  176.         }
  177.  
  178.     }
  179.     for (let el of content) {
  180.         if (typeof el == 'string' || typeof el === 'number') {
  181.             el = document.createTextNode(el);
  182.  
  183.         }
  184.  
  185.         element.appendChild(el)
  186.     }
  187.  
  188.     return element;
  189.  
  190. }
  191. // function header(method, body) {
  192. //     const accessToken = dataUser.accessToken
  193. //     return {
  194. //         method: `${method}`,
  195. //         headers: {
  196. //             "Content-Type": "application/json",
  197. //             "X-Authorization": `${dataUser.accessToken}`
  198. //         },
  199. //         body: JSON.stringify(body)
  200. //     }
  201. // }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement