@@ -7,9 +7,82 @@
77--
88-- Validate JSON values with Swagger Schema.
99module Data.Swagger.Schema.Validation (
10+ -- * How to use validation
11+ -- $howto
12+
13+ -- ** Examples
14+ -- $examples
15+
16+ -- ** Validating @'Maybe'@
17+ -- $maybe
18+
19+ -- * JSON validation
1020 validateToJSON,
1121 validateToJSONWithPatternChecker,
1222 ValidationError,
1323) where
1424
1525import Data.Swagger.Internal.Schema.Validation
26+
27+-- $setup
28+-- >>> import Control.Lens
29+-- >>> import Data.Aeson
30+-- >>> import Data.Proxy
31+-- >>> import Data.Swagger
32+-- >>> import GHC.Generics
33+-- >>> :set -XDeriveGeneric
34+
35+-- $howto
36+--
37+-- This module provides helpful functions for JSON validation.
38+-- These functions are meant to be used in test suites for your application
39+-- to ensure that JSON respresentation for your data corresponds to
40+-- schemas you're using for the Swagger specification.
41+--
42+-- It is recommended to use validation functions as QuickCheck properties
43+-- (see <http://hackage.haskell.org/package/QuickCheck>).
44+
45+-- $examples
46+--
47+-- >>> validateToJSON "hello"
48+-- []
49+--
50+-- >>> validateToJSON False
51+-- []
52+--
53+-- >>> newtype Nat = Nat Integer deriving Generic
54+-- >>> instance ToJSON Nat where toJSON (Nat n) = toJSON n
55+-- >>> :{
56+-- instance ToSchema Nat where
57+-- declareNamedSchema _ = declareNamedSchema (Proxy :: Proxy Integer)
58+-- & mapped.minimum_ ?~ 0
59+-- :}
60+--
61+-- >>> validateToJSON (Nat 10)
62+-- []
63+-- >>> validateToJSON (Nat (-5))
64+-- ["value -5.0 falls below minimum (should be >=0.0)"]
65+
66+-- $maybe
67+--
68+-- Because @'Maybe' a@ has the same schema as @a@, validation
69+-- generally fails for @null@ JSON:
70+--
71+-- >>> validateToJSON (Nothing :: Maybe String)
72+-- ["expected JSON value of type SwaggerString"]
73+-- >>> validateToJSON ([Just "hello", Nothing] :: [Maybe String])
74+-- ["expected JSON value of type SwaggerString"]
75+-- >>> validateToJSON (123, Nothing :: Maybe String)
76+-- ["expected JSON value of type SwaggerString"]
77+--
78+-- However, when @'Maybe' a@ is a type of a record field,
79+-- validation takes @'required'@ property of the @'Schema'@
80+-- into account:
81+--
82+-- >>> data Person = Person { name :: String, age :: Maybe Int } deriving Generic
83+-- >>> instance ToJSON Person
84+-- >>> instance ToSchema Person
85+-- >>> validateToJSON (Person "John" (Just 25))
86+-- []
87+-- >>> validateToJSON (Person "John" Nothing)
88+-- []