@@ -11,7 +11,7 @@ module Servant.API.ContentTypesSpec where
11
11
import Prelude ()
12
12
import Prelude.Compat
13
13
14
- import Data.Aeson
14
+ import Data.Aeson.Compat
15
15
import Data.ByteString.Char8 (ByteString , append , pack )
16
16
import qualified Data.ByteString.Lazy as BSL
17
17
import qualified Data.ByteString.Lazy.Char8 as BSL8
@@ -24,9 +24,9 @@ import Data.Proxy
24
24
import Data.String (IsString (.. ))
25
25
import Data.String.Conversions (cs )
26
26
import qualified Data.Text as TextS
27
+ import qualified Data.Text.Encoding as TextSE
27
28
import qualified Data.Text.Lazy as TextL
28
29
import GHC.Generics
29
- import qualified Network.HTTP.Media as M
30
30
import Test.Hspec
31
31
import Test.QuickCheck
32
32
import Text.Read (readMaybe )
@@ -179,6 +179,15 @@ spec = describe "Servant.API.ContentTypes" $ do
179
179
handleCTypeH (Proxy :: Proxy '[JSONorText ]) " image/jpeg"
180
180
" 42" `shouldBe` (Nothing :: Maybe (Either String Int ))
181
181
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
+
182
191
#if MIN_VERSION_aeson(0,9,0)
183
192
-- aeson >= 0.9 decodes top-level strings
184
193
describe " eitherDecodeLenient" $ do
@@ -226,14 +235,19 @@ instance IsString AcceptHeader where
226
235
data JSONorText
227
236
228
237
instance Accept JSONorText where
229
- contentTypes _ = " text" M. // " plain" NE. :| [ " application" M. // " json" ]
238
+ contentTypes _ = " text/ plain" NE. :| [ " application/ json" ]
230
239
231
240
instance MimeRender JSONorText Int where
232
241
mimeRender _ = cs . show
233
242
234
243
instance MimeUnrender JSONorText Int where
235
244
mimeUnrender _ = maybe (Left " " ) Right . readMaybe . BSL8. unpack
236
245
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
+
237
251
addToAccept :: Accept a => Proxy a -> ZeroToOne -> AcceptHeader -> AcceptHeader
238
252
addToAccept p (ZeroToOne f) (AcceptHeader h) = AcceptHeader (cont h)
239
253
where new = cs (show $ contentType p) `append` " ; q=" `append` pack (show f)
0 commit comments