@@ -11,7 +11,7 @@ module Servant.API.ContentTypesSpec where
1111import Prelude ()
1212import Prelude.Compat
1313
14−import Data.Aeson
14+import Data.Aeson.Compat
1515import Data.ByteString.Char8 (ByteString, append, pack)
1616import qualified Data.ByteString.Lazy as BSL
1717import qualified Data.ByteString.Lazy.Char8 as BSL8
@@ -24,9 +24,9 @@ import Data.Proxy
2424import Data.String (IsString (..))
2525import Data.String.Conversions (cs)
2626import qualified Data.Text as TextS
27+import qualified Data.Text.Encoding as TextSE
2728import qualified Data.Text.Lazy as TextL
2829import GHC.Generics
29−import qualified Network.HTTP.Media as M
3030import Test.Hspec
3131import Test.QuickCheck
3232import Text.Read (readMaybe)
@@ -179,6 +179,15 @@ spec = describe "Servant.API.ContentTypes" $ do
179179 handleCTypeH (Proxy :: Proxy '[JSONorText]) "image/jpeg"
180180 "42" `shouldBe` (Nothing :: Maybe (Either String Int))
181181
182+ it "passes content-type to mimeUnrenderWithType" $ do
183+ let val = "foobar" :: TextS.Text
184+ handleCTypeH (Proxy :: Proxy '[JSONorText]) "application/json"
185+ "\"foobar\"" `shouldBe` Just (Right val)
186+ handleCTypeH (Proxy :: Proxy '[JSONorText]) "text/plain"
187+ "foobar" `shouldBe` Just (Right val)
188+ handleCTypeH (Proxy :: Proxy '[JSONorText]) "image/jpeg"
189+ "foobar" `shouldBe` (Nothing :: Maybe (Either String Int))
190+
182191#if MIN_VERSION_aeson(0,9,0)
183192 -- aeson >= 0.9 decodes top-level strings
184193 describe "eitherDecodeLenient" $ do
@@ -226,7 +235,7 @@ instance IsString AcceptHeader where
226235data JSONorText
227236
228237instance Accept JSONorText where
229− contentTypes _ = "text" M.// "plain" NE.:| [ "application" M.// "json" ]
238+ contentTypes _ = "text/plain" NE.:| [ "application/json" ]
230239
231240instance MimeRender JSONorText Int where
232241 mimeRender _ = cs . show
@@ -234,6 +243,11 @@ instance MimeRender JSONorText Int where
234243instance MimeUnrender JSONorText Int where
235244 mimeUnrender _ = maybe (Left "") Right . readMaybe . BSL8.unpack
236245
246+instance MimeUnrender JSONorText TextS.Text where
247+ mimeUnrenderWithType _ mt
248+ | mt == "application/json" = maybe (Left "") Right . decode
249+ | otherwise = Right . TextSE.decodeUtf8 . BSL.toStrict
250+
237251addToAccept :: Accept a => Proxy a -> ZeroToOne -> AcceptHeader -> AcceptHeader
238252addToAccept p (ZeroToOne f) (AcceptHeader h) = AcceptHeader (cont h)
239253 where new = cs (show $ contentType p) `append` "; q=" `append` pack (show f)