Bring parse call into common logic.
[haskell-cryptsy-api.git] / Cryptsy / API / Public / Order.hs
blob12894fe886e9fea37cd3b7ee101e2bff7526da96
1 module Cryptsy.API.Public.Order
2 ( GOrder(..), Order
3 , withComponents, withText
4 , module Cryptsy.API.Public
5 , module Data.Aeson.Types
6 -- |Re-exported from Data.Text
7 , Text
8 -- |Re-exported from Data.Aeson
9 , FromJSON(..), Value, Object
11 where
13 -- base
14 import Control.Applicative ((<$>), (<*>))
16 -- text
17 import Data.Text (Text, pack)
19 -- aeson
20 import qualified Data.Aeson as Aeson
21 import Data.Aeson (FromJSON(..), Value, Object, withObject, (.:))
22 import Data.Aeson.Types (Parser)
24 -- this package
25 import Cryptsy.API.Public (CryptsyNum(..))
27 data GOrder p q t = Order
28 { price :: p
29 , quantity :: q
30 , total :: t
31 } deriving Show
32 type Order = GOrder CryptsyNum CryptsyNum CryptsyNum
34 instance (FromJSON p, FromJSON q, FromJSON t) =>
35 FromJSON (GOrder p q t)
36 where
37 parseJSON = withObject "order"
38 $ withComponents parseJSON parseJSON parseJSON
40 -- Combine component parsers into JSON Object parser, for use with
41 -- 'Aeson.withObject'.
42 withComponents :: (Value -> Parser p) -- ^ price parser
43 -> (Value -> Parser q) -- ^ quantity parser
44 -> (Value -> Parser t) -- ^ total parser
45 -> Object -> Parser (GOrder p q t)
46 withComponents parsePrice parseQuantity parseTotal o =
47 Order <$>
48 (o .: pack "price" >>= parsePrice ) <*>
49 (o .: pack "quantity" >>= parseQuantity) <*>
50 (o .: pack "total" >>= parseTotal )
52 -- Special from of withComponents, since API delivers components as JSON
53 -- Strings.
54 withText :: (Text -> Parser p) -- ^ price parser
55 -> (Text -> Parser q) -- ^ quantity parser
56 -> (Text -> Parser t) -- ^ total parser
57 -> Object -> Parser (GOrder p q t)
58 withText parsePrice parseQuantity parseTotal = withComponents
59 (Aeson.withText "price" parsePrice )
60 (Aeson.withText "quantity" parseQuantity)
61 (Aeson.withText "total" parseTotal )