matabas/backend/ICAFocus.hs

52 lines
1.3 KiB
Haskell

{-# 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)
import Data.ByteString.Lazy
import Misc
newtype ImageLink = ImageLink { getLink :: String }
deriving (Show)
newtype ImageData = ImageData { getData :: ByteString }
type ProductID = Int32
instance Show ImageData where
show _ = "ImageData { ... }"
data ICAFocusItem a = ICAFocusItem
{ name :: Text
, costPerKg :: Float
, costPerUnit :: Float
, image :: a
}
deriving (Show, Functor)
type ICAFocusData = ICAFocusItem ImageLink
type ICAFocusProduct = ICAFocusItem ImageData
apiEndpoint :: ProductID -> String
apiEndpoint i = "https://handlaprivatkund.ica.se/stores/1004247/api/v4/products/bop?retailerProductId=" ++ show i
instance FromJSON ICAFocusData where
parseJSON (Object v) = do
productMap <- v .: "entities" .:: "product"
product <- case elems productMap of
[Object x] -> pure x
[] -> fail "No products"
_ -> fail "Too many products"
ICAFocusItem
<$> product .: "name"
<*> (unpackEither . readEither =<< product .: "price" .:: "current" .:: "amount")
<*> (unpackEither . readEither =<< product .: "price" .:: "unit" .:: "current" .:: "amount")
<*> (ImageLink <$> product .: "image" .:: "src")