summaryrefslogtreecommitdiff
path: root/src/cron.ts
blob: fb016a3eff13a192d542840c70656ba8b039c3aa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import { fetchColesProduct, fetchWooliesProduct, ProductInfo } from "./gather"
import { storePriceRecord } from "./store"

export interface ProductRequest {
    productId: string,
    companyName: string
}

export async function cacheAllPrices(db: D1Database, products: ProductRequest[]): Promise<boolean> {
    // return getAllPrices(products).then().map(storePriceRecord)
    return (await getAllPrices(products))
        .map(x => {console.log("getting prices", x); return x})
        .filter(x => x != null)
        .map(product => storePriceRecord(db, product as ProductInfo))
        .every(async x => await x === true)

    // for (let p of products) {
    //     console.log(p)
    //     const prices = await getPrice(p)
        // console.warn(prices)
    // }

    // let out = []
    // for (let price of prices) {
    //     if (price !== null) {
    //         const result = await storePriceRecord(db, price)
    //         console.log(price, result)
    //         out.push(result)
    //     }
    // }
    // return out.every(x => !!x)
    // return true


}

async function getAllPrices(products: ProductRequest[]): Promise<(ProductInfo | null)[]> {
    return await Promise.all(products.map(getPrice))
    // let out = []
    // for (let p of products) {
    //     out.push(await getPrice(p))
    // }
    // return out
    // return [await getPrice(products[0])]
}

async function getPrice(product: ProductRequest): Promise<ProductInfo | null> {
    switch (product.companyName) {
        case "Coles":
            return await fetchColesProduct(product.productId)
        case "Woolies":
            return await fetchWooliesProduct(product.productId)
        default:
            throw Error("Invalid store name")
    }
}