@@ -7,9 +7,82 @@
8-- Validate JSON values with Swagger Schema.
8-- Validate JSON values with Swagger Schema.
9module Data.Swagger.Schema.Validation (
9module Data.Swagger.Schema.Validation (
10+ -- * How to use validation
16+ -- ** Validating @'Maybe'@
10 validateToJSON,
20 validateToJSON,
11 validateToJSONWithPatternChecker,
21 validateToJSONWithPatternChecker,
12 ValidationError,
22 ValidationError,
15import Data.Swagger.Internal.Schema.Validation
25import Data.Swagger.Internal.Schema.Validation
28+-- >>> import Control.Lens
29+-- >>> import Data.Aeson
30+-- >>> import Data.Proxy
31+-- >>> import Data.Swagger
32+-- >>> import GHC.Generics
33+-- >>> :set -XDeriveGeneric
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.
42+-- It is recommended to use validation functions as QuickCheck properties
43+-- (see <http://hackage.haskell.org/package/QuickCheck>).
47+-- >>> validateToJSON "hello"
50+-- >>> validateToJSON False
53+-- >>> newtype Nat = Nat Integer deriving Generic
54+-- >>> instance ToJSON Nat where toJSON (Nat n) = toJSON n
56+-- instance ToSchema Nat where
57+-- declareNamedSchema _ = declareNamedSchema (Proxy :: Proxy Integer)
58+-- & mapped.minimum_ ?~ 0
61+-- >>> validateToJSON (Nat 10)
63+-- >>> validateToJSON (Nat (-5))
64+-- ["value -5.0 falls below minimum (should be >=0.0)"]
68+-- Because @'Maybe' a@ has the same schema as @a@, validation
69+-- generally fails for @null@ JSON:
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"]
78+-- However, when @'Maybe' a@ is a type of a record field,
79+-- validation takes @'required'@ property of the @'Schema'@
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))
87+-- >>> validateToJSON (Person "John" Nothing)