import axios from 'axios'; import { load } from 'cheerio'; import { getPizzaListMock } from './mock'; // TODO přesunout do types type PizzaSize = { varId: number, size: string, pizzaPrice: number, boxPrice: number, price: number } // TODO přesunout do types type Pizza = { name: string, ingredients: string[], sizes: PizzaSize[], } // TODO mělo by být konfigurovatelné proměnnou z prostředí s tímhle jako default const baseUrl = 'https://www.pizzachefie.cz'; const pizzyUrl = `${baseUrl}/pizzy.html?pobocka=plzen`; const buildPizzaUrl = (pizzaUrl: string) => { return `${baseUrl}/${pizzaUrl}`; } // Ceny krabic dle velikosti const boxPrices: { [key: string]: number } = { "30cm": 13, "35cm": 15, "40cm": 18, "50cm": 25 } /** * Stáhne a scrapne aktuální pizzy ze stránek Pizza Chefie. * * @param mock zda vrátit pouze mock data */ export async function downloadPizzy(mock: boolean): Promise { if (mock) { // Záměrné zpoždění pro testování return new Promise((resolve) => setTimeout(() => resolve(getPizzaListMock()), 3000)); } // Získáme seznam pizz const html = await axios.get(pizzyUrl).then(res => res.data); const $ = load(html); const links = $('.vypisproduktu > div > h4 > a'); const urls = []; for (let i = 0; i < links.length; i++) { if (links[i].name === 'a' && links[i].attribs?.href) { const pizzaUrl = links[i].attribs?.href; urls.push(buildPizzaUrl(pizzaUrl)); } } // Scrapneme jednotlivé pizzy const result: Pizza[] = []; for (let i = 0; i < urls.length; i++) { const pizzaUrl = urls[i]; const pizzaHtml = await axios.get(pizzaUrl).then(res => res.data); // Název const name = $('.produkt > h2', pizzaHtml).first().text() // Přísady const ingredients: string[] = [] const ingredientsHtml = $('.prisady > li', pizzaHtml); ingredientsHtml.each((i, elm) => { ingredients.push($(elm).text()); }) // Velikosti const sizes: PizzaSize[] = []; const a = $('.varianty > li > a', pizzaHtml); a.each((i, elm) => { const varId = Number.parseInt(elm.attribs.href.split('?varianta=')[1].trim()); const size = $($(elm).contents().get(0)).text().trim(); const price = Number.parseInt($($(elm).contents().get(1)).text().trim().split(" Kč")[0]); sizes.push({ varId, size, pizzaPrice: price, boxPrice: boxPrices[size], price: price + boxPrices[size] }); }) result.push({ name: name, ingredients: ingredients, sizes: sizes, }); } return result; }