Skip to content

Commit

Permalink
Add JSONResponse type
Browse files Browse the repository at this point in the history
Closes #1481
  • Loading branch information
MaxGabriel committed Mar 12, 2018
1 parent ff5618b commit ba2593c
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 1 deletion.
4 changes: 4 additions & 0 deletions yesod-core/ChangeLog.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
## 1.6.3

* Add a type `JSONResponse a` that can be used to type a Handler as returning some value `a`, which should be encoded as JSON. [#1481](https://github.com/yesodweb/yesod/issues/1481)

## 1.6.2

* Derive a `Show` instance for `ResourceTree` and `FlatResource` [#1492](https://github.com/yesodweb/yesod/pull/1492)
Expand Down
8 changes: 8 additions & 0 deletions yesod-core/Yesod/Core/Content.hs
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,12 @@ instance HasContentType J.Value where
instance HasContentType J.Encoding where
getContentType _ = typeJson

instance ToContent (JSONResponse a) where
toContent (JSONResponse a) = toContent $ toEncoding a

instance HasContentType (JSONResponse a) where
getContentType _ = typeJson

instance HasContentType Html where
getContentType _ = typeHtml

Expand Down Expand Up @@ -288,6 +294,8 @@ instance ToTypedContent J.Value where
toTypedContent v = TypedContent typeJson (toContent v)
instance ToTypedContent J.Encoding where
toTypedContent e = TypedContent typeJson (toContent e)
instance ToTypedContent (JSONResponse a) where
toTypedContent c = TypedContent typeJson (toContent c)
instance ToTypedContent Html where
toTypedContent h = TypedContent typeHtml (toContent h)
instance ToTypedContent T.Text where
Expand Down
12 changes: 12 additions & 0 deletions yesod-core/Yesod/Core/Types.hs
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,18 @@ newtype RepXml = RepXml Content

type ContentType = ByteString -- FIXME Text?

-- | Wrapper around types so that Handlers can be typed them, encoded as JSON.
-- Example usage in a type signature:
--
-- > postSignupR :: Handler (JSONResponse CreateUserResponse)
--
-- And in the implementation:
--
-- > return $ JSONResponse $ CreateUserResponse userId
--
-- @since 1.6.3
data JSONResponse a = ToJSON a => JSONResponse a

-- | Prevents a response body from being fully evaluated before sending the
-- request.
--
Expand Down
2 changes: 1 addition & 1 deletion yesod-core/yesod-core.cabal
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
name: yesod-core
version: 1.6.2
version: 1.6.3
license: MIT
license-file: LICENSE
author: Michael Snoyman <michael@snoyman.com>
Expand Down

0 comments on commit ba2593c

Please sign in to comment.