module Data.Parser.Expires
  ( parseExpirationTime,
  )
where

import Control.Monad.Except
import Data.Text.Conversions
import Data.Time.Clock
import Data.Time.Format (defaultTimeLocale, parseTimeM)
import Hasura.Prelude

-- | Extracts an absolute expiration time from a Expires header.
parseExpirationTime :: MonadError String m => Text -> m UTCTime
parseExpirationTime :: Text -> m UTCTime
parseExpirationTime =
  Text -> String
forall a. FromText a => Text -> a
fromText
    (Text -> String) -> (String -> m UTCTime) -> Text -> m UTCTime
forall k (cat :: k -> k -> *) (a :: k) (b :: k) (c :: k).
Category cat =>
cat a b -> cat b c -> cat a c
>>> Bool -> TimeLocale -> String -> String -> Maybe UTCTime
forall (m :: * -> *) t.
(MonadFail m, ParseTime t) =>
Bool -> TimeLocale -> String -> String -> m t
parseTimeM Bool
True TimeLocale
defaultTimeLocale String
"%a, %d %b %Y %T GMT"
    (String -> Maybe UTCTime)
-> (Maybe UTCTime -> m UTCTime) -> String -> m UTCTime
forall k (cat :: k -> k -> *) (a :: k) (b :: k) (c :: k).
Category cat =>
cat a b -> cat b c -> cat a c
>>> (Maybe UTCTime -> m UTCTime -> m UTCTime
forall (m :: * -> *) a. Applicative m => Maybe a -> m a -> m a
`onNothing` String -> m UTCTime
forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError String
"Value of Expires header is not a valid timestamp")