matabas/backend/ICAFocus.hs

52 lines
1.3 KiB
Haskell
Raw Normal View History

2023-08-10 00:55:07 +02:00
{-# LANGUAGE OverloadedStrings #-}
module ICAFocus where
import Data.Aeson
import Data.Aeson.Types
import Data.Aeson.KeyMap
import Data.Text
import Text.Read
import Data.Int (Int32)
2023-08-10 00:55:07 +02:00
import Data.ByteString.Lazy
import Misc
2023-08-10 00:55:07 +02:00
newtype ImageLink = ImageLink { getLink :: String }
deriving (Show)
newtype ImageData = ImageData { getData :: ByteString }
type ProductID = Int32
2023-08-10 00:55:07 +02:00
instance Show ImageData where
show _ = "ImageData { ... }"
data ICAFocusItem a = ICAFocusItem
{ name :: Text
, costPerKg :: Float
, costPerUnit :: Float
2023-08-10 00:55:07 +02:00
, image :: a
}
deriving (Show, Functor)
type ICAFocusData = ICAFocusItem ImageLink
type ICAFocusProduct = ICAFocusItem ImageData
apiEndpoint :: ProductID -> String
2023-08-10 01:56:19 +02:00
apiEndpoint i = "https://handlaprivatkund.ica.se/stores/1004247/api/v4/products/bop?retailerProductId=" ++ show i
2023-08-10 00:55:07 +02:00
instance FromJSON ICAFocusData where
parseJSON (Object v) = do
2023-08-10 01:56:19 +02:00
productMap <- v .: "entities" .:: "product"
2023-08-10 00:55:07 +02:00
product <- case elems productMap of
[Object x] -> pure x
[] -> fail "No products"
_ -> fail "Too many products"
2023-08-10 01:56:19 +02:00
ICAFocusItem
<$> product .: "name"
<*> (unpackEither . readEither =<< product .: "price" .:: "current" .:: "amount")
<*> (unpackEither . readEither =<< product .: "price" .:: "unit" .:: "current" .:: "amount")
<*> (ImageLink <$> product .: "image" .:: "src")
2023-08-10 00:55:07 +02:00