git.iko.soy/typeable/http-api-data
on master help sign in
Add To/FromHttpApiData instances for time types
commitbbac6426c91098f09e4746e1e2ce694543948ef9 authorNickolay Kudasov <nickolay.kudasov@gmail.com> dateTue 8 Dec 2015, 15:58 (11 years ago) parent56e3b9d
1 file changed+42
Web/HttpApiData/Internal.hs+42
Web/HttpApiData/Internal.hs+42
@@ -364,6 +364,26 @@ instance ToHttpApiData Word64 where toUrlPiece = showt
364364-- "2015-10-03"
365365instance ToHttpApiData Day where toUrlPiece = T.pack . show
366366
367+timeToUrlPiece :: FormatTime t => String -> t -> Text
368+timeToUrlPiece fmt = T.pack . formatTime defaultTimeLocale (iso8601DateFormat (Just fmt))
369+
370+-- |
371+-- >>> toUrlPiece $ LocalTime (fromGregorian 2015 10 03) (TimeOfDay 14 55 01)
372+-- "2015-10-03T14:55:01"
373+instance ToHttpApiData LocalTime where toUrlPiece = timeToUrlPiece "%H:%M:%S"
374+
375+-- |
376+-- >>> toUrlPiece $ ZonedTime (LocalTime (fromGregorian 2015 10 03) (TimeOfDay 14 55 01)) utc
377+-- "2015-10-03T14:55:01+0000"
378+instance ToHttpApiData ZonedTime where toUrlPiece = timeToUrlPiece "%H:%M:%S%z"
379+
380+-- |
381+-- >>> toUrlPiece $ UTCTime (fromGregorian 2015 10 03) 864
382+-- "2015-10-03T00:14:24Z"
383+instance ToHttpApiData UTCTime where toUrlPiece = timeToUrlPiece "%H:%M:%SZ"
384+
385+instance ToHttpApiData NominalDiffTime where toUrlPiece = toUrlPiece . fromEnum
386+
367387instance ToHttpApiData String where toUrlPiece = T.pack
368388instance ToHttpApiData Text where toUrlPiece = id
369389instance ToHttpApiData L.Text where toUrlPiece = L.toStrict
@@ -445,6 +465,28 @@ instance FromHttpApiData L.Text where parseUrlPiece = Right . L.fromStrict
445465-- Right (2016,12,1)
446466instance FromHttpApiData Day where parseUrlPiece = readTextData
447467
468+timeParseUrlPiece :: ParseTime t => String -> Text -> Either Text t
469+timeParseUrlPiece fmt = parseMaybeTextData (timeParseUrlPieceMaybe . T.unpack)
470+ where
471+ timeParseUrlPieceMaybe = parseTimeM False defaultTimeLocale (iso8601DateFormat (Just fmt))
472+
473+-- |
474+-- >>> parseUrlPiece "2015-10-03T14:55:01" :: Either Text LocalTime
475+-- Right 2015-10-03 14:55:01
476+instance FromHttpApiData LocalTime where parseUrlPiece = timeParseUrlPiece "%H:%M:%S"
477+
478+-- |
479+-- >>> parseUrlPiece "2015-10-03T14:55:01+0000" :: Either Text ZonedTime
480+-- Right 2015-10-03 14:55:01 +0000
481+instance FromHttpApiData ZonedTime where parseUrlPiece = timeParseUrlPiece "%H:%M:%S%z"
482+
483+-- |
484+-- >>> parseUrlPiece "2015-10-03T00:14:24Z" :: Either Text UTCTime
485+-- Right 2015-10-03 00:14:24 UTC
486+instance FromHttpApiData UTCTime where parseUrlPiece = timeParseUrlPiece "%H:%M:%SZ"
487+
488+instance FromHttpApiData NominalDiffTime where parseUrlPiece = fmap fromInteger . parseUrlPiece
489+
448490instance FromHttpApiData All where parseUrlPiece = fmap All . parseUrlPiece
449491instance FromHttpApiData Any where parseUrlPiece = fmap Any . parseUrlPiece
450492