yesodweb/yesod — Issue #219: Enhancement: add jsonOrRedirect to yesod-json
Author: chreekat
Created: 2012-01-12 20:21:26+00:00
State: open

```haskell

-- | jsonOrRedirect simplifies the scenario where a POST handler sends a different
-- response based on Accept headers:
--
-- a) 200 with JSON data if the client prefers application/json (i.e. is an
-- AJAX request)
--
-- b) 3xx otherwise, following the PRG pattern.
jsonOrRedirect :: (Yesod master, J.ToJSON a)
=> Route master -> a -> GHandler sub master RepJson
jsonOrRedirect r j = do
q <- acceptsJson
if q then jsonToRepJson (J.toJSON j)
else redirect RedirectTemporary r
where
acceptsJson = maybe False (=="application/json") <$> firstAccept
firstAccept = return . join
. fmap (headMay . parseHttpAccept)
=<< lookup "Accept" . W.requestHeaders <$> waiRequest
```