1{-# LANGUAGE OverloadedStrings #-}
6import Data.HashMap.Strict (HashMap)
7import qualified Data.HashMap.Strict as H
10import qualified Data.Text as T
11import qualified Data.Vector as V
13import qualified Data.JsonSchema as JS
15-- Data.JsonSchema isn't designed to be imported qualified,
16-- but we're doing it here to make it obvious what's coming
19schemaData :: JS.RawSchema
20schemaData = JS.RawSchema
22 , JS._rsObject = schemaJSON
25 schemaJSON :: HashMap Text Value
26 schemaJSON = H.singleton "uniqueItems" (Bool True)
29badData = Array $ V.fromList ["foo", "foo"]
34 let currentSchemaCache = H.empty
35 newSchemaCache <- (<> currentSchemaCache) <$> fetchGraph schemaData
37 schema <- compileSchema newSchemaCache schemaData
38 checkResults (JS.validate schema badData)
42 -- Not necessary in this case, but it serves as an example.
44 -- Note that Graphs are used to handle internal as well as external references.
45 -- So even if a schema doesn't reference outside documents, you still need
46 -- to generate a real Graph (and not just use mempty) if it refences itself.
47 fetchGraph :: JS.RawSchema -> IO JS.Graph
49 eitherGraph <- JS.fetchReferencedSchemas JS.draft4 rs H.empty
51 Left e -> error $ "Failed to fetch graph with error: " <> T.unpack e
52 Right graph -> return graph
54 compileSchema :: JS.Graph -> JS.RawSchema -> IO (JS.Schema JS.Draft4Failure)
55 compileSchema graph rs =
56 case JS.compileDraft4 graph rs of
57 Left failure -> error $ "Not a valid schema: " <> show failure
58 Right schema -> return schema
60 checkResults :: [JS.ValidationFailure JS.Draft4Failure] -> IO ()
61 checkResults [] = error "OHNO we validated bad data!"
62 checkResults [JS.ValidationFailure JS.UniqueItems (JS.FailureInfo x y)] =
65 , "Success. We got a UniqueItems error as expected."
66 , "Here's the relevant part of the bad JSON document:"
70 , "And here's the content of the validator that caught it:"
74 checkResults x = error $ "OHNO we got a different failure than we expected: " <> show x
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list