Ukládání pizz do DB místo dočasného souboru
This commit is contained in:
@@ -1,9 +1,5 @@
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
import axios from 'axios';
|
||||
import { load } from 'cheerio';
|
||||
import { formatDate } from './utils';
|
||||
|
||||
// TODO přesunout do types
|
||||
type PizzaSize = {
|
||||
@@ -40,7 +36,7 @@ const boxPrices: { [key: string]: number } = {
|
||||
/**
|
||||
* Stáhne a scrapne aktuální pizzy ze stránek Pizza Chefie.
|
||||
*/
|
||||
const downloadPizzy = async () => {
|
||||
export async function downloadPizzy(): Promise<Pizza[]> {
|
||||
// Získáme seznam pizz
|
||||
const html = await axios.get(pizzyUrl).then(res => res.data);
|
||||
const $ = load(html);
|
||||
@@ -81,26 +77,4 @@ const downloadPizzy = async () => {
|
||||
});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Vrátí pizzy z tempu, nebo čerstvě stažené, pokud v tempu nejsou.
|
||||
*/
|
||||
export const fetchPizzy = async (): Promise<Pizza[]> => {
|
||||
const tmpDir = os.tmpdir();
|
||||
const date_ob = new Date();
|
||||
const dateStr = formatDate(date_ob);
|
||||
const dataPath = path.join(tmpDir, `chefie-${dateStr}.json`);
|
||||
|
||||
if (fs.existsSync(dataPath)) {
|
||||
console.log(`Soubor pro ${dataPath} již existuje, bude použit.`);
|
||||
const rawdata = fs.readFileSync(dataPath);
|
||||
return JSON.parse(rawdata.toString());
|
||||
} else {
|
||||
console.log(`Soubor pro ${dataPath} neexistuje, stahuji...`);
|
||||
const pizzy = await downloadPizzy();
|
||||
fs.writeFileSync(dataPath, JSON.stringify(pizzy));
|
||||
console.log(`Zapsán ${dataPath}`);
|
||||
return pizzy;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user