Bring parse call into common logic.
[haskell-cryptsy-api.git] / Cryptsy / API / Public / Trade.hs
blobce6773a2c5a1fc9bee0304cd2f781de62e5e58d6
1 module Cryptsy.API.Public.Trade
2 ( GTrade(..), Trade
3 , withComponents, withText
4 , module Cryptsy.API.Public
5 -- |Re-exported from Data.Text
6 , Text
7 -- |Re-exported from Data.Aeson
8 , Value, Object, FromJSON(..)
9 -- |Re-exported from Data.Aeson.Types
10 , Parser
12 where
14 -- base
15 import Control.Applicative ((<$>), (<*>))
17 -- text
18 import Data.Text (Text, pack)
20 -- aeson
21 import qualified Data.Aeson as Aeson
22 import Data.Aeson
23 ( FromJSON(..), Value, Object, withObject, (.:)
25 import Data.Aeson.Types (Parser)
27 -- this package
28 import Cryptsy.API.Public (CryptsyNum(..))
30 data GTrade dt p q t = Trade
31 { id :: Text
32 , time :: dt
33 , price :: p
34 , quantity :: q
35 , total :: t
36 } deriving Show
37 type Trade = GTrade Text CryptsyNum CryptsyNum CryptsyNum
39 instance (FromJSON dt, FromJSON p, FromJSON q, FromJSON t) =>
40 FromJSON (GTrade dt p q t)
41 where
42 parseJSON = withObject "trade"
43 $ withComponents parseJSON parseJSON parseJSON parseJSON
45 -- |Combine component parsers into JSON Object parser, for use with
46 -- |'Aeson.withObject'.
47 withComponents :: (Value -> Parser dt) -- ^ date/time parser
48 -> (Value -> Parser p) -- ^ price parser
49 -> (Value -> Parser q) -- ^ quantity parser
50 -> (Value -> Parser t) -- ^ total parser
51 -> Object -> Parser (GTrade dt p q t)
52 withComponents parseDatetime parsePrice parseQuantity parseTotal o =
53 Trade <$>
54 o .: pack "id" <*>
55 (o .: pack "time" >>= parseDatetime) <*>
56 (o .: pack "price" >>= parsePrice ) <*>
57 (o .: pack "quantity" >>= parseQuantity) <*>
58 (o .: pack "total" >>= parseTotal )
60 -- |Special from of 'withComponents', since API delivers components as JSON
61 -- |Strings.
62 withText :: (Text -> Parser dt) -- ^ date/time parser
63 -> (Text -> Parser p) -- ^ price parser
64 -> (Text -> Parser q) -- ^ quantity parser
65 -> (Text -> Parser t) -- ^ total parser
66 -> Object -> Parser (GTrade dt p q t)
67 withText parseDatetime parsePrice parseQuantity parseTotal =
68 withComponents
69 (Aeson.withText "time" parseDatetime)
70 (Aeson.withText "price" parsePrice )
71 (Aeson.withText "quantity" parseQuantity)
72 (Aeson.withText "total" parseTotal )