git.iko.soy/typeable/swagger2
on master help sign in
.ghcinew file+2
since splitsnapshots
unifiedsplit
@@ -0,0 +1,2 @@
1+:set -itest -isrc -optP-include -optP.stack-work/dist/x86_64-linux/Cabal-1.24.2.0/build/autogen/cabal_macros.h -optP-I -optPinclude
2+:set -hide-package base-compat-0.10.4
.gitignore+2
@@ -1,4 +1,6 @@
1dist
1dist
2+dist-newstyle
3+.ghc.environment.*
2cabal-dev
4cabal-dev
3*.o
5*.o
4*.hi
6*.hi
.travis.yml+150−67
@@ -1,79 +1,162 @@
1−# This file has been generated -- see https://github.com/hvr/multi-ghc-travis
1+# This Travis job script has been generated by a script via
2+#
3+# haskell-ci '--branches' 'master' '--haddock-jobs=>=8.4' '--output' '.travis.yml' 'swagger2.cabal'
4+#
5+# For more information, see https://github.com/haskell-CI/haskell-ci
6+#
7+# version: 0.5.20191020
8+#
2language: c
9language: c
10+dist: xenial
11+git:
12+ # whether to recursively clone submodules
3−sudo: false
13+ submodules: false
4−
14+branches:
15+ only:
16+ - master
5cache:
17cache:
6 directories:
18 directories:
7− - $HOME/.cabsnap
8 - $HOME/.cabal/packages
19 - $HOME/.cabal/packages
9−
20+ - $HOME/.cabal/store
10before_cache:
21before_cache:
11− - rm -fv $HOME/.cabal/packages/hackage.haskell.org/build-reports.log
22+ - rm -fv $CABALHOME/packages/hackage.haskell.org/build-reports.log
23+ # remove files that are regenerated by 'cabal update'
12− - rm -fv $HOME/.cabal/packages/hackage.haskell.org/00-index.tar
24+ - rm -fv $CABALHOME/packages/hackage.haskell.org/00-index.*
13−
25+ - rm -fv $CABALHOME/packages/hackage.haskell.org/*.json
26+ - rm -fv $CABALHOME/packages/hackage.haskell.org/01-index.cache
27+ - rm -fv $CABALHOME/packages/hackage.haskell.org/01-index.tar
28+ - rm -fv $CABALHOME/packages/hackage.haskell.org/01-index.tar.idx
29+ - rm -rfv $CABALHOME/packages/head.hackage
14matrix:
30matrix:
15 include:
31 include:
16− - env: CABALVER=1.18 GHCVER=7.8.4
32+ - compiler: ghc-8.8.1
17− compiler: ": #GHC 7.8.4"
33+ addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-8.8.1","cabal-install-3.0"]}}
34+ - compiler: ghc-8.6.5
18− addons: {apt: {packages: [cabal-install-1.18,ghc-7.8.4,happy-1.19.5], sources: [hvr-ghc]}}
35+ addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-8.6.5","cabal-install-3.0"]}}
19− - env: CABALVER=1.22 GHCVER=7.10.3
36+ - compiler: ghc-8.4.4
20− compiler: ": #GHC 7.10.3"
37+ addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-8.4.4","cabal-install-3.0"]}}
21− addons: {apt: {packages: [cabal-install-1.22,ghc-7.10.3,happy-1.19.5], sources: [hvr-ghc]}}
38+ - compiler: ghc-8.2.2
22−
39+ addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-8.2.2","cabal-install-3.0"]}}
40+ - compiler: ghc-8.0.2
41+ addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-8.0.2","cabal-install-3.0"]}}
23before_install:
42before_install:
43+ - HC=$(echo "/opt/$CC/bin/ghc" | sed 's/-/\//')
44+ - WITHCOMPILER="-w $HC"
45+ - HADDOCK=$(echo "/opt/$CC/bin/haddock" | sed 's/-/\//')
46+ - HCPKG="$HC-pkg"
24− - unset CC
47+ - unset CC
25− - export PATH=/opt/ghc/$GHCVER/bin:/opt/cabal/$CABALVER/bin:/opt/happy/1.19.5/bin:$PATH
48+ - CABAL=/opt/ghc/bin/cabal
26−
49+ - CABALHOME=$HOME/.cabal
50+ - export PATH="$CABALHOME/bin:$PATH"
51+ - TOP=$(pwd)
52+ - "HCNUMVER=$(${HC} --numeric-version|perl -ne '/^(\\d+)\\.(\\d+)\\.(\\d+)(\\.(\\d+))?$/; print(10000 * $1 + 100 * $2 + ($3 == 0 ? $5 != 1 : $3))')"
53+ - echo $HCNUMVER
54+ - CABAL="$CABAL -vnormal+nowrap+markoutput"
55+ - set -o pipefail
56+ - |
57+ echo 'function blue(s) { printf "\033[0;34m" s "\033[0m " }' >> .colorful.awk
58+ echo 'BEGIN { state = "output"; }' >> .colorful.awk
59+ echo '/^-----BEGIN CABAL OUTPUT-----$/ { state = "cabal" }' >> .colorful.awk
60+ echo '/^-----END CABAL OUTPUT-----$/ { state = "output" }' >> .colorful.awk
61+ echo '!/^(-----BEGIN CABAL OUTPUT-----|-----END CABAL OUTPUT-----)/ {' >> .colorful.awk
62+ echo ' if (state == "cabal") {' >> .colorful.awk
63+ echo ' print blue($0)' >> .colorful.awk
64+ echo ' } else {' >> .colorful.awk
65+ echo ' print $0' >> .colorful.awk
66+ echo ' }' >> .colorful.awk
67+ echo '}' >> .colorful.awk
68+ - cat .colorful.awk
69+ - |
70+ color_cabal_output () {
71+ awk -f $TOP/.colorful.awk
72+ }
73+ - echo text | color_cabal_output
27install:
74install:
28− - cabal --version
75+ - ${CABAL} --version
29− - echo "$(ghc --version) [$(ghc --print-project-git-commit-id 2> /dev/null || echo '?')]"
76+ - echo "$(${HC} --version) [$(${HC} --print-project-git-commit-id 2> /dev/null || echo '?')]"
30− - if [ -f $HOME/.cabal/packages/hackage.haskell.org/00-index.tar.gz ];
77+ - TEST=--enable-tests
31− then
78+ - BENCH=--enable-benchmarks
32− zcat $HOME/.cabal/packages/hackage.haskell.org/00-index.tar.gz >
79+ - HEADHACKAGE=false
33− $HOME/.cabal/packages/hackage.haskell.org/00-index.tar;
80+ - rm -f $CABALHOME/config
34− fi
81+ - |
82+ echo "verbose: normal +nowrap +markoutput" >> $CABALHOME/config
83+ echo "remote-build-reporting: anonymous" >> $CABALHOME/config
84+ echo "write-ghc-environment-files: always" >> $CABALHOME/config
85+ echo "remote-repo-cache: $CABALHOME/packages" >> $CABALHOME/config
86+ echo "logs-dir: $CABALHOME/logs" >> $CABALHOME/config
87+ echo "world-file: $CABALHOME/world" >> $CABALHOME/config
88+ echo "extra-prog-path: $CABALHOME/bin" >> $CABALHOME/config
89+ echo "symlink-bindir: $CABALHOME/bin" >> $CABALHOME/config
90+ echo "installdir: $CABALHOME/bin" >> $CABALHOME/config
91+ echo "build-summary: $CABALHOME/logs/build.log" >> $CABALHOME/config
92+ echo "store-dir: $CABALHOME/store" >> $CABALHOME/config
93+ echo "install-dirs user" >> $CABALHOME/config
94+ echo " prefix: $CABALHOME" >> $CABALHOME/config
95+ echo "repository hackage.haskell.org" >> $CABALHOME/config
96+ echo " url: http://hackage.haskell.org/" >> $CABALHOME/config
97+ echo " secure: True" >> $CABALHOME/config
98+ echo " key-threshold: 3" >> $CABALHOME/config
99+ echo " root-keys:" >> $CABALHOME/config
100+ echo " fe331502606802feac15e514d9b9ea83fee8b6ffef71335479a2e68d84adc6b0" >> $CABALHOME/config
101+ echo " 1ea9ba32c526d1cc91ab5e5bd364ec5e9e8cb67179a471872f6e26f0ae773d42" >> $CABALHOME/config
102+ echo " 2c6c3627bd6c982990239487f1abd02e08a02e6cf16edb105a8012d444d870c3" >> $CABALHOME/config
103+ echo " 0a5c7ea47cd1b15f01f5f51a33adda7e655bc0f0b0615baa8e271f4c3351e21d" >> $CABALHOME/config
104+ echo " 51f0161b906011b52c6613376b1ae937670da69322113a246a09f807c62f6921" >> $CABALHOME/config
105+ - |
106+ echo "program-default-options" >> $CABALHOME/config
107+ echo " ghc-options: $GHCJOBS +RTS -M6G -RTS" >> $CABALHOME/config
108+ - cat $CABALHOME/config
109+ - rm -fv cabal.project cabal.project.local cabal.project.freeze
35− - travis_retry cabal update -v
110+ - travis_retry ${CABAL} v2-update -v
36− - sed -i 's/^jobs:/-- jobs:/' ${HOME}/.cabal/config
111+ # Generate cabal.project
37− - cabal install --only-dependencies --enable-tests --enable-benchmarks --dry -v > installplan.txt
112+ - rm -rf cabal.project cabal.project.local cabal.project.freeze
38− - sed -i -e '1,/^Resolving /d' installplan.txt; cat installplan.txt
113+ - touch cabal.project
39−
114+ - |
40−# check whether current requested install-plan matches cached package-db snapshot
115+ echo "packages: ." >> cabal.project
41− - if diff -u installplan.txt $HOME/.cabsnap/installplan.txt;
116+ - |
42− then
117+ - "for pkg in $($HCPKG list --simple-output); do echo $pkg | sed 's/-[^-]*$//' | (grep -vE -- '^(swagger2)$' || true) | sed 's/^/constraints: /' | sed 's/$/ installed/' >> cabal.project.local; done"
43− echo "cabal build-cache HIT";
118+ - cat cabal.project || true
44− rm -rfv .ghc;
119+ - cat cabal.project.local || true
45− cp -a $HOME/.cabsnap/ghc $HOME/.ghc;
120+ - if [ -f "./configure.ac" ]; then (cd "." && autoreconf -i); fi
46− cp -a $HOME/.cabsnap/lib $HOME/.cabsnap/share $HOME/.cabsnap/bin $HOME/.cabal/;
121+ - ${CABAL} v2-freeze $WITHCOMPILER ${TEST} ${BENCH} | color_cabal_output
47− else
122+ - "cat cabal.project.freeze | sed -E 's/^(constraints: *| *)//' | sed 's/any.//'"
48− echo "cabal build-cache MISS";
123+ - rm cabal.project.freeze
49− rm -rf $HOME/.cabsnap;
124+ - ${CABAL} v2-build $WITHCOMPILER ${TEST} ${BENCH} --dep -j2 all | color_cabal_output
50− mkdir -p $HOME/.ghc $HOME/.cabal/lib $HOME/.cabal/share $HOME/.cabal/bin;
125+ - ${CABAL} v2-build $WITHCOMPILER --disable-tests --disable-benchmarks --dep -j2 all | color_cabal_output
51− cabal install --only-dependencies --enable-tests --enable-benchmarks;
52− fi
53−
54−# snapshot package-db on cache miss
55− - if [ ! -d $HOME/.cabsnap ];
56− then
57− echo "snapshotting package-db to build-cache";
58− mkdir $HOME/.cabsnap;
59− cp -a $HOME/.ghc $HOME/.cabsnap/ghc;
60− cp -a $HOME/.cabal/lib $HOME/.cabal/share $HOME/.cabal/bin installplan.txt $HOME/.cabsnap/;
61− fi
62−
63−# Here starts the actual work to be performed for the package under test;
64−# any command which exits with a non-zero exit code causes the build to fail.
65script:
126script:
66− - if [ -f configure.ac ]; then autoreconf -i; fi
127+ - DISTDIR=$(mktemp -d /tmp/dist-test.XXXX)
67− - cabal configure --enable-tests --enable-benchmarks -v2 # -v2 provides useful information for debugging
128+ # Packaging...
129+ - ${CABAL} v2-sdist all | color_cabal_output
130+ # Unpacking...
131+ - mv dist-newstyle/sdist/*.tar.gz ${DISTDIR}/
132+ - cd ${DISTDIR} || false
133+ - find . -maxdepth 1 -type f -name '*.tar.gz' -exec tar -xvf '{}' \;
134+ - find . -maxdepth 1 -type f -name '*.tar.gz' -exec rm '{}' \;
135+ - PKGDIR_swagger2="$(find . -maxdepth 1 -type d -regex '.*/swagger2-[0-9.]*')"
136+ # Generate cabal.project
137+ - rm -rf cabal.project cabal.project.local cabal.project.freeze
138+ - touch cabal.project
139+ - |
140+ echo "packages: ${PKGDIR_swagger2}" >> cabal.project
141+ - |
142+ - "for pkg in $($HCPKG list --simple-output); do echo $pkg | sed 's/-[^-]*$//' | (grep -vE -- '^(swagger2)$' || true) | sed 's/^/constraints: /' | sed 's/$/ installed/' >> cabal.project.local; done"
143+ - cat cabal.project || true
144+ - cat cabal.project.local || true
145+ # Building...
68− - cabal build # this builds all libraries and executables (including tests/benchmarks)
146+ # this builds all libraries and executables (without tests/benchmarks)
69− - cabal test
147+ - ${CABAL} v2-build $WITHCOMPILER --disable-tests --disable-benchmarks all | color_cabal_output
70− - cabal check
148+ # Building with tests and benchmarks...
71− - cabal sdist # tests that a source-distribution can be generated
149+ # build & run tests, build benchmarks
72−
150+ - ${CABAL} v2-build $WITHCOMPILER ${TEST} ${BENCH} all | color_cabal_output
73−# Check that the resulting source distribution can be built & installed.
151+ # Testing...
74−# If there are no other `.tar.gz` files in `dist`, this can be even simpler:
152+ - ${CABAL} v2-test $WITHCOMPILER ${TEST} ${BENCH} all | color_cabal_output
75−# `cabal install --force-reinstalls dist/*-*.tar.gz`
153+ # cabal check...
76− - SRC_TGZ=$(cabal info . | awk '{print $2;exit}').tar.gz &&
154+ - (cd ${PKGDIR_swagger2} && ${CABAL} -vnormal check)
77− (cd dist && cabal install --force-reinstalls "$SRC_TGZ")
155+ # haddock...
156+ - if [ $HCNUMVER -ge 80400 ] ; then ${CABAL} v2-haddock $WITHCOMPILER --with-haddock $HADDOCK ${TEST} ${BENCH} all | color_cabal_output ; fi
157+ # Building without installed constraints for packages in global-db...
158+ - rm -f cabal.project.local
159+ - ${CABAL} v2-build $WITHCOMPILER --disable-tests --disable-benchmarks all | color_cabal_output
78
160
161+# REGENDATA ("0.5.20191020",["--branches","master","--haddock-jobs=>=8.4","--output",".travis.yml","swagger2.cabal"])
79# EOF
162# EOF
CHANGELOG.md+186−1
@@ -1,7 +1,192 @@
1+2.5
2+---
3+
4+Highlights:
5+- Add instance for `TimeOfDay` (see [#196]( https://github.com/GetShopTV/swagger2/pull/196 ));
6+- Add support for [`optics`](https://hackage.haskell.org/package/optics) (see [#200]( https://github.com/GetShopTV/swagger2/pull/200 ));
7+- Slightly better validation errors (see [#195]( https://github.com/GetShopTV/swagger2/pull/195 ));
8+
9+Fixes and minor changes:
10+- Minor cleanup (see [#194]( https://github.com/GetShopTV/swagger2/pull/194 ));
11+- Allow base-4.13 and other GHC-8.8 related stuff (see [#198]( https://github.com/GetShopTV/swagger2/pull/198 ));
12+- Fix `stack.yaml` (see [#201]( https://github.com/GetShopTV/swagger2/pull/201 ));
13+
14+2.4
15+---
16+
17+- Allow hashable-1.3, semigroups-0.19, network-3.1, time-1.9, generics-sop-0.5
18+- Tags aren't sorted
19+ (see [#165](https://github.com/GetShopTV/swagger2/issues/165))
20+- Schema type is optional
21+ (see [#138](https://github.com/GetShopTV/swagger2/issues/138), [#164](https://github.com/GetShopTV/swagger2/pull/164))
22+- Take concrete 'Proxy' as argument
23+ (see [#180](https://github.com/GetShopTV/swagger2/pull/180))
24+- GHC-8.8 preparations
25+
26+2.3.1.1
27+-------
28+
29+- Allow `network-3.0`
30+
31+2.3.1
32+-----
33+
34+- Add a quickcheck generator for aeson Values that match a swagger schema
35+ (see [#162](https://github.com/GetShopTV/swagger2/pull/162))
36+- Add `ToParamSchema` instance for `SetCookie`
37+ (see [#173](https://github.com/GetShopTV/swagger2/pull/173))
38+- Make nullary schemas valid
39+ (see [#168](https://github.com/GetShopTV/swagger2/pull/168))
40+
41+2.3.0.1
42+-------
43+
44+- Support GHC-8.6
45+
46+2.3
47+---
48+
49+Major changes:
50+
51+- Add support for `additionalProperties` with `Bool` value (see [#159](https://github.com/GetShopTV/swagger2/pull/159));
52+- Add `ToSchema` `Object` instance (for aeson's `Object`) (see [`d72466a`](https://github.com/GetShopTV/swagger2/commit/d72466a));
53+
54+Dependencies and CI:
55+
56+- Aeson 1.4 (see [#158](https://github.com/GetShopTV/swagger2/pull/158));
57+- Update .travis.yml (see [#160](https://github.com/GetShopTV/swagger2/pull/160));
58+- Allow network 2.7 (see [#155](https://github.com/GetShopTV/swagger2/pull/155));
59+- Allow lens-4.17 (see [#161](https://github.com/GetShopTV/swagger2/pull/161));
60+
61+2.2.2
62+-----
63+
64+* Add `ToSchema Version` instance
65+* Use base-compat-batteries (0.10)
66+* PVP bounds
67+
68+2.2.1
69+-----
70+
71+* Add `Semigroup` instances
72+* GHC-8.4 compatibility
73+* `Schema (NonEmpty a) instance (see [#141](https://github.com/GetShopTV/swagger2/pull/141))
74+* Fix optional property for unary records (see [#142](https://github.com/GetShopTV/swagger2/issues/142))
75+* Add `fromAesonOptions` helper (see [#146](https://github.com/GetShopTV/swagger2/issues/139))
76+* Fix non-termination when using `datatypeNameModifier` with recursive data types (see [#132](https://github.com/GetShopTV/swagger2/issues/132))
77+
78+2.2
79+---
80+
81+* Treat unknown properties as validation errors in `validateToJSON` (see [#126](https://github.com/GetShopTV/swagger2/pull/126));
82+* Add `validateJSON` and `validateJSONWithPatternChecker` to validate JSON `Value` against `Schema` without classes (see [#126](https://github.com/GetShopTV/swagger2/pull/126));
83+* Add more `Schema` helpers (see [#126](https://github.com/GetShopTV/swagger2/pull/126)):
84+ * `genericNameSchema` — to give a custom schema `Generic`-based name;
85+ * `genericDeclareNamedSchemaNewtype` — to derive `NamedSchema` for `newtype`s;
86+ * `declareSchemaBoundedEnumKeyMapping` — to derive more specific `Schema` for maps with `Bounded` `Enum` keys;
87+* Add a few tests with invalid `Schema`.
88+
89+2.1.6
90+-----
91+
92+* Add `ToParamSchema` and `ToSchema` instances for `Fixed` (see [#121](https://github.com/GetShopTV/swagger2/pull/121)) and `Natural` (see [#123](https://github.com/GetShopTV/swagger2/pull/123));
93+* Fix instance for `NominalDiffTime` (see [#121](https://github.com/GetShopTV/swagger2/pull/121));
94+* Fix build for `aeson-1.2.2.0` (see [#125](https://github.com/GetShopTV/swagger2/pull/125)).
95+
96+2.1.5
97+-----
98+
99+* Type error by default when deriving Generic-based instances for mixed sum types (see [#118](https://github.com/GetShopTV/swagger2/pull/118));
100+* Adjust `allOf` to accept referenced schemas (see [#119](https://github.com/GetShopTV/swagger2/issues/119));
101+* Add instances for `Identity` (see [#116](https://github.com/GetShopTV/swagger2/pull/116));
102+* Add Gitter chat badge (see [#114](https://github.com/GetShopTV/swagger2/pull/114)).
103+
104+2.1.4.1
105+-------
106+
107+* GHC-8.2 support (see [#95](https://github.com/GetShopTV/swagger2/issues/95), [#106](https://github.com/GetShopTV/swagger2/pull/106) and [#108](https://github.com/GetShopTV/swagger2/pull/108));
108+* Documentation corrections (see [#105](https://github.com/GetShopTV/swagger2/pull/105));
109+* Allow `generics-sop-0.3` (see [#102](https://github.com/GetShopTV/swagger2/pull/102));
110+* Fix `ToSchema` example in docs (see [#104](https://github.com/GetShopTV/swagger2/pull/104)).
111+
112+2.1.4
113+-----
114+
115+* Add `liftDeclare` (see [#100](https://github.com/GetShopTV/swagger2/pull/100));
116+* Add `MonadDeclare` instances for all monad transformers (see [#100](https://github.com/GetShopTV/swagger2/pull/100)).
117+
118+2.1.3
119+-----
120+
121+* Add [`UUID`](http://hackage.haskell.org/package/uuid-types/docs/Data-UUID-Types.html#t:UUID) instances (see [#81](https://github.com/GetShopTV/swagger2/pull/81)).
122+* Add [`TypeError`](https://hackage.haskell.org/package/base-4.9.0.0/docs/GHC-TypeLits.html#g:4) `ToSchema` and `ToParamSchema ByteString` instances (see [#78](https://github.com/GetShopTV/swagger2/pull/78))
123+* Improve documentation for generic sum type instance derivation (see [#75](https://github.com/GetShopTV/swagger2/pull/75))
124+* Compile warning free (see [#82](https://github.com/GetShopTV/swagger2/pull/82))
125+
126+2.1.2.1
127+-------
128+
129+* Bug fix previous release
130+
131+2.1.2
132+---
133+
134+* Minor changes:
135+ * Support `aeson-1.0.0.0` (see [#70](https://github.com/GetShopTV/swagger2/pull/70)).
136+
137+2.1.1
138+---
139+
140+* Minor changes:
141+ * Proper `Schema` examples for `Char`, `Day`, `LocalTime`, `ZonedTime` and `UTCTime`.
142+
143+2.1
144+---
145+
146+* Major changes:
147+ * Use `InsOrdHashMap` to preserve insertion order for endpoints and definitions (see [#56](https://github.com/GetShopTV/swagger2/pull/56));
148+ * Add support for GHC 8.0 (see [#65](https://github.com/GetShopTV/swagger2/pull/65)).
149+
150+2.0.2
151+---
152+
153+* Fixes:
154+ * Fix `additionalProperties` to allow references;
155+ * Fix `ToSchema` instances for `Map` and `HashMap` (prevent infinite recursion for recursive values).
156+
157+2.0.1
158+---
159+
160+* Fixes:
161+ * Re-export `Pattern` synonym from `Data.Swagger`;
162+ * Documentation fixes.
163+
164+2.0
165+---
166+
167+* Major changes:
168+ * GHC 7.8 support (see [#49](https://github.com/GetShopTV/swagger2/pull/49));
169+ * Switch to classy field lenses (see [#41](https://github.com/GetShopTV/swagger2/pull/41));
170+ * Add `Data.Swagger.Schema.Validation` (see [#18](https://github.com/GetShopTV/swagger2/pull/18));
171+ * Add `Data.Swagger.Operation` with helpers (see [#50](https://github.com/GetShopTV/swagger2/pull/50));
172+ * Add `IsString` instances for some types (see [#47](https://github.com/GetShopTV/swagger2/pull/47));
173+ * Add helpers to sketch `Schema` from JSON (see [#48](https://github.com/GetShopTV/swagger2/pull/48)).
174+
175+* Minor changes:
176+ * Make `NamedSchema` a `data` rather than `type` (see [#42](https://github.com/GetShopTV/swagger2/pull/42));
177+ * Change `Definitions` to `Definitions Schema`;
178+ * Add schema templates for `"binary"`, `"byte"` and `"password"` formats (see [63ed597](https://github.com/GetShopTV/swagger2/commit/63ed59736dc4f942f0e2a7d668d7cee513fa9eaf));
179+ * Add `Monoid` instance for `Contact`;
180+ * Change `tags` to be `Set` rather than list.
181+
182+* Fixes:
183+ * Fix schema for `()` and nullary constructors (see [ab65c4a](https://github.com/GetShopTV/swagger2/commit/ab65c4a48253c34f8a88221a53dc97bf5e6e8d29));
184+ * Fix `Operation` `FromJSON` instance to allow missing `tags` and `parameters` properties.
185+
11.2.1
1861.2.1
2---
187---
3
188
4−* Minor change:
189+* Minor changes:
5 * Change `_SwaggerItemsPrimitive` type from a `Prism'` to a more restrictive `Review`-like `Optic'`.
190 * Change `_SwaggerItemsPrimitive` type from a `Prism'` to a more restrictive `Review`-like `Optic'`.
6
191
7* Fixes:
192* Fixes:
LICENSE+1−1
@@ -1,4 +1,4 @@
1−Copyright (c) 2015, GetShopTV
1+Copyright (c) 2015-2017, GetShopTV
2All rights reserved.
2All rights reserved.
3
3
4Redistribution and use in source and binary forms, with or without
4Redistribution and use in source and binary forms, with or without
README.md+3−1
@@ -1,5 +1,7 @@
1# swagger2
1# swagger2
2
2
3+[![Join the chat at https://gitter.im/haskell-swagger2/Lobby](https://badges.gitter.im/haskell-swagger2/Lobby.svg)](https://gitter.im/haskell-swagger2/Lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
4+
3[![Hackage](https://img.shields.io/hackage/v/swagger2.svg)](http://hackage.haskell.org/package/swagger2)
5[![Hackage](https://img.shields.io/hackage/v/swagger2.svg)](http://hackage.haskell.org/package/swagger2)
4[![Build Status](https://travis-ci.org/GetShopTV/swagger2.svg?branch=master)](https://travis-ci.org/GetShopTV/swagger2)
6[![Build Status](https://travis-ci.org/GetShopTV/swagger2.svg?branch=master)](https://travis-ci.org/GetShopTV/swagger2)
5[![Stackage LTS](http://stackage.org/package/swagger2/badge/lts)](http://stackage.org/lts/package/swagger2)
7[![Stackage LTS](http://stackage.org/package/swagger2/badge/lts)](http://stackage.org/lts/package/swagger2)
@@ -11,7 +13,7 @@ The original Swagger 2.0 specification is available at http://swagger.io/specifi
11
13
12## Usage
14## Usage
13
15
14−This library is inteded to be used for decoding and encoding Swagger 2.0 API specifications as well as manipulating them.
16+This library is intended to be used for decoding and encoding Swagger 2.0 API specifications as well as manipulating them.
15
17
16Please refer to [haddock documentation](http://hackage.haskell.org/package/swagger2).
18Please refer to [haddock documentation](http://hackage.haskell.org/package/swagger2).
17
19
Setup.hs+31
@@ -1,2 +1,33 @@
1+{-# LANGUAGE CPP #-}
2+{-# OPTIONS_GHC -Wall #-}
3+module Main (main) where
4+
5+#ifndef MIN_VERSION_cabal_doctest
6+#define MIN_VERSION_cabal_doctest(x,y,z) 0
7+#endif
8+
9+#if MIN_VERSION_cabal_doctest(1,0,0)
10+
11+import Distribution.Extra.Doctest ( defaultMainWithDoctests )
12+main :: IO ()
13+main = defaultMainWithDoctests "doctests"
14+
15+#else
16+
17+#ifdef MIN_VERSION_Cabal
18+-- If the macro is defined, we have new cabal-install,
19+-- but for some reason we don't have cabal-doctest in package-db
20+--
21+-- Probably we are running cabal sdist, when otherwise using new-build
22+-- workflow
23+#warning You are configuring this package without cabal-doctest installed. \
24+ The doctests test-suite will not work as a result. \
25+ To fix this, install cabal-doctest before configuring.
26+#endif
27+
1import Distribution.Simple
28import Distribution.Simple
29+
30+main :: IO ()
2main = defaultMain
31main = defaultMain
32+
33+#endif
cabal.projectnew file+2
@@ -0,0 +1,2 @@
1+packages: .
2+tests: true
examples/hackage.hs+40−24
@@ -13,13 +13,28 @@ import GHC.Generics
13import Data.Swagger
13import Data.Swagger
14import Data.Swagger.Declare
14import Data.Swagger.Declare
15import Data.Swagger.Lens
15import Data.Swagger.Lens
16+import Data.Swagger.Operation
16
17
17type Username = Text
18type Username = Text
18
19
19data UserSummary = UserSummary
20data UserSummary = UserSummary
20 { summaryUsername :: Username
21 { summaryUsername :: Username
21 , summaryUserid :: Int
22 , summaryUserid :: Int
22− } deriving (Generic, ToSchema)
23+ } deriving (Generic)
24+
25+instance ToSchema UserSummary where
26+ declareNamedSchema _ = do
27+ usernameSchema <- declareSchemaRef (Proxy :: Proxy Username)
28+ useridSchema <- declareSchemaRef (Proxy :: Proxy Int)
29+ return $ NamedSchema (Just "UserSummary") $ mempty
30+ & type_ ?~ SwaggerObject
31+ & properties .~
32+ [ ("summaryUsername", usernameSchema )
33+ , ("summaryUserid" , useridSchema )
34+ ]
35+ & required .~ [ "summaryUsername"
36+ , "summaryUserid" ]
37+
23
38
24type Group = Text
39type Group = Text
25
40
@@ -37,32 +52,33 @@ hackageSwagger = spec & definitions .~ defs
37 where
52 where
38 (defs, spec) = runDeclare declareHackageSwagger mempty
53 (defs, spec) = runDeclare declareHackageSwagger mempty
39
54
40−declareHackageSwagger :: Declare Definitions Swagger
55+declareHackageSwagger :: Declare (Definitions Schema) Swagger
41declareHackageSwagger = do
56declareHackageSwagger = do
57+ -- param schemas
42 let usernameParamSchema = toParamSchema (Proxy :: Proxy Username)
58 let usernameParamSchema = toParamSchema (Proxy :: Proxy Username)
43− userSummarySchemaRef <- declareSchemaRef (Proxy :: Proxy UserSummary)
59+
44− userDetailedSchemaRef <- declareSchemaRef (Proxy :: Proxy UserDetailed)
60+ -- responses
45− packagesSchemaRef <- declareSchemaRef (Proxy :: Proxy [Package])
61+ userSummaryResponse <- declareResponse (Proxy :: Proxy UserSummary)
62+ userDetailedResponse <- declareResponse (Proxy :: Proxy UserDetailed)
63+ packagesResponse <- declareResponse (Proxy :: Proxy [Package])
64+
46 return $ mempty
65 return $ mempty
47− & paths.pathsMap .~
66+ & paths .~
48− [ ("/users", mempty & pathItemGet ?~ (mempty
67+ [ ("/users", mempty & get ?~ (mempty
49− & operationProduces ?~ MimeList ["application/json"]
68+ & produces ?~ MimeList ["application/json"]
50− & operationResponses .~ (mempty
69+ & at 200 ?~ Inline userSummaryResponse))
51− & responsesResponses . at 200 ?~ Inline (mempty & responseSchema ?~ userSummarySchemaRef))))
52− , ("/user/{username}", mempty & pathItemGet ?~ (mempty
70+ , ("/user/{username}", mempty & get ?~ (mempty
53− & operationProduces ?~ MimeList ["application/json"]
71+ & produces ?~ MimeList ["application/json"]
54− & operationParameters .~ [ Inline $ mempty
72+ & parameters .~ [ Inline $ mempty
55− & paramName .~ "username"
73+ & name .~ "username"
56− & paramRequired ?~ True
74+ & required ?~ True
57− & paramSchema .~ ParamOther (mempty
75+ & schema .~ ParamOther (mempty
58− & paramOtherSchemaIn .~ ParamPath
76+ & in_ .~ ParamPath
59− & paramOtherSchemaParamSchema .~ usernameParamSchema) ]
77+ & paramSchema .~ usernameParamSchema) ]
60− & operationResponses .~ (mempty
78+ & at 200 ?~ Inline userDetailedResponse))
61− & responsesResponses . at 200 ?~ Inline (mempty & responseSchema ?~ userDetailedSchemaRef))))
62− , ("/packages", mempty & pathItemGet ?~ (mempty
79+ , ("/packages", mempty & get ?~ (mempty
63− & operationProduces ?~ MimeList ["application/json"]
80+ & produces ?~ MimeList ["application/json"]
64− & operationResponses .~ (mempty
81+ & at 200 ?~ Inline packagesResponse))
65− & responsesResponses . at 200 ?~ Inline (mempty & responseSchema ?~ packagesSchemaRef))))
66 ]
82 ]
67
83
68main :: IO ()
84main :: IO ()
hackage-docs.shnew file+78
@@ -0,0 +1,78 @@
1+#!/bin/bash
2+set -e
3+
4+# This if stack-enabled fork of https://github.com/ekmett/lens/blob/master/scripts/hackage-docs.sh
5+
6+if [ "$#" -ne 1 ]; then
7+ echo "Usage: scripts/hackage-docs.sh HACKAGE_USER"
8+ exit 1
9+fi
10+
11+user=$1
12+
13+cabal_file=$(find . -maxdepth 1 -name "*.cabal" -print -quit)
14+if [ ! -f "$cabal_file" ]; then
15+ echo "Run this script in the top-level package directory"
16+ exit 1
17+fi
18+
19+pkg=$(awk -F ":[[:space:]]*" 'tolower($1)=="name" { print $2 }' < "$cabal_file")
20+ver=$(awk -F ":[[:space:]]*" 'tolower($1)=="version" { print $2 }' < "$cabal_file")
21+
22+if [ -z "$pkg" ]; then
23+ echo "Unable to determine package name"
24+ exit 1
25+fi
26+
27+if [ -z "$ver" ]; then
28+ echo "Unable to determine package version"
29+ exit 1
30+fi
31+
32+echo "Detected package: $pkg-$ver"
33+
34+dir=$(mktemp -d build-docs.XXXXXX)
35+trap 'rm -r "$dir"' EXIT
36+
37+export PATH=$(stack path --bin-path)
38+
39+ghc --version
40+cabal --version
41+stack --version
42+
43+if haddock --hyperlinked-source >/dev/null
44+then
45+ echo "Using fancy hyperlinked source"
46+ HYPERLINK_FLAG="--haddock-option=--hyperlinked-source"
47+else
48+ echo "Using boring hyperlinked source"
49+ HYPERLINK_FLAG="--hyperlink-source"
50+fi
51+
52+# Cabal dist in temporary location
53+builddir=$dir/dist
54+
55+# Build dependencies haddocks with stack, so we get links
56+stack haddock --only-dependencies
57+
58+# Configure using stack databases
59+snapshotpkgdb=$(stack path --snapshot-pkg-db)
60+localpkgdb=$(stack path --local-pkg-db)
61+cabal configure -v2 --builddir=$builddir --package-db=clear --package-db=global --package-db=$snapshotpkgdb --package-db=$localpkgdb
62+
63+# Build Hadckage compatible docs
64+cabal haddock -v2 --builddir=$builddir $HYPERLINK_FLAG --html-location='/package/$pkg-$version/docs' --contents-location='/package/$pkg-$version'
65+
66+# Copy into right directory
67+cp -R $builddir/doc/html/$pkg/ $dir/$pkg-$ver-docs
68+
69+# Tar and gzip
70+tar cvz -C $dir --format=ustar -f $dir/$pkg-$ver-docs.tar.gz $pkg-$ver-docs
71+
72+# Upload
73+curl -X PUT \
74+ -H 'Content-Type: application/x-tar' \
75+ -H 'Content-Encoding: gzip' \
76+ -u "$user" \
77+ --data-binary "@$dir/$pkg-$ver-docs.tar.gz" \
78+ "https://hackage.haskell.org/package/$pkg-$ver/docs"
src/Data/Swagger.hs+104−13
@@ -1,4 +1,9 @@
1+{-# LANGUAGE CPP #-}
1-- |
2-- |
3+-- Module: Data.Swagger
4+-- Maintainer: Nickolay Kudasov <nickolay@getshoptv.com>
5+-- Stability: experimental
6+--
2-- Swagger™ is a project used to describe and document RESTful APIs.
7-- Swagger™ is a project used to describe and document RESTful APIs.
3--
8--
4-- The Swagger specification defines a set of files required to describe such an API.
9-- The Swagger specification defines a set of files required to describe such an API.
@@ -18,10 +23,19 @@ module Data.Swagger (
18 -- ** Schema specification
23 -- ** Schema specification
19 -- $schema
24 -- $schema
20
25
26+ -- ** Manipulation
27+ -- $manipulation
28+
29+ -- ** Validation
30+ -- $validation
31+
21 -- * Re-exports
32 -- * Re-exports
22 module Data.Swagger.Lens,
33 module Data.Swagger.Lens,
34+ module Data.Swagger.Optics,
35+ module Data.Swagger.Operation,
23 module Data.Swagger.ParamSchema,
36 module Data.Swagger.ParamSchema,
24 module Data.Swagger.Schema,
37 module Data.Swagger.Schema,
38+ module Data.Swagger.Schema.Validation,
25
39
26 -- * Swagger specification
40 -- * Swagger specification
27 Swagger(..),
41 Swagger(..),
@@ -63,6 +77,8 @@ module Data.Swagger (
63 NamedSchema(..),
77 NamedSchema(..),
64 SwaggerItems(..),
78 SwaggerItems(..),
65 Xml(..),
79 Xml(..),
80+ Pattern,
81+ AdditionalProperties(..),
66
82
67 -- ** Responses
83 -- ** Responses
68 Responses(..),
84 Responses(..),
@@ -73,6 +89,7 @@ module Data.Swagger (
73 SecurityScheme(..),
89 SecurityScheme(..),
74 SecuritySchemeType(..),
90 SecuritySchemeType(..),
75 SecurityRequirement(..),
91 SecurityRequirement(..),
92+ SecurityDefinitions(..),
76
93
77 -- *** API key
94 -- *** API key
78 ApiKeyParams(..),
95 ApiKeyParams(..),
@@ -97,8 +114,11 @@ module Data.Swagger (
97) where
114) where
98
115
99import Data.Swagger.Lens
116import Data.Swagger.Lens
117+import Data.Swagger.Optics ()
118+import Data.Swagger.Operation
100import Data.Swagger.ParamSchema
119import Data.Swagger.ParamSchema
101import Data.Swagger.Schema
120import Data.Swagger.Schema
121+import Data.Swagger.Schema.Validation
102
122
103import Data.Swagger.Internal
123import Data.Swagger.Internal
104
124
@@ -158,43 +178,47 @@ import Data.Swagger.Internal
158
178
159-- $lens
179-- $lens
160--
180--
181+-- Note: if you're working with the <https://hackage.haskell.org/package/optics optics> library, take a look at "Data.Swagger.Optics".
182+--
161-- Since @'Swagger'@ has a fairly complex structure, lenses and prisms are used
183-- Since @'Swagger'@ has a fairly complex structure, lenses and prisms are used
162−-- to work comfortly with it. In combination with @'Monoid'@ instances, lenses
184+-- to work comfortably with it. In combination with @'Monoid'@ instances, lenses
163-- make it fairly simple to construct/modify any part of the specification:
185-- make it fairly simple to construct/modify any part of the specification:
164--
186--
165-- >>> :{
187-- >>> :{
166-- encode $ (mempty :: Swagger)
188-- encode $ (mempty :: Swagger)
167−-- & definitions .~ [ ("User", mempty & type_ .~ SwaggerString) ]
189+-- & definitions .~ [ ("User", mempty & type_ ?~ SwaggerString) ]
168-- & paths .~
190-- & paths .~
169-- [ ("/user", mempty & get ?~ (mempty
191-- [ ("/user", mempty & get ?~ (mempty
170-- & produces ?~ MimeList ["application/json"]
192-- & produces ?~ MimeList ["application/json"]
171−-- & at 200 ?~ Inline (mempty & schema ?~ Ref (Reference "User")))) ]
193+-- & at 200 ?~ ("OK" & _Inline.schema ?~ Ref (Reference "User"))
194+-- & at 404 ?~ "User info not found")) ]
172-- :}
195-- :}
173−-- "{\"swagger\":\"2.0\",\"info\":{\"version\":\"\",\"title\":\"\"},\"definitions\":{\"User\":{\"type\":\"string\"}},\"paths\":{\"/user\":{\"get\":{\"responses\":{\"200\":{\"schema\":{\"$ref\":\"#/definitions/User\"},\"description\":\"\"}},\"produces\":[\"application/json\"]}}}}"
196+-- "{\"swagger\":\"2.0\",\"info\":{\"version\":\"\",\"title\":\"\"},\"paths\":{\"/user\":{\"get\":{\"produces\":[\"application/json\"],\"responses\":{\"404\":{\"description\":\"User info not found\"},\"200\":{\"schema\":{\"$ref\":\"#/definitions/User\"},\"description\":\"OK\"}}}}},\"definitions\":{\"User\":{\"type\":\"string\"}}}"
174--
197--
175−-- In the snippet above we declare API with a single path @/user@ providing method @GET@
198+-- In the snippet above we declare an API with a single path @/user@. This path provides method @GET@
176−-- which produces @application/json@ output and should respond with code @200@ and body specified
199+-- which produces @application/json@ output. It should respond with code @200@ and body specified
177-- by schema @User@ which is defined in @'definitions'@ property of swagger specification.
200-- by schema @User@ which is defined in @'definitions'@ property of swagger specification.
201+-- Alternatively it may respond with code @404@ meaning that user info is not found.
178--
202--
179-- For convenience, @swagger2@ uses /classy field lenses/. It means that
203-- For convenience, @swagger2@ uses /classy field lenses/. It means that
180-- field accessor names can be overloaded for different types. One such
204-- field accessor names can be overloaded for different types. One such
181−-- common field is @'description'@. Many components of Swagger specification
205+-- common field is @'description'@. Many components of a Swagger specification
182-- can have descriptions, and you can use the same name for them:
206-- can have descriptions, and you can use the same name for them:
183--
207--
184-- >>> encode $ (mempty :: Response) & description .~ "No content"
208-- >>> encode $ (mempty :: Response) & description .~ "No content"
185-- "{\"description\":\"No content\"}"
209-- "{\"description\":\"No content\"}"
186-- >>> :{
210-- >>> :{
187-- encode $ (mempty :: Schema)
211-- encode $ (mempty :: Schema)
188−-- & type_ .~ SwaggerBoolean
212+-- & type_ ?~ SwaggerBoolean
189-- & description ?~ "To be or not to be"
213-- & description ?~ "To be or not to be"
190-- :}
214-- :}
191−-- "{\"type\":\"boolean\",\"description\":\"To be or not to be\"}"
215+-- "{\"description\":\"To be or not to be\",\"type\":\"boolean\"}"
192--
216--
193-- @'ParamSchema'@ is basically the /base schema specification/ and many types contain it (see @'HasParamSchema'@).
217-- @'ParamSchema'@ is basically the /base schema specification/ and many types contain it (see @'HasParamSchema'@).
194-- So for convenience, all @'ParamSchema'@ fields are transitively made fields of the type that has it.
218-- So for convenience, all @'ParamSchema'@ fields are transitively made fields of the type that has it.
195-- For example, you can use @'type_'@ to access @'SwaggerType'@ of @'Header'@ schema without having to use @'paramSchema'@:
219-- For example, you can use @'type_'@ to access @'SwaggerType'@ of @'Header'@ schema without having to use @'paramSchema'@:
196--
220--
197−-- >>> encode $ (mempty :: Header) & type_ .~ SwaggerNumber
221+-- >>> encode $ (mempty :: Header) & type_ ?~ SwaggerNumber
198-- "{\"type\":\"number\"}"
222-- "{\"type\":\"number\"}"
199--
223--
200-- Additionally, to simplify working with @'Response'@, both @'Operation'@ and @'Responses'@
224-- Additionally, to simplify working with @'Response'@, both @'Operation'@ and @'Responses'@
@@ -202,7 +226,7 @@ import Data.Swagger.Internal
202--
226--
203-- >>> :{
227-- >>> :{
204-- encode $ (mempty :: Operation)
228-- encode $ (mempty :: Operation)
205−-- & at 404 ?~ Inline (mempty & description .~ "Not found")
229+-- & at 404 ?~ "Not found"
206-- :}
230-- :}
207-- "{\"responses\":{\"404\":{\"description\":\"Not found\"}}}"
231-- "{\"responses\":{\"404\":{\"description\":\"Not found\"}}}"
208--
232--
@@ -212,7 +236,7 @@ import Data.Swagger.Internal
212-- A few other field accessors are modified in this way:
236-- A few other field accessors are modified in this way:
213--
237--
214-- - @'in_'@, @'type_'@, @'default_'@ (as keywords);
238-- - @'in_'@, @'type_'@, @'default_'@ (as keywords);
215−-- - @'maximum_'@ and @'minimum_'@ (as conflicting with @Prelude@);
239+-- - @'maximum_'@, @'minimum_'@, @'head_'@ (as conflicting with @Prelude@);
216-- - @'enum_'@ (as conflicting with @Control.Lens@).
240-- - @'enum_'@ (as conflicting with @Control.Lens@).
217
241
218-- $schema
242-- $schema
@@ -254,6 +278,73 @@ import Data.Swagger.Internal
254-- >>> encode (Person "David" 28)
278-- >>> encode (Person "David" 28)
255-- "{\"age\":28,\"name\":\"David\"}"
279-- "{\"age\":28,\"name\":\"David\"}"
256-- >>> encode $ toSchema (Proxy :: Proxy Person)
280-- >>> encode $ toSchema (Proxy :: Proxy Person)
257−-- "{\"required\":[\"name\",\"age\"],\"type\":\"object\",\"properties\":{\"age\":{\"type\":\"integer\"},\"name\":{\"type\":\"string\"}}}"
281+-- "{\"required\":[\"name\",\"age\"],\"properties\":{\"name\":{\"type\":\"string\"},\"age\":{\"type\":\"integer\"}},\"type\":\"object\"}"
282+--
283+-- Please note that not all valid Haskell data types will have a proper swagger schema. For example while we can derive a
284+-- schema for basic enums like
285+--
286+-- >>> data SampleEnum = ChoiceOne | ChoiceTwo deriving Generic
287+-- >>> instance ToSchema SampleEnum
288+-- >>> instance ToJSON SampleEnum
289+--
290+-- and for sum types that have constructors with values
291+--
292+-- >>> data SampleSumType = ChoiceInt Int | ChoiceString String deriving Generic
293+-- >>> instance ToSchema SampleSumType
294+-- >>> instance ToJSON SampleSumType
295+--
296+-- we can not derive a valid schema for a mix of the above. The following will result in a type error
297+--
298+#if __GLASGOW_HASKELL__ < 800
299+-- >>> data BadMixedType = ChoiceBool Bool | JustTag deriving Generic
300+-- >>> instance ToSchema BadMixedType
301+-- ...
302+-- ... error:
303+-- ... • No instance for (Data.Swagger.Internal.TypeShape.CannotDeriveSchemaForMixedSumType
304+-- ... BadMixedType)
305+-- ... arising from a use of ‘Data.Swagger.Internal.Schema.$dmdeclareNamedSchema’
306+-- ... • In the expression:
307+-- ... Data.Swagger.Internal.Schema.$dmdeclareNamedSchema @BadMixedType
308+-- ... In an equation for ‘declareNamedSchema’:
309+-- ... declareNamedSchema
310+-- ... = Data.Swagger.Internal.Schema.$dmdeclareNamedSchema @BadMixedType
311+-- ... In the instance declaration for ‘ToSchema BadMixedType’
312+#else
313+-- >>> data BadMixedType = ChoiceBool Bool | JustTag deriving Generic
314+-- >>> instance ToSchema BadMixedType
315+-- ...
316+-- ... error:
317+-- ... • Cannot derive Generic-based Swagger Schema for BadMixedType
318+-- ... BadMixedType is a mixed sum type (has both unit and non-unit constructors).
319+-- ... Swagger does not have a good representation for these types.
320+-- ... Use genericDeclareNamedSchemaUnrestricted if you want to derive schema
321+-- ... that matches aeson's Generic-based toJSON,
322+-- ... but that's not supported by some Swagger tools.
323+-- ... • In the expression:
324+-- ... Data.Swagger.Internal.Schema.$dmdeclareNamedSchema @BadMixedType
325+-- ... In an equation for ‘declareNamedSchema’:
326+-- ... declareNamedSchema
327+-- ... = Data.Swagger.Internal.Schema.$dmdeclareNamedSchema @BadMixedType
328+-- ... In the instance declaration for ‘ToSchema BadMixedType’
329+#endif
330+--
331+-- We can use 'genericDeclareNamedSchemaUnrestricted' to try our best to represent this type as a Swagger Schema and match 'ToJSON':
332+--
333+-- >>> data BadMixedType = ChoiceBool Bool | JustTag deriving Generic
334+-- >>> instance ToSchema BadMixedType where declareNamedSchema = genericDeclareNamedSchemaUnrestricted defaultSchemaOptions
335+-- >>> instance ToJSON BadMixedType
258--
336--
259
337
338+-- $manipulation
339+-- Sometimes you have to work with an imported or generated @'Swagger'@.
340+-- For instance, <servant-swagger http://hackage.haskell.org/package/servant-swagger> generates basic @'Swagger'@
341+-- for a type-level servant API.
342+--
343+-- Lenses and prisms can be used to manipulate such specification to add additional information, tags, extra responses, etc.
344+-- To facilitate common needs, @"Data.Swagger.Operation"@ module provides useful helpers.
345+
346+-- $validation
347+-- While @'ToParamSchema'@ and @'ToSchema'@ provide means to easily obtain schemas for Haskell types,
348+-- there is no static mechanism to ensure those instances correspond to the @'ToHttpApiData'@ or @'ToJSON'@ instances.
349+--
350+-- @"Data.Swagger.Schema.Validation"@ addresses @'ToJSON'@/@'ToSchema'@ validation.
src/Data/Swagger/Declare.hs+83−5
@@ -2,15 +2,33 @@
2{-# LANGUAGE FlexibleInstances #-}
2{-# LANGUAGE FlexibleInstances #-}
3{-# LANGUAGE FunctionalDependencies #-}
3{-# LANGUAGE FunctionalDependencies #-}
4{-# LANGUAGE MultiParamTypeClasses #-}
4{-# LANGUAGE MultiParamTypeClasses #-}
5+{-# LANGUAGE UndecidableInstances #-}
6+-- |
7+-- Module: Data.Swagger.Declare
8+-- Maintainer: Nickolay Kudasov <nickolay@getshoptv.com>
9+-- Stability: experimental
10+--
11+-- Declare monad transformer and associated functions.
5module Data.Swagger.Declare where
12module Data.Swagger.Declare where
6
13
7import Prelude ()
14import Prelude ()
8import Prelude.Compat
15import Prelude.Compat
9
16
10import Control.Monad
17import Control.Monad
18+import Control.Monad.Cont (ContT)
19+import Control.Monad.List (ListT)
20+import Control.Monad.Reader (ReaderT)
11import Control.Monad.Trans
21import Control.Monad.Trans
22+import Control.Monad.Trans.Except (ExceptT)
23+import Control.Monad.Trans.Identity (IdentityT)
24+import Control.Monad.Trans.Maybe (MaybeT)
25+import Control.Monad.Trans.State.Lazy as Lazy
26+import Control.Monad.Trans.State.Strict as Strict
27+import Control.Monad.Trans.RWS.Lazy as Lazy
28+import Control.Monad.Trans.RWS.Strict as Strict
29+import Control.Monad.Trans.Writer.Lazy as Lazy
30+import Control.Monad.Trans.Writer.Strict as Strict
12import Data.Functor.Identity
31import Data.Functor.Identity
13−import Data.Monoid
14
32
15-- | A declare monad transformer parametrized by:
33-- | A declare monad transformer parametrized by:
16--
34--
@@ -31,15 +49,15 @@ instance (Applicative m, Monad m, Monoid d) => Applicative (DeclareT d m) where
31 pure x = DeclareT (\_ -> pure (mempty, x))
49 pure x = DeclareT (\_ -> pure (mempty, x))
32 DeclareT df <*> DeclareT dx = DeclareT $ \d -> do
50 DeclareT df <*> DeclareT dx = DeclareT $ \d -> do
33 ~(d', f) <- df d
51 ~(d', f) <- df d
34− ~(d'', x) <- dx (d <> d')
52+ ~(d'', x) <- dx (mappend d d')
35− return (d' <> d'', f x)
53+ return (mappend d' d'', f x)
36
54
37instance (Applicative m, Monad m, Monoid d) => Monad (DeclareT d m) where
55instance (Applicative m, Monad m, Monoid d) => Monad (DeclareT d m) where
38 return x = DeclareT (\_ -> pure (mempty, x))
56 return x = DeclareT (\_ -> pure (mempty, x))
39 DeclareT dx >>= f = DeclareT $ \d -> do
57 DeclareT dx >>= f = DeclareT $ \d -> do
40 ~(d', x) <- dx d
58 ~(d', x) <- dx d
41− ~(d'', y) <- runDeclareT (f x) (d <> d')
59+ ~(d'', y) <- runDeclareT (f x) (mappend d d')
42− return (d' <> d'', y)
60+ return (mappend d' d'', y)
43
61
44instance Monoid d => MonadTrans (DeclareT d) where
62instance Monoid d => MonadTrans (DeclareT d) where
45 lift m = DeclareT (\_ -> (,) mempty `liftM` m)
63 lift m = DeclareT (\_ -> (,) mempty `liftM` m)
@@ -71,6 +89,13 @@ instance (Applicative m, Monad m, Monoid d) => MonadDeclare d (DeclareT d m) whe
71 declare d = DeclareT (\_ -> return (d, ()))
89 declare d = DeclareT (\_ -> return (d, ()))
72 look = DeclareT (\d -> return (mempty, d))
90 look = DeclareT (\d -> return (mempty, d))
73
91
92+-- | Lift a computation from the simple Declare monad.
93+liftDeclare :: MonadDeclare d m => Declare d a -> m a
94+liftDeclare da = do
95+ (d', a) <- looks (runDeclare da)
96+ declare d'
97+ pure a
98+
74-- | Retrieve a function of all the output so far.
99-- | Retrieve a function of all the output so far.
75looks :: MonadDeclare d m => (d -> a) -> m a
100looks :: MonadDeclare d m => (d -> a) -> m a
76looks f = f <$> look
101looks f = f <$> look
@@ -119,3 +144,56 @@ execDeclare m = runIdentity . execDeclareT m
119undeclare :: Monoid d => Declare d a -> a
144undeclare :: Monoid d => Declare d a -> a
120undeclare = runIdentity . undeclareT
145undeclare = runIdentity . undeclareT
121
146
147+-- ---------------------------------------------------------------------------
148+-- Instances for other mtl transformers
149+--
150+-- All of these instances need UndecidableInstances,
151+-- because they do not satisfy the coverage condition.
152+
153+instance MonadDeclare d m => MonadDeclare d (ContT r m) where
154+ declare = lift . declare
155+ look = lift look
156+
157+instance MonadDeclare d m => MonadDeclare d (ExceptT e m) where
158+ declare = lift . declare
159+ look = lift look
160+
161+instance MonadDeclare d m => MonadDeclare d (IdentityT m) where
162+ declare = lift . declare
163+ look = lift look
164+
165+instance MonadDeclare d m => MonadDeclare d (ListT m) where
166+ declare = lift . declare
167+ look = lift look
168+
169+instance MonadDeclare d m => MonadDeclare d (MaybeT m) where
170+ declare = lift . declare
171+ look = lift look
172+
173+instance MonadDeclare d m => MonadDeclare d (ReaderT r m) where
174+ declare = lift . declare
175+ look = lift look
176+
177+instance (Monoid w, MonadDeclare d m) => MonadDeclare d (Lazy.RWST r w s m) where
178+ declare = lift . declare
179+ look = lift look
180+
181+instance (Monoid w, MonadDeclare d m) => MonadDeclare d (Strict.RWST r w s m) where
182+ declare = lift . declare
183+ look = lift look
184+
185+instance MonadDeclare d m => MonadDeclare d (Lazy.StateT s m) where
186+ declare = lift . declare
187+ look = lift look
188+
189+instance MonadDeclare d m => MonadDeclare d (Strict.StateT s m) where
190+ declare = lift . declare
191+ look = lift look
192+
193+instance (Monoid w, MonadDeclare d m) => MonadDeclare d (Lazy.WriterT w m) where
194+ declare = lift . declare
195+ look = lift look
196+
197+instance (Monoid w, MonadDeclare d m) => MonadDeclare d (Strict.WriterT w m) where
198+ declare = lift . declare
199+ look = lift look
src/Data/Swagger/Internal.hs+399−143
@@ -1,5 +1,7 @@
1{-# LANGUAGE CPP #-}
1{-# LANGUAGE CPP #-}
2+{-# LANGUAGE DataKinds #-}
2{-# LANGUAGE DeriveDataTypeable #-}
3{-# LANGUAGE DeriveDataTypeable #-}
4+{-# LANGUAGE DeriveFunctor #-}
3{-# LANGUAGE DeriveGeneric #-}
5{-# LANGUAGE DeriveGeneric #-}
4{-# LANGUAGE DeriveTraversable #-}
6{-# LANGUAGE DeriveTraversable #-}
5{-# LANGUAGE FlexibleContexts #-}
7{-# LANGUAGE FlexibleContexts #-}
@@ -10,36 +12,66 @@
10{-# LANGUAGE RecordWildCards #-}
12{-# LANGUAGE RecordWildCards #-}
11{-# LANGUAGE ScopedTypeVariables #-}
13{-# LANGUAGE ScopedTypeVariables #-}
12{-# LANGUAGE StandaloneDeriving #-}
14{-# LANGUAGE StandaloneDeriving #-}
15+{-# LANGUAGE TemplateHaskell #-}
16+{-# LANGUAGE TypeFamilies #-}
13{-# LANGUAGE UndecidableInstances #-}
17{-# LANGUAGE UndecidableInstances #-}
18+#if __GLASGOW_HASKELL__ <710
19+{-# LANGUAGE PolyKinds #-}
20+#endif
14#include "overlapping-compat.h"
21#include "overlapping-compat.h"
15module Data.Swagger.Internal where
22module Data.Swagger.Internal where
16
23
17import Prelude ()
24import Prelude ()
18import Prelude.Compat
25import Prelude.Compat
19
26
27+import Control.Lens ((&), (.~), (?~))
20import Control.Applicative
28import Control.Applicative
21−import Control.Monad
22import Data.Aeson
29import Data.Aeson
23import qualified Data.Aeson.Types as JSON
30import qualified Data.Aeson.Types as JSON
24import Data.Data (Data(..), Typeable, mkConstr, mkDataType, Fixity(..), Constr, DataType, constrIndex)
31import Data.Data (Data(..), Typeable, mkConstr, mkDataType, Fixity(..), Constr, DataType, constrIndex)
25−import Data.HashMap.Strict (HashMap)
32+import Data.Hashable (Hashable)
26import qualified Data.HashMap.Strict as HashMap
33import qualified Data.HashMap.Strict as HashMap
34+import Data.HashSet.InsOrd (InsOrdHashSet)
27import Data.Map (Map)
35import Data.Map (Map)
28import qualified Data.Map as Map
36import qualified Data.Map as Map
29−import Data.Monoid
37+import Data.Monoid (Monoid (..))
38+import Data.Semigroup.Compat (Semigroup (..))
30import Data.Scientific (Scientific)
39import Data.Scientific (Scientific)
31−import Data.String (fromString)
40+import Data.String (IsString(..))
32import Data.Text (Text)
41import Data.Text (Text)
33import qualified Data.Text as Text
42import qualified Data.Text as Text
34import GHC.Generics (Generic)
43import GHC.Generics (Generic)
35−import Network (HostName, PortNumber)
44+import Network.Socket (HostName, PortNumber)
36import Network.HTTP.Media (MediaType)
45import Network.HTTP.Media (MediaType)
37import Text.Read (readMaybe)
46import Text.Read (readMaybe)
38
47
48+import Data.HashMap.Strict.InsOrd (InsOrdHashMap)
49+import qualified Data.HashMap.Strict.InsOrd as InsOrdHashMap
50+
51+import Generics.SOP.TH (deriveGeneric)
52+import Data.Swagger.Internal.AesonUtils (sopSwaggerGenericToJSON
53+ ,sopSwaggerGenericToJSONWithOpts
54+ ,sopSwaggerGenericParseJSON
55+ ,HasSwaggerAesonOptions(..)
56+ ,AesonDefaultValue(..)
57+ ,mkSwaggerAesonOptions
58+ ,saoAdditionalPairs
59+ ,saoSubObject)
39import Data.Swagger.Internal.Utils
60import Data.Swagger.Internal.Utils
40
61
62+#if MIN_VERSION_aeson(0,10,0)
63+import Data.Swagger.Internal.AesonUtils (sopSwaggerGenericToEncoding)
64+#define DEFINE_TOENCODING toEncoding = sopSwaggerGenericToEncoding
65+#else
66+#define DEFINE_TOENCODING
67+#endif
68+
69+-- $setup
70+-- >>> :seti -XDataKinds
71+-- >>> import Data.Aeson
72+
41-- | A list of definitions that can be used in references.
73-- | A list of definitions that can be used in references.
42−type Definitions = HashMap Text
74+type Definitions = InsOrdHashMap Text
43
75
44-- | This is the root document object for the API specification.
76-- | This is the root document object for the API specification.
45data Swagger = Swagger
77data Swagger = Swagger
@@ -71,7 +103,7 @@ data Swagger = Swagger
71 -- | The available paths and operations for the API.
103 -- | The available paths and operations for the API.
72 -- Holds the relative paths to the individual endpoints.
104 -- Holds the relative paths to the individual endpoints.
73 -- The path is appended to the @'basePath'@ in order to construct the full URL.
105 -- The path is appended to the @'basePath'@ in order to construct the full URL.
74− , _swaggerPaths :: HashMap FilePath PathItem
106+ , _swaggerPaths :: InsOrdHashMap FilePath PathItem
75
107
76 -- | An object to hold data types produced and consumed by operations.
108 -- | An object to hold data types produced and consumed by operations.
77 , _swaggerDefinitions :: Definitions Schema
109 , _swaggerDefinitions :: Definitions Schema
@@ -85,7 +117,7 @@ data Swagger = Swagger
85 , _swaggerResponses :: Definitions Response
117 , _swaggerResponses :: Definitions Response
86
118
87 -- | Security scheme definitions that can be used across the specification.
119 -- | Security scheme definitions that can be used across the specification.
88− , _swaggerSecurityDefinitions :: Definitions SecurityScheme
120+ , _swaggerSecurityDefinitions :: SecurityDefinitions
89
121
90 -- | A declaration of which security schemes are applied for the API as a whole.
122 -- | A declaration of which security schemes are applied for the API as a whole.
91 -- The list of values describes alternative security schemes that can be used
123 -- The list of values describes alternative security schemes that can be used
@@ -98,7 +130,7 @@ data Swagger = Swagger
98 -- Not all tags that are used by the Operation Object must be declared.
130 -- Not all tags that are used by the Operation Object must be declared.
99 -- The tags that are not declared may be organized randomly or based on the tools' logic.
131 -- The tags that are not declared may be organized randomly or based on the tools' logic.
100 -- Each tag name in the list MUST be unique.
132 -- Each tag name in the list MUST be unique.
101− , _swaggerTags :: [Tag]
133+ , _swaggerTags :: InsOrdHashSet Tag
102
134
103 -- | Additional external documentation.
135 -- | Additional external documentation.
104 , _swaggerExternalDocs :: Maybe ExternalDocs
136 , _swaggerExternalDocs :: Maybe ExternalDocs
@@ -150,12 +182,18 @@ data License = License
150 , _licenseUrl :: Maybe URL
182 , _licenseUrl :: Maybe URL
151 } deriving (Eq, Show, Generic, Data, Typeable)
183 } deriving (Eq, Show, Generic, Data, Typeable)
152
184
185+instance IsString License where
186+ fromString s = License (fromString s) Nothing
187+
153-- | The host (name or ip) serving the API. It MAY include a port.
188-- | The host (name or ip) serving the API. It MAY include a port.
154data Host = Host
189data Host = Host
155 { _hostName :: HostName -- ^ Host name.
190 { _hostName :: HostName -- ^ Host name.
156 , _hostPort :: Maybe PortNumber -- ^ Optional port.
191 , _hostPort :: Maybe PortNumber -- ^ Optional port.
157 } deriving (Eq, Show, Generic, Typeable)
192 } deriving (Eq, Show, Generic, Typeable)
158
193
194+instance IsString Host where
195+ fromString s = Host s Nothing
196+
159hostConstr :: Constr
197hostConstr :: Constr
160hostConstr = mkConstr hostDataType "Host" [] Prefix
198hostConstr = mkConstr hostDataType "Host" [] Prefix
161
199
@@ -214,7 +252,7 @@ data PathItem = PathItem
214data Operation = Operation
252data Operation = Operation
215 { -- | A list of tags for API documentation control.
253 { -- | A list of tags for API documentation control.
216 -- Tags can be used for logical grouping of operations by resources or any other qualifier.
254 -- Tags can be used for logical grouping of operations by resources or any other qualifier.
217− _operationTags :: [TagName]
255+ _operationTags :: InsOrdHashSet TagName
218
256
219 -- | A short summary of what the operation does.
257 -- | A short summary of what the operation does.
220 -- For maximum readability in the swagger-ui, this field SHOULD be less than 120 characters.
258 -- For maximum readability in the swagger-ui, this field SHOULD be less than 120 characters.
@@ -271,7 +309,7 @@ data Operation = Operation
271 } deriving (Eq, Show, Generic, Data, Typeable)
309 } deriving (Eq, Show, Generic, Data, Typeable)
272
310
273newtype MimeList = MimeList { getMimeList :: [MediaType] }
311newtype MimeList = MimeList { getMimeList :: [MediaType] }
274− deriving (Eq, Show, Monoid, Typeable)
312+ deriving (Eq, Show, Semigroup, Monoid, Typeable)
275
313
276mimeListConstr :: Constr
314mimeListConstr :: Constr
277mimeListConstr = mkConstr mimeListDataType "MimeList" ["getMimeList"] Prefix
315mimeListConstr = mkConstr mimeListDataType "MimeList" ["getMimeList"] Prefix
@@ -322,8 +360,8 @@ data ParamOtherSchema = ParamOtherSchema
322 -- Default value is @False@.
360 -- Default value is @False@.
323 , _paramOtherSchemaAllowEmptyValue :: Maybe Bool
361 , _paramOtherSchemaAllowEmptyValue :: Maybe Bool
324
362
325− , _paramOtherSchemaParamSchema :: ParamSchema ParamOtherSchema
363+ , _paramOtherSchemaParamSchema :: ParamSchema 'SwaggerKindParamOtherSchema
326− } deriving (Eq, Show, Generic, Data, Typeable)
364+ } deriving (Eq, Show, Generic, Typeable, Data)
327
365
328-- | Items for @'SwaggerArray'@ schemas.
366-- | Items for @'SwaggerArray'@ schemas.
329--
367--
@@ -336,9 +374,9 @@ data ParamOtherSchema = ParamOtherSchema
336--
374--
337-- @'SwaggerItemsArray'@ should be used to specify tuple @'Schema'@s.
375-- @'SwaggerItemsArray'@ should be used to specify tuple @'Schema'@s.
338data SwaggerItems t where
376data SwaggerItems t where
339− SwaggerItemsPrimitive :: Maybe (CollectionFormat t) -> ParamSchema t -> SwaggerItems t
377+ SwaggerItemsPrimitive :: Maybe (CollectionFormat k) -> ParamSchema k-> SwaggerItems k
340− SwaggerItemsObject :: Referenced Schema -> SwaggerItems Schema
378+ SwaggerItemsObject :: Referenced Schema -> SwaggerItems 'SwaggerKindSchema
341− SwaggerItemsArray :: [Referenced Schema] -> SwaggerItems Schema
379+ SwaggerItemsArray :: [Referenced Schema] -> SwaggerItems 'SwaggerKindSchema
342 deriving (Typeable)
380 deriving (Typeable)
343
381
344deriving instance Eq (SwaggerItems t)
382deriving instance Eq (SwaggerItems t)
@@ -348,17 +386,66 @@ deriving instance Show (SwaggerItems t)
348swaggerItemsPrimitiveConstr :: Constr
386swaggerItemsPrimitiveConstr :: Constr
349swaggerItemsPrimitiveConstr = mkConstr swaggerItemsDataType "SwaggerItemsPrimitive" [] Prefix
387swaggerItemsPrimitiveConstr = mkConstr swaggerItemsDataType "SwaggerItemsPrimitive" [] Prefix
350
388
389+swaggerItemsObjectConstr :: Constr
390+swaggerItemsObjectConstr = mkConstr swaggerItemsDataType "SwaggerItemsObject" [] Prefix
391+
392+swaggerItemsArrayConstr :: Constr
393+swaggerItemsArrayConstr = mkConstr swaggerItemsDataType "SwaggerItemsArray" [] Prefix
394+
351swaggerItemsDataType :: DataType
395swaggerItemsDataType :: DataType
352swaggerItemsDataType = mkDataType "Data.Swagger.SwaggerItems" [swaggerItemsPrimitiveConstr]
396swaggerItemsDataType = mkDataType "Data.Swagger.SwaggerItems" [swaggerItemsPrimitiveConstr]
353
397
398+-- Note: unfortunately we have to write these Data instances by hand,
399+-- to get better contexts / avoid duplicate name when using standalone deriving
400+
354−instance OVERLAPPABLE_ Data t => Data (SwaggerItems t) where
401+instance Data t => Data (SwaggerItems ('SwaggerKindNormal t)) where
402+ -- TODO: define gfoldl
355 gunfold k z c = case constrIndex c of
403 gunfold k z c = case constrIndex c of
356 1 -> k (k (z SwaggerItemsPrimitive))
404 1 -> k (k (z SwaggerItemsPrimitive))
357 _ -> error $ "Data.Data.gunfold: Constructor " ++ show c ++ " is not of type (SwaggerItems t)."
405 _ -> error $ "Data.Data.gunfold: Constructor " ++ show c ++ " is not of type (SwaggerItems t)."
358 toConstr _ = swaggerItemsPrimitiveConstr
406 toConstr _ = swaggerItemsPrimitiveConstr
359 dataTypeOf _ = swaggerItemsDataType
407 dataTypeOf _ = swaggerItemsDataType
360
408
409+-- SwaggerItems SwaggerKindParamOtherSchema can be constructed using SwaggerItemsPrimitive only
361−deriving instance Data (SwaggerItems Schema)
410+instance Data (SwaggerItems 'SwaggerKindParamOtherSchema) where
411+ -- TODO: define gfoldl
412+ gunfold k z c = case constrIndex c of
413+ 1 -> k (k (z SwaggerItemsPrimitive))
414+ _ -> error $ "Data.Data.gunfold: Constructor " ++ show c ++ " is not of type (SwaggerItems SwaggerKindParamOtherSchema)."
415+ toConstr _ = swaggerItemsPrimitiveConstr
416+ dataTypeOf _ = swaggerItemsDataType
417+
418+instance Data (SwaggerItems 'SwaggerKindSchema) where
419+ gfoldl _ _ (SwaggerItemsPrimitive _ _) = error $ " Data.Data.gfoldl: Constructor SwaggerItemsPrimitive used to construct SwaggerItems SwaggerKindSchema"
420+ gfoldl k z (SwaggerItemsObject ref) = z SwaggerItemsObject `k` ref
421+ gfoldl k z (SwaggerItemsArray ref) = z SwaggerItemsArray `k` ref
422+
423+ gunfold k z c = case constrIndex c of
424+ 2 -> k (z SwaggerItemsObject)
425+ 3 -> k (z SwaggerItemsArray)
426+ _ -> error $ "Data.Data.gunfold: Constructor " ++ show c ++ " is not of type (SwaggerItems SwaggerKindSchema)."
427+
428+ toConstr (SwaggerItemsPrimitive _ _) = error "Not supported"
429+ toConstr (SwaggerItemsObject _) = swaggerItemsObjectConstr
430+ toConstr (SwaggerItemsArray _) = swaggerItemsArrayConstr
431+
432+ dataTypeOf _ = swaggerItemsDataType
433+
434+-- | Type used as a kind to avoid overlapping instances.
435+data SwaggerKind t
436+ = SwaggerKindNormal t
437+ | SwaggerKindParamOtherSchema
438+ | SwaggerKindSchema
439+ deriving (Typeable)
440+
441+deriving instance Typeable 'SwaggerKindNormal
442+deriving instance Typeable 'SwaggerKindParamOtherSchema
443+deriving instance Typeable 'SwaggerKindSchema
444+
445+type family SwaggerKindType (k :: SwaggerKind *) :: *
446+type instance SwaggerKindType ('SwaggerKindNormal t) = t
447+type instance SwaggerKindType 'SwaggerKindSchema = Schema
448+type instance SwaggerKindType 'SwaggerKindParamOtherSchema = ParamOtherSchema
362
449
363data SwaggerType t where
450data SwaggerType t where
364 SwaggerString :: SwaggerType t
451 SwaggerString :: SwaggerType t
@@ -366,9 +453,9 @@ data SwaggerType t where
366 SwaggerInteger :: SwaggerType t
453 SwaggerInteger :: SwaggerType t
367 SwaggerBoolean :: SwaggerType t
454 SwaggerBoolean :: SwaggerType t
368 SwaggerArray :: SwaggerType t
455 SwaggerArray :: SwaggerType t
369− SwaggerFile :: SwaggerType ParamOtherSchema
456+ SwaggerFile :: SwaggerType 'SwaggerKindParamOtherSchema
370− SwaggerNull :: SwaggerType Schema
457+ SwaggerNull :: SwaggerType 'SwaggerKindSchema
371− SwaggerObject :: SwaggerType Schema
458+ SwaggerObject :: SwaggerType 'SwaggerKindSchema
372 deriving (Typeable)
459 deriving (Typeable)
373
460
374deriving instance Eq (SwaggerType t)
461deriving instance Eq (SwaggerType t)
@@ -377,33 +464,33 @@ deriving instance Show (SwaggerType t)
377swaggerTypeConstr :: Data (SwaggerType t) => SwaggerType t -> Constr
464swaggerTypeConstr :: Data (SwaggerType t) => SwaggerType t -> Constr
378swaggerTypeConstr t = mkConstr (dataTypeOf t) (show t) [] Prefix
465swaggerTypeConstr t = mkConstr (dataTypeOf t) (show t) [] Prefix
379
466
380−swaggerTypeDataType :: Data (SwaggerType t) => SwaggerType t -> DataType
467+swaggerTypeDataType :: {- Data (SwaggerType t) => -} SwaggerType t -> DataType
381swaggerTypeDataType _ = mkDataType "Data.Swagger.SwaggerType" swaggerTypeConstrs
468swaggerTypeDataType _ = mkDataType "Data.Swagger.SwaggerType" swaggerTypeConstrs
382
469
383−swaggerCommonTypes :: [SwaggerType t]
470+swaggerCommonTypes :: [SwaggerType k]
384swaggerCommonTypes = [SwaggerString, SwaggerNumber, SwaggerInteger, SwaggerBoolean, SwaggerArray]
471swaggerCommonTypes = [SwaggerString, SwaggerNumber, SwaggerInteger, SwaggerBoolean, SwaggerArray]
385
472
386−swaggerParamTypes :: [SwaggerType ParamOtherSchema]
473+swaggerParamTypes :: [SwaggerType 'SwaggerKindParamOtherSchema]
387swaggerParamTypes = swaggerCommonTypes ++ [SwaggerFile]
474swaggerParamTypes = swaggerCommonTypes ++ [SwaggerFile]
388
475
389−swaggerSchemaTypes :: [SwaggerType Schema]
476+swaggerSchemaTypes :: [SwaggerType 'SwaggerKindSchema]
390swaggerSchemaTypes = swaggerCommonTypes ++ [error "SwaggerFile is invalid SwaggerType Schema", SwaggerNull, SwaggerObject]
477swaggerSchemaTypes = swaggerCommonTypes ++ [error "SwaggerFile is invalid SwaggerType Schema", SwaggerNull, SwaggerObject]
391
478
392swaggerTypeConstrs :: [Constr]
479swaggerTypeConstrs :: [Constr]
393−swaggerTypeConstrs = map swaggerTypeConstr (swaggerCommonTypes :: [SwaggerType Schema])
480+swaggerTypeConstrs = map swaggerTypeConstr (swaggerCommonTypes :: [SwaggerType 'SwaggerKindSchema])
394 ++ [swaggerTypeConstr SwaggerFile, swaggerTypeConstr SwaggerNull, swaggerTypeConstr SwaggerObject]
481 ++ [swaggerTypeConstr SwaggerFile, swaggerTypeConstr SwaggerNull, swaggerTypeConstr SwaggerObject]
395
482
396−instance OVERLAPPABLE_ Typeable t => Data (SwaggerType t) where
483+instance Typeable t => Data (SwaggerType ('SwaggerKindNormal t)) where
397 gunfold = gunfoldEnum "SwaggerType" swaggerCommonTypes
484 gunfold = gunfoldEnum "SwaggerType" swaggerCommonTypes
398 toConstr = swaggerTypeConstr
485 toConstr = swaggerTypeConstr
399 dataTypeOf = swaggerTypeDataType
486 dataTypeOf = swaggerTypeDataType
400
487
401−instance OVERLAPPABLE_ Data (SwaggerType ParamOtherSchema) where
488+instance Data (SwaggerType 'SwaggerKindParamOtherSchema) where
402 gunfold = gunfoldEnum "SwaggerType ParamOtherSchema" swaggerParamTypes
489 gunfold = gunfoldEnum "SwaggerType ParamOtherSchema" swaggerParamTypes
403 toConstr = swaggerTypeConstr
490 toConstr = swaggerTypeConstr
404 dataTypeOf = swaggerTypeDataType
491 dataTypeOf = swaggerTypeDataType
405
492
406−instance OVERLAPPABLE_ Data (SwaggerType Schema) where
493+instance Data (SwaggerType 'SwaggerKindSchema) where
407 gunfold = gunfoldEnum "SwaggerType Schema" swaggerSchemaTypes
494 gunfold = gunfoldEnum "SwaggerType Schema" swaggerSchemaTypes
408 toConstr = swaggerTypeConstr
495 toConstr = swaggerTypeConstr
409 dataTypeOf = swaggerTypeDataType
496 dataTypeOf = swaggerTypeDataType
@@ -443,7 +530,7 @@ data CollectionFormat t where
443 -- Corresponds to multiple parameter instances
530 -- Corresponds to multiple parameter instances
444 -- instead of multiple values for a single instance @foo=bar&foo=baz@.
531 -- instead of multiple values for a single instance @foo=bar&foo=baz@.
445 -- This is valid only for parameters in @'ParamQuery'@ or @'ParamFormData'@.
532 -- This is valid only for parameters in @'ParamQuery'@ or @'ParamFormData'@.
446− CollectionMulti :: CollectionFormat ParamOtherSchema
533+ CollectionMulti :: CollectionFormat 'SwaggerKindParamOtherSchema
447 deriving (Typeable)
534 deriving (Typeable)
448
535
449deriving instance Eq (CollectionFormat t)
536deriving instance Eq (CollectionFormat t)
@@ -459,12 +546,12 @@ collectionFormatDataType = mkDataType "Data.Swagger.CollectionFormat" $
459collectionCommonFormats :: [CollectionFormat t]
546collectionCommonFormats :: [CollectionFormat t]
460collectionCommonFormats = [ CollectionCSV, CollectionSSV, CollectionTSV, CollectionPipes ]
547collectionCommonFormats = [ CollectionCSV, CollectionSSV, CollectionTSV, CollectionPipes ]
461
548
462−instance OVERLAPPABLE_ Data t => Data (CollectionFormat t) where
549+instance Data t => Data (CollectionFormat ('SwaggerKindNormal t)) where
463 gunfold = gunfoldEnum "CollectionFormat" collectionCommonFormats
550 gunfold = gunfoldEnum "CollectionFormat" collectionCommonFormats
464 toConstr = collectionFormatConstr
551 toConstr = collectionFormatConstr
465 dataTypeOf _ = collectionFormatDataType
552 dataTypeOf _ = collectionFormatDataType
466
553
467−deriving instance OVERLAPPABLE_ Data (CollectionFormat ParamOtherSchema)
554+deriving instance Data (CollectionFormat 'SwaggerKindParamOtherSchema)
468
555
469type ParamName = Text
556type ParamName = Text
470
557
@@ -473,9 +560,9 @@ data Schema = Schema
473 , _schemaDescription :: Maybe Text
560 , _schemaDescription :: Maybe Text
474 , _schemaRequired :: [ParamName]
561 , _schemaRequired :: [ParamName]
475
562
476− , _schemaAllOf :: Maybe [Schema]
563+ , _schemaAllOf :: Maybe [Referenced Schema]
477− , _schemaProperties :: HashMap Text (Referenced Schema)
564+ , _schemaProperties :: InsOrdHashMap Text (Referenced Schema)
478− , _schemaAdditionalProperties :: Maybe Schema
565+ , _schemaAdditionalProperties :: Maybe AdditionalProperties
479
566
480 , _schemaDiscriminator :: Maybe Text
567 , _schemaDiscriminator :: Maybe Text
481 , _schemaReadOnly :: Maybe Bool
568 , _schemaReadOnly :: Maybe Bool
@@ -486,7 +573,7 @@ data Schema = Schema
486 , _schemaMaxProperties :: Maybe Integer
573 , _schemaMaxProperties :: Maybe Integer
487 , _schemaMinProperties :: Maybe Integer
574 , _schemaMinProperties :: Maybe Integer
488
575
489− , _schemaParamSchema :: ParamSchema Schema
576+ , _schemaParamSchema :: ParamSchema 'SwaggerKindSchema
490 } deriving (Eq, Show, Generic, Data, Typeable)
577 } deriving (Eq, Show, Generic, Data, Typeable)
491
578
492-- | A @'Schema'@ with an optional name.
579-- | A @'Schema'@ with an optional name.
@@ -499,7 +586,7 @@ data NamedSchema = NamedSchema
499-- | Regex pattern for @string@ type.
586-- | Regex pattern for @string@ type.
500type Pattern = Text
587type Pattern = Text
501
588
502−data ParamSchema t = ParamSchema
589+data ParamSchema (t :: SwaggerKind *) = ParamSchema
503 { -- | Declares the value of the parameter that the server will use if none is provided,
590 { -- | Declares the value of the parameter that the server will use if none is provided,
504 -- for example a @"count"@ to control the number of results per page might default to @100@
591 -- for example a @"count"@ to control the number of results per page might default to @100@
505 -- if not supplied by the client in the request.
592 -- if not supplied by the client in the request.
@@ -507,7 +594,7 @@ data ParamSchema t = ParamSchema
507 -- Unlike JSON Schema this value MUST conform to the defined type for this parameter.
594 -- Unlike JSON Schema this value MUST conform to the defined type for this parameter.
508 _paramSchemaDefault :: Maybe Value
595 _paramSchemaDefault :: Maybe Value
509
596
510− , _paramSchemaType :: SwaggerType t
597+ , _paramSchemaType :: Maybe (SwaggerType t)
511 , _paramSchemaFormat :: Maybe Format
598 , _paramSchemaFormat :: Maybe Format
512 , _paramSchemaItems :: Maybe (SwaggerItems t)
599 , _paramSchemaItems :: Maybe (SwaggerItems t)
513 , _paramSchemaMaximum :: Maybe Scientific
600 , _paramSchemaMaximum :: Maybe Scientific
@@ -524,7 +611,7 @@ data ParamSchema t = ParamSchema
524 , _paramSchemaMultipleOf :: Maybe Scientific
611 , _paramSchemaMultipleOf :: Maybe Scientific
525 } deriving (Eq, Show, Generic, Typeable)
612 } deriving (Eq, Show, Generic, Typeable)
526
613
527−deriving instance (Data t, Data (SwaggerType t), Data (SwaggerItems t)) => Data (ParamSchema t)
614+deriving instance (Typeable k, Data (Maybe (SwaggerType k)), Data (SwaggerItems k)) => Data (ParamSchema k)
528
615
529data Xml = Xml
616data Xml = Xml
530 { -- | Replaces the name of the element/attribute used for the described schema property.
617 { -- | Replaces the name of the element/attribute used for the described schema property.
@@ -566,7 +653,7 @@ data Responses = Responses
566
653
567 -- | Any HTTP status code can be used as the property name (one property per HTTP status code).
654 -- | Any HTTP status code can be used as the property name (one property per HTTP status code).
568 -- Describes the expected response for those HTTP status codes.
655 -- Describes the expected response for those HTTP status codes.
569− , _responsesResponses :: HashMap HttpStatusCode (Referenced Response)
656+ , _responsesResponses :: InsOrdHashMap HttpStatusCode (Referenced Response)
570 } deriving (Eq, Show, Generic, Data, Typeable)
657 } deriving (Eq, Show, Generic, Data, Typeable)
571
658
572type HttpStatusCode = Int
659type HttpStatusCode = Int
@@ -585,19 +672,22 @@ data Response = Response
585 , _responseSchema :: Maybe (Referenced Schema)
672 , _responseSchema :: Maybe (Referenced Schema)
586
673
587 -- | A list of headers that are sent with the response.
674 -- | A list of headers that are sent with the response.
588− , _responseHeaders :: HashMap HeaderName Header
675+ , _responseHeaders :: InsOrdHashMap HeaderName Header
589
676
590 -- | An example of the response message.
677 -- | An example of the response message.
591 , _responseExamples :: Maybe Example
678 , _responseExamples :: Maybe Example
592 } deriving (Eq, Show, Generic, Data, Typeable)
679 } deriving (Eq, Show, Generic, Data, Typeable)
593
680
681+instance IsString Response where
682+ fromString s = Response (fromString s) Nothing mempty Nothing
683+
594type HeaderName = Text
684type HeaderName = Text
595
685
596data Header = Header
686data Header = Header
597 { -- | A short description of the header.
687 { -- | A short description of the header.
598 _headerDescription :: Maybe Text
688 _headerDescription :: Maybe Text
599
689
600− , _headerParamSchema :: ParamSchema Header
690+ , _headerParamSchema :: ParamSchema ('SwaggerKindNormal Header)
601 } deriving (Eq, Show, Generic, Data, Typeable)
691 } deriving (Eq, Show, Generic, Data, Typeable)
602
692
603data Example = Example { getExample :: Map MediaType Value }
693data Example = Example { getExample :: Map MediaType Value }
@@ -648,7 +738,7 @@ data OAuth2Params = OAuth2Params
648 _oauth2Flow :: OAuth2Flow
738 _oauth2Flow :: OAuth2Flow
649
739
650 -- | The available scopes for the OAuth2 security scheme.
740 -- | The available scopes for the OAuth2 security scheme.
651− , _oauth2Scopes :: HashMap Text Text
741+ , _oauth2Scopes :: InsOrdHashMap Text Text
652 } deriving (Eq, Show, Generic, Data, Typeable)
742 } deriving (Eq, Show, Generic, Data, Typeable)
653
743
654data SecuritySchemeType
744data SecuritySchemeType
@@ -665,12 +755,28 @@ data SecurityScheme = SecurityScheme
665 , _securitySchemeDescription :: Maybe Text
755 , _securitySchemeDescription :: Maybe Text
666 } deriving (Eq, Show, Generic, Data, Typeable)
756 } deriving (Eq, Show, Generic, Data, Typeable)
667
757
758+
759+-- | merge scopes of two OAuth2 security schemes when their flows are identical.
760+-- In other case returns first security scheme
761+mergeSecurityScheme :: SecurityScheme -> SecurityScheme -> SecurityScheme
762+mergeSecurityScheme s1@(SecurityScheme (SecuritySchemeOAuth2 (OAuth2Params flow1 scopes1)) desc)
763+ s2@(SecurityScheme (SecuritySchemeOAuth2 (OAuth2Params flow2 scopes2)) _)
764+ = if flow1 == flow2 then
765+ SecurityScheme (SecuritySchemeOAuth2 (OAuth2Params flow1 (scopes1 <> scopes2))) desc
766+ else
767+ s1
768+mergeSecurityScheme s1 _ = s1
769+
770+newtype SecurityDefinitions
771+ = SecurityDefinitions (Definitions SecurityScheme)
772+ deriving (Eq, Show, Generic, Data, Typeable)
773+
668-- | Lists the required security schemes to execute this operation.
774-- | Lists the required security schemes to execute this operation.
669-- The object can have multiple security schemes declared in it which are all required
775-- The object can have multiple security schemes declared in it which are all required
670-- (that is, there is a logical AND between the schemes).
776-- (that is, there is a logical AND between the schemes).
671newtype SecurityRequirement = SecurityRequirement
777newtype SecurityRequirement = SecurityRequirement
672− { getSecurityRequirement :: HashMap Text [Text]
778+ { getSecurityRequirement :: InsOrdHashMap Text [Text]
673− } deriving (Eq, Read, Show, Monoid, ToJSON, FromJSON, Data, Typeable)
779+ } deriving (Eq, Read, Show, Semigroup, Monoid, ToJSON, FromJSON, Data, Typeable)
674
780
675-- | Tag name.
781-- | Tag name.
676type TagName = Text
782type TagName = Text
@@ -687,7 +793,12 @@ data Tag = Tag
687
793
688 -- | Additional external documentation for this tag.
794 -- | Additional external documentation for this tag.
689 , _tagExternalDocs :: Maybe ExternalDocs
795 , _tagExternalDocs :: Maybe ExternalDocs
690− } deriving (Eq, Show, Generic, Data, Typeable)
796+ } deriving (Eq, Ord, Show, Generic, Data, Typeable)
797+
798+instance Hashable Tag
799+
800+instance IsString Tag where
801+ fromString s = Tag (fromString s) Nothing Nothing
691
802
692-- | Allows referencing an external resource for extended documentation.
803-- | Allows referencing an external resource for extended documentation.
693data ExternalDocs = ExternalDocs
804data ExternalDocs = ExternalDocs
@@ -697,7 +808,9 @@ data ExternalDocs = ExternalDocs
697
808
698 -- | The URL for the target documentation.
809 -- | The URL for the target documentation.
699 , _externalDocsUrl :: URL
810 , _externalDocsUrl :: URL
700− } deriving (Eq, Show, Generic, Data, Typeable)
811+ } deriving (Eq, Ord, Show, Generic, Data, Typeable)
812+
813+instance Hashable ExternalDocs
701
814
702-- | A simple object to allow referencing other definitions in the specification.
815-- | A simple object to allow referencing other definitions in the specification.
703-- It can be used to reference parameters and responses that are defined at the top level for reuse.
816-- It can be used to reference parameters and responses that are defined at the top level for reuse.
@@ -707,69 +820,116 @@ newtype Reference = Reference { getReference :: Text }
707data Referenced a
820data Referenced a
708 = Ref Reference
821 = Ref Reference
709 | Inline a
822 | Inline a
710− deriving (Eq, Show, Data, Typeable)
823+ deriving (Eq, Show, Functor, Data, Typeable)
824+
825+instance IsString a => IsString (Referenced a) where
826+ fromString = Inline . fromString
827+
828+newtype URL = URL { getUrl :: Text } deriving (Eq, Ord, Show, Hashable, ToJSON, FromJSON, Data, Typeable)
711
829
830+data AdditionalProperties
831+ = AdditionalPropertiesAllowed Bool
832+ | AdditionalPropertiesSchema (Referenced Schema)
712−newtype URL = URL { getUrl :: Text } deriving (Eq, Show, ToJSON, FromJSON, Data, Typeable)
833+ deriving (Eq, Show, Data, Typeable)
713
834
714-- =======================================================================
835-- =======================================================================
715-- Monoid instances
836-- Monoid instances
716-- =======================================================================
837-- =======================================================================
717
838
839+instance Semigroup Swagger where
840+ (<>) = genericMappend
718instance Monoid Swagger where
841instance Monoid Swagger where
719 mempty = genericMempty
842 mempty = genericMempty
720− mappend = genericMappend
843+ mappend = (<>)
721
844
845+instance Semigroup Info where
846+ (<>) = genericMappend
722instance Monoid Info where
847instance Monoid Info where
723 mempty = genericMempty
848 mempty = genericMempty
724− mappend = genericMappend
849+ mappend = (<>)
725
850
851+instance Semigroup Contact where
852+ (<>) = genericMappend
726instance Monoid Contact where
853instance Monoid Contact where
727 mempty = genericMempty
854 mempty = genericMempty
728− mappend = genericMappend
855+ mappend = (<>)
729
856
857+instance Semigroup PathItem where
858+ (<>) = genericMappend
730instance Monoid PathItem where
859instance Monoid PathItem where
731 mempty = genericMempty
860 mempty = genericMempty
732− mappend = genericMappend
861+ mappend = (<>)
733
862
863+instance Semigroup Schema where
864+ (<>) = genericMappend
734instance Monoid Schema where
865instance Monoid Schema where
735 mempty = genericMempty
866 mempty = genericMempty
736− mappend = genericMappend
867+ mappend = (<>)
737
868
869+instance Semigroup (ParamSchema t) where
870+ (<>) = genericMappend
738instance Monoid (ParamSchema t) where
871instance Monoid (ParamSchema t) where
739 mempty = genericMempty
872 mempty = genericMempty
740− mappend = genericMappend
873+ mappend = (<>)
741
874
875+instance Semigroup Param where
876+ (<>) = genericMappend
742instance Monoid Param where
877instance Monoid Param where
743 mempty = genericMempty
878 mempty = genericMempty
744− mappend = genericMappend
879+ mappend = (<>)
745
880
881+instance Semigroup ParamOtherSchema where
882+ (<>) = genericMappend
746instance Monoid ParamOtherSchema where
883instance Monoid ParamOtherSchema where
747 mempty = genericMempty
884 mempty = genericMempty
748− mappend = genericMappend
885+ mappend = (<>)
749
886
887+instance Semigroup Header where
888+ (<>) = genericMappend
750instance Monoid Header where
889instance Monoid Header where
751 mempty = genericMempty
890 mempty = genericMempty
752− mappend = genericMappend
891+ mappend = (<>)
753
892
893+instance Semigroup Responses where
894+ (<>) = genericMappend
754instance Monoid Responses where
895instance Monoid Responses where
755 mempty = genericMempty
896 mempty = genericMempty
756− mappend = genericMappend
897+ mappend = (<>)
757
898
899+instance Semigroup Response where
900+ (<>) = genericMappend
758instance Monoid Response where
901instance Monoid Response where
759 mempty = genericMempty
902 mempty = genericMempty
760− mappend = genericMappend
903+ mappend = (<>)
761
904
905+instance Semigroup ExternalDocs where
906+ (<>) = genericMappend
762instance Monoid ExternalDocs where
907instance Monoid ExternalDocs where
763 mempty = genericMempty
908 mempty = genericMempty
764− mappend = genericMappend
909+ mappend = (<>)
765
910
911+instance Semigroup Operation where
912+ (<>) = genericMappend
766instance Monoid Operation where
913instance Monoid Operation where
767 mempty = genericMempty
914 mempty = genericMempty
768− mappend = genericMappend
915+ mappend = (<>)
769
916
917+instance Semigroup Example where
918+ (<>) = genericMappend
770instance Monoid Example where
919instance Monoid Example where
771 mempty = genericMempty
920 mempty = genericMempty
772− mappend = genericMappend
921+ mappend = (<>)
922+
923+instance Semigroup SecurityScheme where
924+ (<>) = mergeSecurityScheme
925+
926+instance Semigroup SecurityDefinitions where
927+ (SecurityDefinitions sd1) <> (SecurityDefinitions sd2) =
928+ SecurityDefinitions $ InsOrdHashMap.unionWith (<>) sd1 sd2
929+
930+instance Monoid SecurityDefinitions where
931+ mempty = SecurityDefinitions $ InsOrdHashMap.empty
932+ mappend = (<>)
773
933
774-- =======================================================================
934-- =======================================================================
775-- SwaggerMonoid helper instances
935-- SwaggerMonoid helper instances
@@ -785,6 +945,8 @@ instance SwaggerMonoid Responses
785instance SwaggerMonoid Response
945instance SwaggerMonoid Response
786instance SwaggerMonoid ExternalDocs
946instance SwaggerMonoid ExternalDocs
787instance SwaggerMonoid Operation
947instance SwaggerMonoid Operation
948+instance SwaggerMonoid SecurityDefinitions
949+instance (Eq a, Hashable a) => SwaggerMonoid (InsOrdHashSet a)
788
950
789instance SwaggerMonoid MimeList
951instance SwaggerMonoid MimeList
790deriving instance SwaggerMonoid URL
952deriving instance SwaggerMonoid URL
@@ -797,13 +959,13 @@ instance SwaggerMonoid ParamLocation where
797 swaggerMempty = ParamQuery
959 swaggerMempty = ParamQuery
798 swaggerMappend _ y = y
960 swaggerMappend _ y = y
799
961
800−instance OVERLAPPING_ SwaggerMonoid (HashMap FilePath PathItem) where
962+instance OVERLAPPING_ SwaggerMonoid (InsOrdHashMap FilePath PathItem) where
801− swaggerMempty = HashMap.empty
963+ swaggerMempty = InsOrdHashMap.empty
802− swaggerMappend = HashMap.unionWith mappend
964+ swaggerMappend = InsOrdHashMap.unionWith mappend
803
965
804instance Monoid a => SwaggerMonoid (Referenced a) where
966instance Monoid a => SwaggerMonoid (Referenced a) where
805 swaggerMempty = Inline mempty
967 swaggerMempty = Inline mempty
806− swaggerMappend (Inline x) (Inline y) = Inline (x <> y)
968+ swaggerMappend (Inline x) (Inline y) = Inline (mappend x y)
807 swaggerMappend _ y = y
969 swaggerMappend _ y = y
808
970
809instance SwaggerMonoid ParamAnySchema where
971instance SwaggerMonoid ParamAnySchema where
@@ -897,7 +1059,8 @@ instance ToJSON OAuth2Flow where
897 , "tokenUrl" .= tokenUrl ]
1059 , "tokenUrl" .= tokenUrl ]
898
1060
899instance ToJSON OAuth2Params where
1061instance ToJSON OAuth2Params where
900− toJSON = omitEmpties . genericToJSONWithSub "flow" (jsonPrefix "oauth2")
1062+ toJSON = sopSwaggerGenericToJSON
1063+ DEFINE_TOENCODING
901
1064
902instance ToJSON SecuritySchemeType where
1065instance ToJSON SecuritySchemeType where
903 toJSON SecuritySchemeBasic
1066 toJSON SecuritySchemeBasic
@@ -910,28 +1073,37 @@ instance ToJSON SecuritySchemeType where
910 <+> object [ "type" .= ("oauth2" :: Text) ]
1073 <+> object [ "type" .= ("oauth2" :: Text) ]
911
1074
912instance ToJSON Swagger where
1075instance ToJSON Swagger where
913− toJSON = omitEmpties . addVersion . genericToJSON (jsonPrefix "swagger")
1076+ toJSON = sopSwaggerGenericToJSON
914− where
1077+ DEFINE_TOENCODING
915− addVersion (Object o) = Object (HashMap.insert "swagger" "2.0" o)
916− addVersion _ = error "impossible"
917
1078
918instance ToJSON SecurityScheme where
1079instance ToJSON SecurityScheme where
919− toJSON = genericToJSONWithSub "type" (jsonPrefix "securityScheme")
1080+ toJSON = sopSwaggerGenericToJSON
1081+ DEFINE_TOENCODING
920
1082
921instance ToJSON Schema where
1083instance ToJSON Schema where
922− toJSON = omitEmptiesExcept f . genericToJSONWithSub "paramSchema" (jsonPrefix "schema")
1084+ toJSON = sopSwaggerGenericToJSON
923− where
1085+ DEFINE_TOENCODING
924− f "items" (Array _) = True
925− f _ _ = False
926
1086
927instance ToJSON Header where
1087instance ToJSON Header where
928− toJSON = genericToJSONWithSub "paramSchema" (jsonPrefix "header")
1088+ toJSON = sopSwaggerGenericToJSON
1089+ DEFINE_TOENCODING
929
1090
1091+-- | As for nullary schema for 0-arity type constructors, see
1092+-- <https://github.com/GetShopTV/swagger2/issues/167>.
1093+--
1094+-- >>> encode (SwaggerItemsArray [])
1095+-- "{\"example\":[],\"items\":{},\"maxItems\":0}"
1096+--
930−instance ToJSON (SwaggerItems t) where
1097+instance ToJSON (ParamSchema t) => ToJSON (SwaggerItems t) where
931 toJSON (SwaggerItemsPrimitive fmt schema) = object
1098 toJSON (SwaggerItemsPrimitive fmt schema) = object
932 [ "collectionFormat" .= fmt
1099 [ "collectionFormat" .= fmt
933 , "items" .= schema ]
1100 , "items" .= schema ]
934 toJSON (SwaggerItemsObject x) = object [ "items" .= x ]
1101 toJSON (SwaggerItemsObject x) = object [ "items" .= x ]
1102+ toJSON (SwaggerItemsArray []) = object
1103+ [ "items" .= object []
1104+ , "maxItems" .= (0 :: Int)
1105+ , "example" .= Array mempty
1106+ ]
935 toJSON (SwaggerItemsArray x) = object [ "items" .= x ]
1107 toJSON (SwaggerItemsArray x) = object [ "items" .= x ]
936
1108
937instance ToJSON Host where
1109instance ToJSON Host where
@@ -944,31 +1116,39 @@ instance ToJSON MimeList where
944 toJSON (MimeList xs) = toJSON (map show xs)
1116 toJSON (MimeList xs) = toJSON (map show xs)
945
1117
946instance ToJSON Param where
1118instance ToJSON Param where
947− toJSON = genericToJSONWithSub "schema" (jsonPrefix "param")
1119+ toJSON = sopSwaggerGenericToJSON
1120+ DEFINE_TOENCODING
948
1121
949instance ToJSON ParamAnySchema where
1122instance ToJSON ParamAnySchema where
950 toJSON (ParamBody s) = object [ "in" .= ("body" :: Text), "schema" .= s ]
1123 toJSON (ParamBody s) = object [ "in" .= ("body" :: Text), "schema" .= s ]
951 toJSON (ParamOther s) = toJSON s
1124 toJSON (ParamOther s) = toJSON s
952
1125
953instance ToJSON ParamOtherSchema where
1126instance ToJSON ParamOtherSchema where
954− toJSON = genericToJSONWithSub "paramSchema" (jsonPrefix "paramOtherSchema")
1127+ toJSON = sopSwaggerGenericToJSON
1128+ DEFINE_TOENCODING
955
1129
956instance ToJSON Responses where
1130instance ToJSON Responses where
957− toJSON (Responses def rs) = omitEmpties $
1131+ toJSON = sopSwaggerGenericToJSON
958− toJSON (hashMapMapKeys show rs) <+> object [ "default" .= def ]
1132+ DEFINE_TOENCODING
959
1133
960instance ToJSON Response where
1134instance ToJSON Response where
961− toJSON = omitEmpties . genericToJSON (jsonPrefix "response")
1135+ toJSON = sopSwaggerGenericToJSON
1136+ DEFINE_TOENCODING
962
1137
963instance ToJSON Operation where
1138instance ToJSON Operation where
964− toJSON = omitEmpties . genericToJSON (jsonPrefix "operation")
1139+ toJSON = sopSwaggerGenericToJSON
1140+ DEFINE_TOENCODING
965
1141
966instance ToJSON PathItem where
1142instance ToJSON PathItem where
967− toJSON = omitEmpties . genericToJSON (jsonPrefix "pathItem")
1143+ toJSON = sopSwaggerGenericToJSON
1144+ DEFINE_TOENCODING
968
1145
969instance ToJSON Example where
1146instance ToJSON Example where
970 toJSON = toJSON . Map.mapKeys show . getExample
1147 toJSON = toJSON . Map.mapKeys show . getExample
971
1148
1149+instance ToJSON SecurityDefinitions where
1150+ toJSON (SecurityDefinitions sd) = toJSON sd
1151+
972instance ToJSON Reference where
1152instance ToJSON Reference where
973 toJSON (Reference ref) = object [ "$ref" .= ref ]
1153 toJSON (Reference ref) = object [ "$ref" .= ref ]
974
1154
@@ -997,11 +1177,14 @@ instance ToJSON (CollectionFormat t) where
997 toJSON CollectionPipes = "pipes"
1177 toJSON CollectionPipes = "pipes"
998 toJSON CollectionMulti = "multi"
1178 toJSON CollectionMulti = "multi"
999
1179
1000−instance ToJSON (ParamSchema t) where
1180+instance ToJSON (ParamSchema k) where
1001− toJSON = omitEmptiesExcept f . genericToJSONWithSub "items" (jsonPrefix "paramSchema")
1181+ -- TODO: this is a bit fishy, why we need sub object only in `ToJSON`?
1002− where
1182+ toJSON = sopSwaggerGenericToJSONWithOpts $
1003− f "items" (Array _) = True
1183+ mkSwaggerAesonOptions "paramSchema" & saoSubObject ?~ "items"
1004− f _ _ = False
1184+
1185+instance ToJSON AdditionalProperties where
1186+ toJSON (AdditionalPropertiesAllowed b) = toJSON b
1187+ toJSON (AdditionalPropertiesSchema s) = toJSON s
1005
1188
1006-- =======================================================================
1189-- =======================================================================
1007-- Manual FromJSON instances
1190-- Manual FromJSON instances
@@ -1021,7 +1204,7 @@ instance FromJSON OAuth2Flow where
1021 parseJSON _ = empty
1204 parseJSON _ = empty
1022
1205
1023instance FromJSON OAuth2Params where
1206instance FromJSON OAuth2Params where
1024− parseJSON = genericParseJSONWithSub "flow" (jsonPrefix "oauth2")
1207+ parseJSON = sopSwaggerGenericParseJSON
1025
1208
1026instance FromJSON SecuritySchemeType where
1209instance FromJSON SecuritySchemeType where
1027 parseJSON js@(Object o) = do
1210 parseJSON js@(Object o) = do
@@ -1034,57 +1217,65 @@ instance FromJSON SecuritySchemeType where
1034 parseJSON _ = empty
1217 parseJSON _ = empty
1035
1218
1036instance FromJSON Swagger where
1219instance FromJSON Swagger where
1037− parseJSON js@(Object o) = do
1220+ parseJSON = sopSwaggerGenericParseJSON
1038− (version :: Text) <- o .: "swagger"
1039− when (version /= "2.0") empty
1040− (genericParseJSON (jsonPrefix "swagger")
1041− `withDefaults` [ "consumes" .= (mempty :: MimeList)
1042− , "produces" .= (mempty :: MimeList)
1043− , "security" .= ([] :: [SecurityRequirement])
1044− , "tags" .= ([] :: [Tag])
1045− , "definitions" .= (mempty :: Definitions Schema)
1046− , "parameters" .= (mempty :: Definitions Param)
1047− , "responses" .= (mempty :: Definitions Response)
1048− , "securityDefinitions" .= (mempty :: Definitions SecurityScheme)
1049− ] ) js
1050− parseJSON _ = empty
1051
1221
1052instance FromJSON SecurityScheme where
1222instance FromJSON SecurityScheme where
1053− parseJSON = genericParseJSONWithSub "type" (jsonPrefix "securityScheme")
1223+ parseJSON = sopSwaggerGenericParseJSON
1054
1224
1055instance FromJSON Schema where
1225instance FromJSON Schema where
1056− parseJSON = genericParseJSONWithSub "paramSchema" (jsonPrefix "schema")
1226+ parseJSON = fmap nullaryCleanup . sopSwaggerGenericParseJSON
1057− `withDefaults` [ "properties" .= (mempty :: HashMap Text Schema)
1227+ where nullaryCleanup :: Schema -> Schema
1058− , "required" .= ([] :: [ParamName]) ]
1228+ nullaryCleanup s@Schema{_schemaParamSchema=ps} =
1229+ if _paramSchemaItems ps == Just (SwaggerItemsArray [])
1230+ then s { _schemaExample = Nothing
1231+ , _schemaParamSchema = ps { _paramSchemaMaxItems = Nothing } }
1232+ else s
1059
1233
1060instance FromJSON Header where
1234instance FromJSON Header where
1061− parseJSON = genericParseJSONWithSub "paramSchema" (jsonPrefix "header")
1235+ parseJSON = sopSwaggerGenericParseJSON
1062
1236
1063−instance OVERLAPPABLE_ (FromJSON (CollectionFormat t), FromJSON (ParamSchema t)) => FromJSON (SwaggerItems t) where
1237+instance (FromJSON (CollectionFormat ('SwaggerKindNormal t)), FromJSON (ParamSchema ('SwaggerKindNormal t))) => FromJSON (SwaggerItems ('SwaggerKindNormal t)) where
1064 parseJSON = withObject "SwaggerItemsPrimitive" $ \o -> SwaggerItemsPrimitive
1238 parseJSON = withObject "SwaggerItemsPrimitive" $ \o -> SwaggerItemsPrimitive
1065 <$> o .:? "collectionFormat"
1239 <$> o .:? "collectionFormat"
1066 <*> (o .: "items" >>= parseJSON)
1240 <*> (o .: "items" >>= parseJSON)
1067
1241
1242+instance FromJSON (SwaggerItems 'SwaggerKindParamOtherSchema) where
1243+ parseJSON = withObject "SwaggerItemsPrimitive" $ \o -> SwaggerItemsPrimitive
1244+ <$> o .:? "collectionFormat"
1245+ <*> ((o .: "items" >>= parseJSON) <|> fail ("foo" ++ show o))
1246+
1247+-- |
1248+--
1249+-- >>> decode "{}" :: Maybe (SwaggerItems 'SwaggerKindSchema)
1250+-- Just (SwaggerItemsArray [])
1251+--
1252+-- >>> eitherDecode "{\"$ref\":\"#/definitions/example\"}" :: Either String (SwaggerItems 'SwaggerKindSchema)
1253+-- Right (SwaggerItemsObject (Ref (Reference {getReference = "example"})))
1254+--
1255+-- >>> eitherDecode "[{\"$ref\":\"#/definitions/example\"}]" :: Either String (SwaggerItems 'SwaggerKindSchema)
1256+-- Right (SwaggerItemsArray [Ref (Reference {getReference = "example"})])
1257+--
1068−instance OVERLAPPABLE_ FromJSON (SwaggerItems Schema) where
1258+instance FromJSON (SwaggerItems 'SwaggerKindSchema) where
1259+ parseJSON js@(Object obj)
1260+ | null obj = pure $ SwaggerItemsArray [] -- Nullary schema.
1069− parseJSON js@(Object _) = SwaggerItemsObject <$> parseJSON js
1261+ | otherwise = SwaggerItemsObject <$> parseJSON js
1070 parseJSON js@(Array _) = SwaggerItemsArray <$> parseJSON js
1262 parseJSON js@(Array _) = SwaggerItemsArray <$> parseJSON js
1071 parseJSON _ = empty
1263 parseJSON _ = empty
1072
1264
1073instance FromJSON Host where
1265instance FromJSON Host where
1074− parseJSON (String s) =
1266+ parseJSON (String s) = case map Text.unpack $ Text.split (== ':') s of
1075− case fromInteger <$> readMaybe portStr of
1267+ [host] -> return $ Host host Nothing
1076− Nothing | not (null portStr) -> fail $ "Invalid port `" ++ portStr ++ "'"
1268+ [host, port] -> case readMaybe port of
1077− mport -> pure $ Host host mport
1269+ Nothing -> fail $ "Invalid port `" ++ port ++ "'"
1078− where
1270+ Just p -> return $ Host host (Just (fromInteger p))
1079− (hostText, portText) = Text.breakOn ":" s
1271+ _ -> fail $ "Invalid host `" ++ Text.unpack s ++ "'"
1080− [host, portStr] = map Text.unpack [hostText, portText]
1081 parseJSON _ = empty
1272 parseJSON _ = empty
1082
1273
1083instance FromJSON MimeList where
1274instance FromJSON MimeList where
1084 parseJSON js = (MimeList . map fromString) <$> parseJSON js
1275 parseJSON js = (MimeList . map fromString) <$> parseJSON js
1085
1276
1086instance FromJSON Param where
1277instance FromJSON Param where
1087− parseJSON = genericParseJSONWithSub "schema" (jsonPrefix "param")
1278+ parseJSON = sopSwaggerGenericParseJSON
1088
1279
1089instance FromJSON ParamAnySchema where
1280instance FromJSON ParamAnySchema where
1090 parseJSON js@(Object o) = do
1281 parseJSON js@(Object o) = do
@@ -1097,12 +1288,12 @@ instance FromJSON ParamAnySchema where
1097 parseJSON _ = empty
1288 parseJSON _ = empty
1098
1289
1099instance FromJSON ParamOtherSchema where
1290instance FromJSON ParamOtherSchema where
1100− parseJSON = genericParseJSONWithSub "paramSchema" (jsonPrefix "paramOtherSchema")
1291+ parseJSON = sopSwaggerGenericParseJSON
1101
1292
1102instance FromJSON Responses where
1293instance FromJSON Responses where
1103 parseJSON (Object o) = Responses
1294 parseJSON (Object o) = Responses
1104 <$> o .:? "default"
1295 <$> o .:? "default"
1105− <*> (parseJSON (Object (HashMap.delete "default" o)) >>= hashMapReadKeys)
1296+ <*> (parseJSON (Object (HashMap.delete "default" o)))
1106 parseJSON _ = empty
1297 parseJSON _ = empty
1107
1298
1108instance FromJSON Example where
1299instance FromJSON Example where
@@ -1111,16 +1302,16 @@ instance FromJSON Example where
1111 pure $ Example (Map.mapKeys fromString m)
1302 pure $ Example (Map.mapKeys fromString m)
1112
1303
1113instance FromJSON Response where
1304instance FromJSON Response where
1114− parseJSON = genericParseJSON (jsonPrefix "response")
1305+ parseJSON = sopSwaggerGenericParseJSON
1115− `withDefaults` [ "headers" .= (mempty :: HashMap HeaderName Header) ]
1116
1306
1117instance FromJSON Operation where
1307instance FromJSON Operation where
1118− parseJSON = genericParseJSON (jsonPrefix "operation")
1308+ parseJSON = sopSwaggerGenericParseJSON
1119− `withDefaults` [ "security" .= ([] :: [SecurityRequirement]) ]
1120
1309
1121instance FromJSON PathItem where
1310instance FromJSON PathItem where
1122− parseJSON = genericParseJSON (jsonPrefix "pathItem")
1311+ parseJSON = sopSwaggerGenericParseJSON
1123− `withDefaults` [ "parameters" .= ([] :: [Param]) ]
1312+
1313+instance FromJSON SecurityDefinitions where
1314+ parseJSON js = SecurityDefinitions <$> parseJSON js
1124
1315
1125instance FromJSON Reference where
1316instance FromJSON Reference where
1126 parseJSON (Object o) = Reference <$> o .: "$ref"
1317 parseJSON (Object o) = Reference <$> o .: "$ref"
@@ -1146,26 +1337,91 @@ instance FromJSON (Referenced Response) where parseJSON = referencedParseJSON "#
1146instance FromJSON Xml where
1337instance FromJSON Xml where
1147 parseJSON = genericParseJSON (jsonPrefix "xml")
1338 parseJSON = genericParseJSON (jsonPrefix "xml")
1148
1339
1149−instance FromJSON (SwaggerType Schema) where
1340+instance FromJSON (SwaggerType 'SwaggerKindSchema) where
1150 parseJSON = parseOneOf [SwaggerString, SwaggerInteger, SwaggerNumber, SwaggerBoolean, SwaggerArray, SwaggerNull, SwaggerObject]
1341 parseJSON = parseOneOf [SwaggerString, SwaggerInteger, SwaggerNumber, SwaggerBoolean, SwaggerArray, SwaggerNull, SwaggerObject]
1151
1342
1152−instance FromJSON (SwaggerType ParamOtherSchema) where
1343+instance FromJSON (SwaggerType 'SwaggerKindParamOtherSchema) where
1153 parseJSON = parseOneOf [SwaggerString, SwaggerInteger, SwaggerNumber, SwaggerBoolean, SwaggerArray, SwaggerFile]
1344 parseJSON = parseOneOf [SwaggerString, SwaggerInteger, SwaggerNumber, SwaggerBoolean, SwaggerArray, SwaggerFile]
1154
1345
1155−instance OVERLAPPABLE_ FromJSON (SwaggerType t) where
1346+instance FromJSON (SwaggerType ('SwaggerKindNormal t)) where
1156 parseJSON = parseOneOf [SwaggerString, SwaggerInteger, SwaggerNumber, SwaggerBoolean, SwaggerArray]
1347 parseJSON = parseOneOf [SwaggerString, SwaggerInteger, SwaggerNumber, SwaggerBoolean, SwaggerArray]
1157
1348
1158−instance OVERLAPPABLE_ FromJSON (CollectionFormat t) where
1349+instance FromJSON (CollectionFormat ('SwaggerKindNormal t)) where
1159 parseJSON = parseOneOf [CollectionCSV, CollectionSSV, CollectionTSV, CollectionPipes]
1350 parseJSON = parseOneOf [CollectionCSV, CollectionSSV, CollectionTSV, CollectionPipes]
1160
1351
1352+-- NOTE: There aren't collections of 'Schema'
1161−instance FromJSON (CollectionFormat ParamOtherSchema) where
1353+--instance FromJSON (CollectionFormat (SwaggerKindSchema)) where
1162− parseJSON = parseOneOf [CollectionCSV, CollectionSSV, CollectionTSV, CollectionPipes, CollectionMulti]
1354+-- parseJSON = parseOneOf [CollectionCSV, CollectionSSV, CollectionTSV, CollectionPipes]
1163
1355
1164−-- NOTE: The constraints @FromJSON (SwaggerType t)@ and
1356+instance FromJSON (CollectionFormat 'SwaggerKindParamOtherSchema) where
1165−-- @FromJSON (SwaggerItems t)@ are necessary here!
1357+ parseJSON = parseOneOf [CollectionCSV, CollectionSSV, CollectionTSV, CollectionPipes, CollectionMulti]
1166−-- Without the constraint the general instance will be used
1167−-- that only accepts common types (i.e. NOT object, null or file)
1168−-- and primitive array items.
1169−instance (FromJSON (SwaggerType t), FromJSON (SwaggerItems t)) => FromJSON (ParamSchema t) where
1170− parseJSON = genericParseJSONWithSub "items" (jsonPrefix "ParamSchema")
1171
1358
1359+instance (FromJSON (SwaggerType ('SwaggerKindNormal t)), FromJSON (SwaggerItems ('SwaggerKindNormal t))) => FromJSON (ParamSchema ('SwaggerKindNormal t)) where
1360+ parseJSON = sopSwaggerGenericParseJSON
1361+instance FromJSON (ParamSchema 'SwaggerKindParamOtherSchema) where
1362+ parseJSON = sopSwaggerGenericParseJSON
1363+instance FromJSON (ParamSchema 'SwaggerKindSchema) where
1364+ parseJSON = sopSwaggerGenericParseJSON
1365+
1366+instance FromJSON AdditionalProperties where
1367+ parseJSON (Bool b) = pure $ AdditionalPropertiesAllowed b
1368+ parseJSON js = AdditionalPropertiesSchema <$> parseJSON js
1369+
1370+-------------------------------------------------------------------------------
1371+-- TH splices
1372+-------------------------------------------------------------------------------
1373+
1374+deriveGeneric ''Header
1375+deriveGeneric ''OAuth2Params
1376+deriveGeneric ''Operation
1377+deriveGeneric ''Param
1378+deriveGeneric ''ParamOtherSchema
1379+deriveGeneric ''PathItem
1380+deriveGeneric ''Response
1381+deriveGeneric ''Responses
1382+deriveGeneric ''SecurityScheme
1383+deriveGeneric ''Schema
1384+deriveGeneric ''ParamSchema
1385+deriveGeneric ''Swagger
1386+
1387+instance HasSwaggerAesonOptions Header where
1388+ swaggerAesonOptions _ = mkSwaggerAesonOptions "header" & saoSubObject ?~ "paramSchema"
1389+instance HasSwaggerAesonOptions OAuth2Params where
1390+ swaggerAesonOptions _ = mkSwaggerAesonOptions "oauth2" & saoSubObject ?~ "flow"
1391+instance HasSwaggerAesonOptions Operation where
1392+ swaggerAesonOptions _ = mkSwaggerAesonOptions "operation"
1393+instance HasSwaggerAesonOptions Param where
1394+ swaggerAesonOptions _ = mkSwaggerAesonOptions "param" & saoSubObject ?~ "schema"
1395+instance HasSwaggerAesonOptions ParamOtherSchema where
1396+ swaggerAesonOptions _ = mkSwaggerAesonOptions "paramOtherSchema" & saoSubObject ?~ "paramSchema"
1397+instance HasSwaggerAesonOptions PathItem where
1398+ swaggerAesonOptions _ = mkSwaggerAesonOptions "pathItem"
1399+instance HasSwaggerAesonOptions Response where
1400+ swaggerAesonOptions _ = mkSwaggerAesonOptions "response"
1401+instance HasSwaggerAesonOptions Responses where
1402+ swaggerAesonOptions _ = mkSwaggerAesonOptions "responses" & saoSubObject ?~ "responses"
1403+instance HasSwaggerAesonOptions SecurityScheme where
1404+ swaggerAesonOptions _ = mkSwaggerAesonOptions "securityScheme" & saoSubObject ?~ "type"
1405+instance HasSwaggerAesonOptions Schema where
1406+ swaggerAesonOptions _ = mkSwaggerAesonOptions "schema" & saoSubObject ?~ "paramSchema"
1407+instance HasSwaggerAesonOptions Swagger where
1408+ swaggerAesonOptions _ = mkSwaggerAesonOptions "swagger" & saoAdditionalPairs .~ [("swagger", "2.0")]
1409+
1410+instance HasSwaggerAesonOptions (ParamSchema ('SwaggerKindNormal t)) where
1411+ swaggerAesonOptions _ = mkSwaggerAesonOptions "paramSchema" & saoSubObject ?~ "items"
1412+instance HasSwaggerAesonOptions (ParamSchema 'SwaggerKindParamOtherSchema) where
1413+ swaggerAesonOptions _ = mkSwaggerAesonOptions "paramSchema" & saoSubObject ?~ "items"
1414+-- NOTE: Schema doesn't have 'items' sub object!
1415+instance HasSwaggerAesonOptions (ParamSchema 'SwaggerKindSchema) where
1416+ swaggerAesonOptions _ = mkSwaggerAesonOptions "paramSchema"
1417+
1418+instance AesonDefaultValue (ParamSchema s)
1419+instance AesonDefaultValue OAuth2Flow
1420+instance AesonDefaultValue Responses
1421+instance AesonDefaultValue ParamAnySchema
1422+instance AesonDefaultValue SecuritySchemeType
1423+instance AesonDefaultValue (SwaggerType a)
1424+instance AesonDefaultValue MimeList where defaultValue = Just mempty
1425+instance AesonDefaultValue Info
1426+instance AesonDefaultValue ParamLocation
1427+instance AesonDefaultValue SecurityDefinitions where defaultValue = Just $ SecurityDefinitions mempty
src/Data/Swagger/Internal/AesonUtils.hsnew file+346
@@ -0,0 +1,346 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE DataKinds #-}
3+{-# LANGUAGE FlexibleContexts #-}
4+{-# LANGUAGE GADTs #-}
5+{-# LANGUAGE ScopedTypeVariables #-}
6+{-# LANGUAGE ExplicitForAll #-}
7+{-# LANGUAGE TemplateHaskell #-}
8+#if __GLASGOW_HASKELL__ >= 800
9+{-# LANGUAGE UndecidableSuperClasses #-}
10+#endif
11+module Data.Swagger.Internal.AesonUtils (
12+ -- * Generic functions
13+ AesonDefaultValue(..),
14+ sopSwaggerGenericToJSON,
15+#if MIN_VERSION_aeson(0,10,0)
16+ sopSwaggerGenericToEncoding,
17+#endif
18+ sopSwaggerGenericToJSONWithOpts,
19+ sopSwaggerGenericParseJSON,
20+ -- * Options
21+ HasSwaggerAesonOptions(..),
22+ SwaggerAesonOptions,
23+ mkSwaggerAesonOptions,
24+ saoPrefix,
25+ saoAdditionalPairs,
26+ saoSubObject,
27+ ) where
28+
29+import Prelude ()
30+import Prelude.Compat
31+
32+import Control.Applicative ((<|>))
33+import Control.Lens (makeLenses, (^.))
34+import Control.Monad (unless)
35+import Data.Aeson (ToJSON(..), FromJSON(..), Value(..), Object, object, (.:), (.:?), (.!=), withObject)
36+import Data.Aeson.Types (Parser, Pair)
37+import Data.Char (toLower, isUpper)
38+import Data.Foldable (traverse_)
39+import Data.Text (Text)
40+
41+import Generics.SOP
42+
43+import qualified Data.Text as T
44+import qualified Data.HashMap.Strict as HM
45+import qualified Data.Set as Set
46+import qualified Data.HashMap.Strict.InsOrd as InsOrd
47+import qualified Data.HashSet.InsOrd as InsOrdHS
48+
49+#if MIN_VERSION_aeson(0,10,0)
50+import Data.Aeson (Encoding, pairs, (.=), Series)
51+#endif
52+
53+-------------------------------------------------------------------------------
54+-- SwaggerAesonOptions
55+-------------------------------------------------------------------------------
56+
57+data SwaggerAesonOptions = SwaggerAesonOptions
58+ { _saoPrefix :: String
59+ , _saoAdditionalPairs :: [(Text, Value)]
60+ , _saoSubObject :: Maybe String
61+ }
62+
63+mkSwaggerAesonOptions
64+ :: String -- ^ prefix
65+ -> SwaggerAesonOptions
66+mkSwaggerAesonOptions pfx = SwaggerAesonOptions pfx [] Nothing
67+
68+makeLenses ''SwaggerAesonOptions
69+
70+class (Generic a, All2 AesonDefaultValue (Code a)) => HasSwaggerAesonOptions a where
71+ swaggerAesonOptions :: Proxy a -> SwaggerAesonOptions
72+
73+ -- So far we use only default definitions
74+ aesonDefaults :: Proxy a -> POP Maybe (Code a)
75+ aesonDefaults _ = hcpure (Proxy :: Proxy AesonDefaultValue) defaultValue
76+
77+-------------------------------------------------------------------------------
78+-- Generics
79+-------------------------------------------------------------------------------
80+
81+class AesonDefaultValue a where
82+ defaultValue :: Maybe a
83+ defaultValue = Nothing
84+
85+instance AesonDefaultValue Text where defaultValue = Nothing
86+instance AesonDefaultValue (Maybe a) where defaultValue = Just Nothing
87+instance AesonDefaultValue [a] where defaultValue = Just []
88+instance AesonDefaultValue (Set.Set a) where defaultValue = Just Set.empty
89+instance AesonDefaultValue (InsOrdHS.InsOrdHashSet k) where defaultValue = Just InsOrdHS.empty
90+instance AesonDefaultValue (InsOrd.InsOrdHashMap k v) where defaultValue = Just InsOrd.empty
91+
92+-------------------------------------------------------------------------------
93+-- ToJSON
94+-------------------------------------------------------------------------------
95+
96+-- | Generic serialisation for swagger records.
97+--
98+-- Features
99+--
100+-- * omits nulls, empty objects and empty arrays (configurable)
101+-- * possible to add fields
102+-- * possible to merge sub-object
103+sopSwaggerGenericToJSON
104+ :: forall a xs.
105+ ( HasDatatypeInfo a
106+ , HasSwaggerAesonOptions a
107+ , All2 ToJSON (Code a)
108+ , All2 Eq (Code a)
109+ , Code a ~ '[xs]
110+ )
111+ => a
112+ -> Value
113+sopSwaggerGenericToJSON x =
114+ let ps = sopSwaggerGenericToJSON' opts (from x) (datatypeInfo proxy) (aesonDefaults proxy)
115+ in object (opts ^. saoAdditionalPairs ++ ps)
116+ where
117+ proxy = Proxy :: Proxy a
118+ opts = swaggerAesonOptions proxy
119+
120+-- | *TODO:* This is only used by ToJSON (ParamSchema SwaggerKindSchema)
121+--
122+-- Also uses default `aesonDefaults`
123+sopSwaggerGenericToJSONWithOpts
124+ :: forall a xs.
125+ ( Generic a
126+ , All2 AesonDefaultValue (Code a)
127+ , HasDatatypeInfo a
128+ , All2 ToJSON (Code a)
129+ , All2 Eq (Code a)
130+ , Code a ~ '[xs]
131+ )
132+ => SwaggerAesonOptions
133+ -> a
134+ -> Value
135+sopSwaggerGenericToJSONWithOpts opts x =
136+ let ps = sopSwaggerGenericToJSON' opts (from x) (datatypeInfo proxy) defs
137+ in object (opts ^. saoAdditionalPairs ++ ps)
138+ where
139+ proxy = Proxy :: Proxy a
140+ defs = hcpure (Proxy :: Proxy AesonDefaultValue) defaultValue
141+
142+sopSwaggerGenericToJSON'
143+ :: (All2 ToJSON '[xs], All2 Eq '[xs])
144+ => SwaggerAesonOptions
145+ -> SOP I '[xs]
146+ -> DatatypeInfo '[xs]
147+ -> POP Maybe '[xs]
148+ -> [Pair]
149+#if MIN_VERSION_generics_sop(0,5,0)
150+sopSwaggerGenericToJSON' opts (SOP (Z fields)) (ADT _ _ (Record _ fieldsInfo :* Nil) _) (POP (defs :* Nil)) =
151+#else
152+sopSwaggerGenericToJSON' opts (SOP (Z fields)) (ADT _ _ (Record _ fieldsInfo :* Nil)) (POP (defs :* Nil)) =
153+#endif
154+ sopSwaggerGenericToJSON'' opts fields fieldsInfo defs
155+sopSwaggerGenericToJSON' _ _ _ _ = error "sopSwaggerGenericToJSON: unsupported type"
156+
157+sopSwaggerGenericToJSON''
158+ :: (All ToJSON xs, All Eq xs)
159+ => SwaggerAesonOptions
160+ -> NP I xs
161+ -> NP FieldInfo xs
162+ -> NP Maybe xs
163+ -> [Pair]
164+sopSwaggerGenericToJSON'' (SwaggerAesonOptions prefix _ sub) = go
165+ where
166+ go :: (All ToJSON ys, All Eq ys) => NP I ys -> NP FieldInfo ys -> NP Maybe ys -> [Pair]
167+ go Nil Nil Nil = []
168+ go (I x :* xs) (FieldInfo name :* names) (def :* defs)
169+ | Just name' == sub = case json of
170+ Object m -> HM.toList m ++ rest
171+ Null -> rest
172+ _ -> error $ "sopSwaggerGenericToJSON: subjson is not an object: " ++ show json
173+ -- If default value: omit it.
174+ | Just x == def =
175+ rest
176+ | otherwise =
177+ (T.pack name', json) : rest
178+ where
179+ json = toJSON x
180+ name' = fieldNameModifier name
181+ rest = go xs names defs
182+#if __GLASGOW_HASKELL__ < 800
183+ go _ _ _ = error "not empty"
184+#endif
185+
186+ fieldNameModifier = modifier . drop 1
187+ modifier = lowerFirstUppers . drop (length prefix)
188+ lowerFirstUppers s = map toLower x ++ y
189+ where (x, y) = span isUpper s
190+
191+-------------------------------------------------------------------------------
192+-- FromJSON
193+-------------------------------------------------------------------------------
194+
195+sopSwaggerGenericParseJSON
196+ :: forall a xs.
197+ ( HasDatatypeInfo a
198+ , HasSwaggerAesonOptions a
199+ , All2 FromJSON (Code a)
200+ , All2 Eq (Code a)
201+ , Code a ~ '[xs]
202+ )
203+ => Value
204+ -> Parser a
205+sopSwaggerGenericParseJSON = withObject "Swagger Record Object" $ \obj ->
206+ let ps = sopSwaggerGenericParseJSON' opts obj (datatypeInfo proxy) (aesonDefaults proxy)
207+ in do
208+ traverse_ (parseAdditionalField obj) (opts ^. saoAdditionalPairs)
209+ to <$> ps
210+ where
211+ proxy = Proxy :: Proxy a
212+ opts = swaggerAesonOptions proxy
213+
214+ parseAdditionalField :: Object -> (Text, Value) -> Parser ()
215+ parseAdditionalField obj (k, v) = do
216+ v' <- obj .: k
217+ unless (v == v') $ fail $
218+ "Additonal field don't match for key " ++ T.unpack k
219+ ++ ": " ++ show v
220+ ++ " /= " ++ show v'
221+
222+sopSwaggerGenericParseJSON'
223+ :: (All2 FromJSON '[xs], All2 Eq '[xs])
224+ => SwaggerAesonOptions
225+ -> Object
226+ -> DatatypeInfo '[xs]
227+ -> POP Maybe '[xs]
228+ -> Parser (SOP I '[xs])
229+#if MIN_VERSION_generics_sop(0,5,0)
230+sopSwaggerGenericParseJSON' opts obj (ADT _ _ (Record _ fieldsInfo :* Nil) _) (POP (defs :* Nil)) =
231+#else
232+sopSwaggerGenericParseJSON' opts obj (ADT _ _ (Record _ fieldsInfo :* Nil)) (POP (defs :* Nil)) =
233+#endif
234+ SOP . Z <$> sopSwaggerGenericParseJSON'' opts obj fieldsInfo defs
235+sopSwaggerGenericParseJSON' _ _ _ _ = error "sopSwaggerGenericParseJSON: unsupported type"
236+
237+sopSwaggerGenericParseJSON''
238+ :: (All FromJSON xs, All Eq xs)
239+ => SwaggerAesonOptions
240+ -> Object
241+ -> NP FieldInfo xs
242+ -> NP Maybe xs
243+ -> Parser (NP I xs)
244+sopSwaggerGenericParseJSON'' (SwaggerAesonOptions prefix _ sub) obj = go
245+ where
246+ go :: (All FromJSON ys, All Eq ys) => NP FieldInfo ys -> NP Maybe ys -> Parser (NP I ys)
247+ go Nil Nil = pure Nil
248+ go (FieldInfo name :* names) (def :* defs)
249+ | Just name' == sub =
250+ -- Note: we might strip fields of outer structure.
251+ cons <$> (withDef $ parseJSON $ Object obj) <*> rest
252+ | otherwise = case def of
253+ Just def' -> cons <$> obj .:? T.pack name' .!= def' <*> rest
254+ Nothing -> cons <$> obj .: T.pack name' <*> rest
255+ where
256+ cons h t = I h :* t
257+ name' = fieldNameModifier name
258+ rest = go names defs
259+
260+ withDef = case def of
261+ Just def' -> (<|> pure def')
262+ Nothing -> id
263+#if __GLASGOW_HASKELL__ < 800
264+ go _ _ = error "not empty"
265+#endif
266+
267+ fieldNameModifier = modifier . drop 1
268+ modifier = lowerFirstUppers . drop (length prefix)
269+ lowerFirstUppers s = map toLower x ++ y
270+ where (x, y) = span isUpper s
271+
272+-------------------------------------------------------------------------------
273+-- ToEncoding
274+-------------------------------------------------------------------------------
275+
276+#if MIN_VERSION_aeson(0,10,0)
277+
278+sopSwaggerGenericToEncoding
279+ :: forall a xs.
280+ ( HasDatatypeInfo a
281+ , HasSwaggerAesonOptions a
282+ , All2 ToJSON (Code a)
283+ , All2 Eq (Code a)
284+ , Code a ~ '[xs]
285+ )
286+ => a
287+ -> Encoding
288+sopSwaggerGenericToEncoding x =
289+ let ps = sopSwaggerGenericToEncoding' opts (from x) (datatypeInfo proxy) (aesonDefaults proxy)
290+ in pairs (pairsToSeries (opts ^. saoAdditionalPairs) <> ps)
291+ where
292+ proxy = Proxy :: Proxy a
293+ opts = swaggerAesonOptions proxy
294+
295+pairsToSeries :: [Pair] -> Series
296+pairsToSeries = foldMap (\(k, v) -> (k .= v))
297+
298+sopSwaggerGenericToEncoding'
299+ :: (All2 ToJSON '[xs], All2 Eq '[xs])
300+ => SwaggerAesonOptions
301+ -> SOP I '[xs]
302+ -> DatatypeInfo '[xs]
303+ -> POP Maybe '[xs]
304+ -> Series
305+#if MIN_VERSION_generics_sop(0,5,0)
306+sopSwaggerGenericToEncoding' opts (SOP (Z fields)) (ADT _ _ (Record _ fieldsInfo :* Nil) _) (POP (defs :* Nil)) =
307+#else
308+sopSwaggerGenericToEncoding' opts (SOP (Z fields)) (ADT _ _ (Record _ fieldsInfo :* Nil)) (POP (defs :* Nil)) =
309+#endif
310+ sopSwaggerGenericToEncoding'' opts fields fieldsInfo defs
311+sopSwaggerGenericToEncoding' _ _ _ _ = error "sopSwaggerGenericToEncoding: unsupported type"
312+
313+sopSwaggerGenericToEncoding''
314+ :: (All ToJSON xs, All Eq xs)
315+ => SwaggerAesonOptions
316+ -> NP I xs
317+ -> NP FieldInfo xs
318+ -> NP Maybe xs
319+ -> Series
320+sopSwaggerGenericToEncoding'' (SwaggerAesonOptions prefix _ sub) = go
321+ where
322+ go :: (All ToJSON ys, All Eq ys) => NP I ys -> NP FieldInfo ys -> NP Maybe ys -> Series
323+ go Nil Nil Nil = mempty
324+ go (I x :* xs) (FieldInfo name :* names) (def :* defs)
325+ | Just name' == sub = case toJSON x of
326+ Object m -> pairsToSeries (HM.toList m) <> rest
327+ Null -> rest
328+ _ -> error $ "sopSwaggerGenericToJSON: subjson is not an object: " ++ show (toJSON x)
329+ -- If default value: omit it.
330+ | Just x == def =
331+ rest
332+ | otherwise =
333+ (T.pack name' .= x) <> rest
334+ where
335+ name' = fieldNameModifier name
336+ rest = go xs names defs
337+#if __GLASGOW_HASKELL__ < 800
338+ go _ _ _ = error "not empty"
339+#endif
340+
341+ fieldNameModifier = modifier . drop 1
342+ modifier = lowerFirstUppers . drop (length prefix)
343+ lowerFirstUppers s = map toLower x ++ y
344+ where (x, y) = span isUpper s
345+
346+#endif
src/Data/Swagger/Internal/ParamSchema.hs+120−23
@@ -1,4 +1,5 @@
1{-# LANGUAGE CPP #-}
1{-# LANGUAGE CPP #-}
2+{-# LANGUAGE DataKinds #-}
2{-# LANGUAGE DefaultSignatures #-}
3{-# LANGUAGE DefaultSignatures #-}
3{-# LANGUAGE FlexibleContexts #-}
4{-# LANGUAGE FlexibleContexts #-}
4{-# LANGUAGE FlexibleInstances #-}
5{-# LANGUAGE FlexibleInstances #-}
@@ -7,13 +8,21 @@
7{-# LANGUAGE PackageImports #-}
8{-# LANGUAGE PackageImports #-}
8{-# LANGUAGE PolyKinds #-}
9{-# LANGUAGE PolyKinds #-}
9{-# LANGUAGE ScopedTypeVariables #-}
10{-# LANGUAGE ScopedTypeVariables #-}
11+{-# LANGUAGE TypeFamilies #-}
10{-# LANGUAGE TypeOperators #-}
12{-# LANGUAGE TypeOperators #-}
11{-# LANGUAGE TypeSynonymInstances #-}
13{-# LANGUAGE TypeSynonymInstances #-}
14+{-# LANGUAGE UndecidableInstances #-}
15+#if __GLASGOW_HASKELL__ >= 800
16+-- Generic a is redundant in ToParamSchema a default imple
17+{-# OPTIONS_GHC -Wno-redundant-constraints #-}
18+-- For TypeErrors
19+{-# OPTIONS_GHC -Wno-unticked-promoted-constructors #-}
20+#endif
12#include "overlapping-compat.h"
21#include "overlapping-compat.h"
13module Data.Swagger.Internal.ParamSchema where
22module Data.Swagger.Internal.ParamSchema where
14
23
15import Control.Lens
24import Control.Lens
16−import Data.Aeson
25+import Data.Aeson (ToJSON (..))
17import Data.Proxy
26import Data.Proxy
18import GHC.Generics
27import GHC.Generics
19
28
@@ -22,15 +31,50 @@ import "unordered-containers" Data.HashSet (HashSet)
22import Data.Monoid
31import Data.Monoid
23import Data.Set (Set)
32import Data.Set (Set)
24import Data.Scientific
33import Data.Scientific
34+import Data.Fixed (HasResolution(..), Fixed, Pico)
25import qualified Data.Text as T
35import qualified Data.Text as T
26import qualified Data.Text.Lazy as TL
36import qualified Data.Text.Lazy as TL
27import Data.Time
37import Data.Time
38+import qualified Data.Vector as V
39+import qualified Data.Vector.Primitive as VP
40+import qualified Data.Vector.Storable as VS
41+import qualified Data.Vector.Unboxed as VU
42+import Data.Version (Version)
43+import Numeric.Natural.Compat (Natural)
28import Data.Word
44import Data.Word
45+import Data.UUID.Types (UUID)
46+import Web.Cookie (SetCookie)
29
47
30import Data.Swagger.Internal
48import Data.Swagger.Internal
31import Data.Swagger.Lens
49import Data.Swagger.Lens
32import Data.Swagger.SchemaOptions
50import Data.Swagger.SchemaOptions
33
51
52+#if __GLASGOW_HASKELL__ < 800
53+#else
54+import qualified Data.ByteString as BS
55+import qualified Data.ByteString.Lazy as BSL
56+import GHC.TypeLits (TypeError, ErrorMessage(..))
57+#endif
58+
59+-- | Default schema for binary data (any sequence of octets).
60+binaryParamSchema :: ParamSchema t
61+binaryParamSchema = mempty
62+ & type_ ?~ SwaggerString
63+ & format ?~ "binary"
64+
65+-- | Default schema for binary data (base64 encoded).
66+byteParamSchema :: ParamSchema t
67+byteParamSchema = mempty
68+ & type_ ?~ SwaggerString
69+ & format ?~ "byte"
70+
71+-- | Default schema for password string.
72+-- @"password"@ format is used to hint UIs the input needs to be obscured.
73+passwordParamSchema :: ParamSchema t
74+passwordParamSchema = mempty
75+ & type_ ?~ SwaggerString
76+ & format ?~ "password"
77+
34-- | Convert a type into a plain @'ParamSchema'@.
78-- | Convert a type into a plain @'ParamSchema'@.
35--
79--
36-- An example type and instance:
80-- An example type and instance:
@@ -43,9 +87,9 @@ import Data.Swagger.SchemaOptions
43-- data Direction = Up | Down
87-- data Direction = Up | Down
44--
88--
45-- instance ToParamSchema Direction where
89-- instance ToParamSchema Direction where
46−-- toParamSchema = mempty
90+-- toParamSchema _ = mempty
47−-- & type_ .~ SwaggerString
91+-- & type_ ?~ SwaggerString
48−-- & enum_ .~ [ \"Up\", \"Down\" ]
92+-- & enum_ ?~ [ \"Up\", \"Down\" ]
49-- @
93-- @
50--
94--
51-- Instead of manually writing your @'ToParamSchema'@ instance you can
95-- Instead of manually writing your @'ToParamSchema'@ instance you can
@@ -71,18 +115,24 @@ class ToParamSchema a where
71 --
115 --
72 -- >>> encode $ toParamSchema (Proxy :: Proxy Integer)
116 -- >>> encode $ toParamSchema (Proxy :: Proxy Integer)
73 -- "{\"type\":\"integer\"}"
117 -- "{\"type\":\"integer\"}"
74− toParamSchema :: proxy a -> ParamSchema t
118+ toParamSchema :: Proxy a -> ParamSchema t
75− default toParamSchema :: (Generic a, GToParamSchema (Rep a)) => proxy a -> ParamSchema t
119+ default toParamSchema :: (Generic a, GToParamSchema (Rep a)) => Proxy a -> ParamSchema t
76 toParamSchema = genericToParamSchema defaultSchemaOptions
120 toParamSchema = genericToParamSchema defaultSchemaOptions
77
121
78instance OVERLAPPING_ ToParamSchema String where
122instance OVERLAPPING_ ToParamSchema String where
79− toParamSchema _ = mempty & type_ .~ SwaggerString
123+ toParamSchema _ = mempty & type_ ?~ SwaggerString
80
124
81instance ToParamSchema Bool where
125instance ToParamSchema Bool where
82− toParamSchema _ = mempty & type_ .~ SwaggerBoolean
126+ toParamSchema _ = mempty & type_ ?~ SwaggerBoolean
83
127
84instance ToParamSchema Integer where
128instance ToParamSchema Integer where
85− toParamSchema _ = mempty & type_ .~ SwaggerInteger
129+ toParamSchema _ = mempty & type_ ?~ SwaggerInteger
130+
131+instance ToParamSchema Natural where
132+ toParamSchema _ = mempty
133+ & type_ ?~ SwaggerInteger
134+ & minimum_ ?~ 0
135+ & exclusiveMinimum ?~ False
86
136
87instance ToParamSchema Int where toParamSchema = toParamSchemaBoundedIntegral
137instance ToParamSchema Int where toParamSchema = toParamSchemaBoundedIntegral
88instance ToParamSchema Int8 where toParamSchema = toParamSchemaBoundedIntegral
138instance ToParamSchema Int8 where toParamSchema = toParamSchemaBoundedIntegral
@@ -104,40 +154,51 @@ instance ToParamSchema Word64 where toParamSchema = toParamSchemaBoundedIntegral
104--
154--
105-- >>> encode $ toParamSchemaBoundedIntegral (Proxy :: Proxy Int8)
155-- >>> encode $ toParamSchemaBoundedIntegral (Proxy :: Proxy Int8)
106-- "{\"maximum\":127,\"minimum\":-128,\"type\":\"integer\"}"
156-- "{\"maximum\":127,\"minimum\":-128,\"type\":\"integer\"}"
107−toParamSchemaBoundedIntegral :: forall proxy a t. (Bounded a, Integral a) => proxy a -> ParamSchema t
157+toParamSchemaBoundedIntegral :: forall a t. (Bounded a, Integral a) => Proxy a -> ParamSchema t
108toParamSchemaBoundedIntegral _ = mempty
158toParamSchemaBoundedIntegral _ = mempty
109− & type_ .~ SwaggerInteger
159+ & type_ ?~ SwaggerInteger
110 & minimum_ ?~ fromInteger (toInteger (minBound :: a))
160 & minimum_ ?~ fromInteger (toInteger (minBound :: a))
111 & maximum_ ?~ fromInteger (toInteger (maxBound :: a))
161 & maximum_ ?~ fromInteger (toInteger (maxBound :: a))
112
162
113instance ToParamSchema Char where
163instance ToParamSchema Char where
114 toParamSchema _ = mempty
164 toParamSchema _ = mempty
115− & type_ .~ SwaggerString
165+ & type_ ?~ SwaggerString
116 & maxLength ?~ 1
166 & maxLength ?~ 1
117 & minLength ?~ 1
167 & minLength ?~ 1
118
168
119instance ToParamSchema Scientific where
169instance ToParamSchema Scientific where
120− toParamSchema _ = mempty & type_ .~ SwaggerNumber
170+ toParamSchema _ = mempty & type_ ?~ SwaggerNumber
171+
172+instance HasResolution a => ToParamSchema (Fixed a) where
173+ toParamSchema _ = mempty
174+ & type_ ?~ SwaggerNumber
175+ & multipleOf ?~ (recip . fromInteger $ resolution (Proxy :: Proxy a))
121
176
122instance ToParamSchema Double where
177instance ToParamSchema Double where
123 toParamSchema _ = mempty
178 toParamSchema _ = mempty
124− & type_ .~ SwaggerNumber
179+ & type_ ?~ SwaggerNumber
125 & format ?~ "double"
180 & format ?~ "double"
126
181
127instance ToParamSchema Float where
182instance ToParamSchema Float where
128 toParamSchema _ = mempty
183 toParamSchema _ = mempty
129− & type_ .~ SwaggerNumber
184+ & type_ ?~ SwaggerNumber
130 & format ?~ "float"
185 & format ?~ "float"
131
186
132timeParamSchema :: String -> ParamSchema t
187timeParamSchema :: String -> ParamSchema t
133timeParamSchema fmt = mempty
188timeParamSchema fmt = mempty
134− & type_ .~ SwaggerString
189+ & type_ ?~ SwaggerString
135 & format ?~ T.pack fmt
190 & format ?~ T.pack fmt
136
191
137-- | Format @"date"@ corresponds to @yyyy-mm-dd@ format.
192-- | Format @"date"@ corresponds to @yyyy-mm-dd@ format.
138instance ToParamSchema Day where
193instance ToParamSchema Day where
139 toParamSchema _ = timeParamSchema "date"
194 toParamSchema _ = timeParamSchema "date"
140
195
196+-- |
197+-- >>> toParamSchema (Proxy :: Proxy TimeOfDay) ^. format
198+-- Just "hh:MM:ss"
199+instance ToParamSchema TimeOfDay where
200+ toParamSchema _ = timeParamSchema "hh:MM:ss"
201+
141-- |
202-- |
142-- >>> toParamSchema (Proxy :: Proxy LocalTime) ^. format
203-- >>> toParamSchema (Proxy :: Proxy LocalTime) ^. format
143-- Just "yyyy-mm-ddThh:MM:ss"
204-- Just "yyyy-mm-ddThh:MM:ss"
@@ -157,7 +218,7 @@ instance ToParamSchema UTCTime where
157 toParamSchema _ = timeParamSchema "yyyy-mm-ddThh:MM:ssZ"
218 toParamSchema _ = timeParamSchema "yyyy-mm-ddThh:MM:ssZ"
158
219
159instance ToParamSchema NominalDiffTime where
220instance ToParamSchema NominalDiffTime where
160− toParamSchema _ = toParamSchema (Proxy :: Proxy Integer)
221+ toParamSchema _ = toParamSchema (Proxy :: Proxy Pico)
161
222
162instance ToParamSchema T.Text where
223instance ToParamSchema T.Text where
163 toParamSchema _ = toParamSchema (Proxy :: Proxy String)
224 toParamSchema _ = toParamSchema (Proxy :: Proxy String)
@@ -165,6 +226,28 @@ instance ToParamSchema T.Text where
165instance ToParamSchema TL.Text where
226instance ToParamSchema TL.Text where
166 toParamSchema _ = toParamSchema (Proxy :: Proxy String)
227 toParamSchema _ = toParamSchema (Proxy :: Proxy String)
167
228
229+instance ToParamSchema Version where
230+ toParamSchema _ = mempty
231+ & type_ ?~ SwaggerString
232+ & pattern ?~ "^\\d+(\\.\\d+)*$"
233+
234+instance ToParamSchema SetCookie where
235+ toParamSchema _ = mempty
236+ & type_ ?~ SwaggerString
237+
238+
239+#if __GLASGOW_HASKELL__ < 800
240+#else
241+type family ToParamSchemaByteStringError bs where
242+ ToParamSchemaByteStringError bs = TypeError
243+ ( 'Text "Impossible to have an instance " :<>: ShowType (ToParamSchema bs) :<>: Text "."
244+ :$$: 'Text "Please, use a newtype wrapper around " :<>: ShowType bs :<>: Text " instead."
245+ :$$: 'Text "Consider using byteParamSchema or binaryParamSchema templates." )
246+
247+instance ToParamSchemaByteStringError BS.ByteString => ToParamSchema BS.ByteString where toParamSchema = error "impossible"
248+instance ToParamSchemaByteStringError BSL.ByteString => ToParamSchema BSL.ByteString where toParamSchema = error "impossible"
249+#endif
250+
168instance ToParamSchema All where toParamSchema _ = toParamSchema (Proxy :: Proxy Bool)
251instance ToParamSchema All where toParamSchema _ = toParamSchema (Proxy :: Proxy Bool)
169instance ToParamSchema Any where toParamSchema _ = toParamSchema (Proxy :: Proxy Bool)
252instance ToParamSchema Any where toParamSchema _ = toParamSchema (Proxy :: Proxy Bool)
170instance ToParamSchema a => ToParamSchema (Sum a) where toParamSchema _ = toParamSchema (Proxy :: Proxy a)
253instance ToParamSchema a => ToParamSchema (Sum a) where toParamSchema _ = toParamSchema (Proxy :: Proxy a)
@@ -173,11 +256,18 @@ instance ToParamSchema a => ToParamSchema (First a) where toParamSchema _ = to
173instance ToParamSchema a => ToParamSchema (Last a) where toParamSchema _ = toParamSchema (Proxy :: Proxy a)
256instance ToParamSchema a => ToParamSchema (Last a) where toParamSchema _ = toParamSchema (Proxy :: Proxy a)
174instance ToParamSchema a => ToParamSchema (Dual a) where toParamSchema _ = toParamSchema (Proxy :: Proxy a)
257instance ToParamSchema a => ToParamSchema (Dual a) where toParamSchema _ = toParamSchema (Proxy :: Proxy a)
175
258
259+instance ToParamSchema a => ToParamSchema (Identity a) where toParamSchema _ = toParamSchema (Proxy :: Proxy a)
260+
176instance ToParamSchema a => ToParamSchema [a] where
261instance ToParamSchema a => ToParamSchema [a] where
177 toParamSchema _ = mempty
262 toParamSchema _ = mempty
178− & type_ .~ SwaggerArray
263+ & type_ ?~ SwaggerArray
179 & items ?~ SwaggerItemsPrimitive Nothing (toParamSchema (Proxy :: Proxy a))
264 & items ?~ SwaggerItemsPrimitive Nothing (toParamSchema (Proxy :: Proxy a))
180
265
266+instance ToParamSchema a => ToParamSchema (V.Vector a) where toParamSchema _ = toParamSchema (Proxy :: Proxy [a])
267+instance ToParamSchema a => ToParamSchema (VP.Vector a) where toParamSchema _ = toParamSchema (Proxy :: Proxy [a])
268+instance ToParamSchema a => ToParamSchema (VS.Vector a) where toParamSchema _ = toParamSchema (Proxy :: Proxy [a])
269+instance ToParamSchema a => ToParamSchema (VU.Vector a) where toParamSchema _ = toParamSchema (Proxy :: Proxy [a])
270+
181instance ToParamSchema a => ToParamSchema (Set a) where
271instance ToParamSchema a => ToParamSchema (Set a) where
182 toParamSchema _ = toParamSchema (Proxy :: Proxy [a])
272 toParamSchema _ = toParamSchema (Proxy :: Proxy [a])
183 & uniqueItems ?~ True
273 & uniqueItems ?~ True
@@ -190,20 +280,25 @@ instance ToParamSchema a => ToParamSchema (HashSet a) where
190-- "{\"type\":\"string\",\"enum\":[\"_\"]}"
280-- "{\"type\":\"string\",\"enum\":[\"_\"]}"
191instance ToParamSchema () where
281instance ToParamSchema () where
192 toParamSchema _ = mempty
282 toParamSchema _ = mempty
193− & type_ .~ SwaggerString
283+ & type_ ?~ SwaggerString
194 & enum_ ?~ ["_"]
284 & enum_ ?~ ["_"]
195
285
286+instance ToParamSchema UUID where
287+ toParamSchema _ = mempty
288+ & type_ ?~ SwaggerString
289+ & format ?~ "uuid"
290+
196-- | A configurable generic @'ParamSchema'@ creator.
291-- | A configurable generic @'ParamSchema'@ creator.
197--
292--
198-- >>> :set -XDeriveGeneric
293-- >>> :set -XDeriveGeneric
199-- >>> data Color = Red | Blue deriving Generic
294-- >>> data Color = Red | Blue deriving Generic
200-- >>> encode $ genericToParamSchema defaultSchemaOptions (Proxy :: Proxy Color)
295-- >>> encode $ genericToParamSchema defaultSchemaOptions (Proxy :: Proxy Color)
201-- "{\"type\":\"string\",\"enum\":[\"Red\",\"Blue\"]}"
296-- "{\"type\":\"string\",\"enum\":[\"Red\",\"Blue\"]}"
202−genericToParamSchema :: forall proxy a t. (Generic a, GToParamSchema (Rep a)) => SchemaOptions -> proxy a -> ParamSchema t
297+genericToParamSchema :: forall a t. (Generic a, GToParamSchema (Rep a)) => SchemaOptions -> Proxy a -> ParamSchema t
203genericToParamSchema opts _ = gtoParamSchema opts (Proxy :: Proxy (Rep a)) mempty
298genericToParamSchema opts _ = gtoParamSchema opts (Proxy :: Proxy (Rep a)) mempty
204
299
205class GToParamSchema (f :: * -> *) where
300class GToParamSchema (f :: * -> *) where
206− gtoParamSchema :: SchemaOptions -> proxy f -> ParamSchema t -> ParamSchema t
301+ gtoParamSchema :: SchemaOptions -> Proxy f -> ParamSchema t -> ParamSchema t
207
302
208instance GToParamSchema f => GToParamSchema (D1 d f) where
303instance GToParamSchema f => GToParamSchema (D1 d f) where
209 gtoParamSchema opts _ = gtoParamSchema opts (Proxy :: Proxy f)
304 gtoParamSchema opts _ = gtoParamSchema opts (Proxy :: Proxy f)
@@ -221,14 +316,14 @@ instance (GEnumParamSchema f, GEnumParamSchema g) => GToParamSchema (f :+: g) wh
221 gtoParamSchema opts _ = genumParamSchema opts (Proxy :: Proxy (f :+: g))
316 gtoParamSchema opts _ = genumParamSchema opts (Proxy :: Proxy (f :+: g))
222
317
223class GEnumParamSchema (f :: * -> *) where
318class GEnumParamSchema (f :: * -> *) where
224− genumParamSchema :: SchemaOptions -> proxy f -> ParamSchema t -> ParamSchema t
319+ genumParamSchema :: SchemaOptions -> Proxy f -> ParamSchema t -> ParamSchema t
225
320
226instance (GEnumParamSchema f, GEnumParamSchema g) => GEnumParamSchema (f :+: g) where
321instance (GEnumParamSchema f, GEnumParamSchema g) => GEnumParamSchema (f :+: g) where
227 genumParamSchema opts _ = genumParamSchema opts (Proxy :: Proxy f) . genumParamSchema opts (Proxy :: Proxy g)
322 genumParamSchema opts _ = genumParamSchema opts (Proxy :: Proxy f) . genumParamSchema opts (Proxy :: Proxy g)
228
323
229instance Constructor c => GEnumParamSchema (C1 c U1) where
324instance Constructor c => GEnumParamSchema (C1 c U1) where
230 genumParamSchema opts _ s = s
325 genumParamSchema opts _ s = s
231− & type_ .~ SwaggerString
326+ & type_ ?~ SwaggerString
232 & enum_ %~ addEnumValue tag
327 & enum_ %~ addEnumValue tag
233 where
328 where
234 tag = toJSON (constructorTagModifier opts (conName (Proxy3 :: Proxy3 c f p)))
329 tag = toJSON (constructorTagModifier opts (conName (Proxy3 :: Proxy3 c f p)))
@@ -238,3 +333,5 @@ instance Constructor c => GEnumParamSchema (C1 c U1) where
238
333
239data Proxy3 a b c = Proxy3
334data Proxy3 a b c = Proxy3
240
335
336+-- $setup
337+-- >>> import Data.Aeson (encode)
src/Data/Swagger/Internal/Schema.hs+386−81
@@ -1,8 +1,10 @@
1{-# LANGUAGE CPP #-}
1{-# LANGUAGE CPP #-}
2+{-# LANGUAGE ConstraintKinds #-}
2{-# LANGUAGE DefaultSignatures #-}
3{-# LANGUAGE DefaultSignatures #-}
3{-# LANGUAGE FlexibleContexts #-}
4{-# LANGUAGE FlexibleContexts #-}
4{-# LANGUAGE FlexibleInstances #-}
5{-# LANGUAGE FlexibleInstances #-}
5{-# LANGUAGE KindSignatures #-}
6{-# LANGUAGE KindSignatures #-}
7+{-# LANGUAGE DataKinds #-}
6{-# LANGUAGE OverloadedLists #-}
8{-# LANGUAGE OverloadedLists #-}
7{-# LANGUAGE OverloadedStrings #-}
9{-# LANGUAGE OverloadedStrings #-}
8{-# LANGUAGE PackageImports #-}
10{-# LANGUAGE PackageImports #-}
@@ -12,6 +14,13 @@
12{-# LANGUAGE TypeFamilies #-}
14{-# LANGUAGE TypeFamilies #-}
13{-# LANGUAGE TypeOperators #-}
15{-# LANGUAGE TypeOperators #-}
14{-# LANGUAGE TypeSynonymInstances #-}
16{-# LANGUAGE TypeSynonymInstances #-}
17+{-# LANGUAGE UndecidableInstances #-}
18+#if __GLASGOW_HASKELL__ >= 800
19+-- Few generics related redundant constraints
20+{-# OPTIONS_GHC -Wno-redundant-constraints #-}
21+-- For TypeErrors
22+{-# OPTIONS_GHC -Wno-unticked-promoted-constructors #-}
23+#endif
15#include "overlapping-compat.h"
24#include "overlapping-compat.h"
16module Data.Swagger.Internal.Schema where
25module Data.Swagger.Internal.Schema where
17
26
@@ -23,34 +32,50 @@ import Data.Data.Lens (template)
23
32
24import Control.Monad
33import Control.Monad
25import Control.Monad.Writer
34import Control.Monad.Writer
26−import Data.Aeson
35+import Data.Aeson (ToJSON (..), ToJSONKey (..), ToJSONKeyFunction (..), Value (..), Object(..))
27import Data.Char
36import Data.Char
28import Data.Data (Data)
37import Data.Data (Data)
29import Data.Foldable (traverse_)
38import Data.Foldable (traverse_)
30import Data.HashMap.Strict (HashMap)
39import Data.HashMap.Strict (HashMap)
31import qualified Data.HashMap.Strict as HashMap
40import qualified Data.HashMap.Strict as HashMap
32−import "unordered-containers" Data.HashSet (HashSet)
41+import "unordered-containers" Data.HashSet (HashSet)
42+import qualified "unordered-containers" Data.HashSet as HashSet
43+import qualified Data.HashMap.Strict.InsOrd as InsOrdHashMap
33import Data.Int
44import Data.Int
34import Data.IntSet (IntSet)
45import Data.IntSet (IntSet)
35import Data.IntMap (IntMap)
46import Data.IntMap (IntMap)
47+import Data.List.NonEmpty.Compat (NonEmpty)
36import Data.Map (Map)
48import Data.Map (Map)
37import Data.Proxy
49import Data.Proxy
38import Data.Scientific (Scientific)
50import Data.Scientific (Scientific)
51+import Data.Fixed (Fixed, HasResolution, Pico)
39import Data.Set (Set)
52import Data.Set (Set)
40import qualified Data.Text as T
53import qualified Data.Text as T
41import qualified Data.Text.Lazy as TL
54import qualified Data.Text.Lazy as TL
42import Data.Time
55import Data.Time
56+import qualified Data.Vector as V
57+import qualified Data.Vector.Primitive as VP
58+import qualified Data.Vector.Storable as VS
59+import qualified Data.Vector.Unboxed as VU
60+import Data.Version (Version)
61+import Numeric.Natural.Compat (Natural)
43import Data.Word
62import Data.Word
44import GHC.Generics
63import GHC.Generics
64+import qualified Data.UUID.Types as UUID
45
65
46import Data.Swagger.Declare
66import Data.Swagger.Declare
47import Data.Swagger.Internal
67import Data.Swagger.Internal
48import Data.Swagger.Internal.ParamSchema (ToParamSchema(..))
68import Data.Swagger.Internal.ParamSchema (ToParamSchema(..))
49import Data.Swagger.Lens hiding (name, schema)
69import Data.Swagger.Lens hiding (name, schema)
70+import qualified Data.Swagger.Lens as Swagger
50import Data.Swagger.SchemaOptions
71import Data.Swagger.SchemaOptions
72+import Data.Swagger.Internal.TypeShape
51
73
52−#ifdef __DOCTEST__
74+#if __GLASGOW_HASKELL__ < 800
53−import Data.Swagger.Lens (name, schema)
75+#else
76+import qualified Data.ByteString as BS
77+import qualified Data.ByteString.Lazy as BSL
78+import GHC.TypeLits (TypeError, ErrorMessage(..))
54#endif
79#endif
55
80
56unnamed :: Schema -> NamedSchema
81unnamed :: Schema -> NamedSchema
@@ -77,19 +102,21 @@ rename name (NamedSchema _ schema) = NamedSchema name schema
77-- {-\# LANGUAGE OverloadedLists \#-} -- allows to write 'Map' and 'HashMap' as lists
102-- {-\# LANGUAGE OverloadedLists \#-} -- allows to write 'Map' and 'HashMap' as lists
78--
103--
79-- import Control.Lens
104-- import Control.Lens
105+-- import Data.Proxy
106+-- import Data.Swagger
80--
107--
81-- data Coord = Coord { x :: Double, y :: Double }
108-- data Coord = Coord { x :: Double, y :: Double }
82--
109--
83-- instance ToSchema Coord where
110-- instance ToSchema Coord where
84−-- declareNamedSchema = pure (Just \"Coord\", schema)
111+-- declareNamedSchema _ = do
85−-- where
112+-- doubleSchema <- declareSchemaRef (Proxy :: Proxy Double)
86−-- schema = mempty
113+-- return $ NamedSchema (Just \"Coord\") $ mempty
87−-- & type_ .~ SwaggerObject
114+-- & type_ ?~ SwaggerObject
88−-- & properties .~
115+-- & properties .~
89−-- [ (\"x\", toSchemaRef (Proxy :: Proxy Double))
116+-- [ (\"x\", doubleSchema)
90−-- , (\"y\", toSchemaRef (Proxy :: Proxy Double))
117+-- , (\"y\", doubleSchema)
91−-- ]
118+-- ]
92−-- & required .~ [ \"x\", \"y\" ]
119+-- & required .~ [ \"x\", \"y\" ]
93-- @
120-- @
94--
121--
95-- Instead of manually writing your @'ToSchema'@ instance you can
122-- Instead of manually writing your @'ToSchema'@ instance you can
@@ -115,12 +142,17 @@ class ToSchema a where
115 -- together with all used definitions.
142 -- together with all used definitions.
116 -- Note that the schema itself is included in definitions
143 -- Note that the schema itself is included in definitions
117 -- only if it is recursive (and thus needs its definition in scope).
144 -- only if it is recursive (and thus needs its definition in scope).
118− declareNamedSchema :: proxy a -> Declare (Definitions Schema) NamedSchema
145+ declareNamedSchema :: Proxy a -> Declare (Definitions Schema) NamedSchema
146+ default declareNamedSchema :: (Generic a, GToSchema (Rep a), TypeHasSimpleShape a "genericDeclareNamedSchemaUnrestricted") =>
119− default declareNamedSchema :: (Generic a, GToSchema (Rep a)) => proxy a -> Declare (Definitions Schema) NamedSchema
147+ Proxy a -> Declare (Definitions Schema) NamedSchema
120 declareNamedSchema = genericDeclareNamedSchema defaultSchemaOptions
148 declareNamedSchema = genericDeclareNamedSchema defaultSchemaOptions
121
149
150+instance ToSchema TimeOfDay where
151+ declareNamedSchema _ = pure $ named "TimeOfDay" $ timeSchema "hh:MM:ss"
152+ & example ?~ toJSON (TimeOfDay 12 33 15)
153+
122-- | Convert a type into a schema and declare all used schema definitions.
154-- | Convert a type into a schema and declare all used schema definitions.
123−declareSchema :: ToSchema a => proxy a -> Declare (Definitions Schema) Schema
155+declareSchema :: ToSchema a => Proxy a -> Declare (Definitions Schema) Schema
124declareSchema = fmap _namedSchemaSchema . declareNamedSchema
156declareSchema = fmap _namedSchemaSchema . declareNamedSchema
125
157
126-- | Convert a type into an optionally named schema.
158-- | Convert a type into an optionally named schema.
@@ -133,8 +165,8 @@ declareSchema = fmap _namedSchemaSchema . declareNamedSchema
133-- >>> toNamedSchema (Proxy :: Proxy Day) ^. name
165-- >>> toNamedSchema (Proxy :: Proxy Day) ^. name
134-- Just "Day"
166-- Just "Day"
135-- >>> encode (toNamedSchema (Proxy :: Proxy Day) ^. schema)
167-- >>> encode (toNamedSchema (Proxy :: Proxy Day) ^. schema)
136−-- "{\"format\":\"date\",\"type\":\"string\"}"
168+-- "{\"example\":\"2016-07-22\",\"format\":\"date\",\"type\":\"string\"}"
137−toNamedSchema :: ToSchema a => proxy a -> NamedSchema
169+toNamedSchema :: ToSchema a => Proxy a -> NamedSchema
138toNamedSchema = undeclare . declareNamedSchema
170toNamedSchema = undeclare . declareNamedSchema
139
171
140-- | Get type's schema name according to its @'ToSchema'@ instance.
172-- | Get type's schema name according to its @'ToSchema'@ instance.
@@ -144,7 +176,7 @@ toNamedSchema = undeclare . declareNamedSchema
144--
176--
145-- >>> schemaName (Proxy :: Proxy UTCTime)
177-- >>> schemaName (Proxy :: Proxy UTCTime)
146-- Just "UTCTime"
178-- Just "UTCTime"
147−schemaName :: ToSchema a => proxy a -> Maybe T.Text
179+schemaName :: ToSchema a => Proxy a -> Maybe T.Text
148schemaName = _namedSchemaName . toNamedSchema
180schemaName = _namedSchemaName . toNamedSchema
149
181
150-- | Convert a type into a schema.
182-- | Convert a type into a schema.
@@ -154,7 +186,7 @@ schemaName = _namedSchemaName . toNamedSchema
154--
186--
155-- >>> encode $ toSchema (Proxy :: Proxy [Day])
187-- >>> encode $ toSchema (Proxy :: Proxy [Day])
156-- "{\"items\":{\"$ref\":\"#/definitions/Day\"},\"type\":\"array\"}"
188-- "{\"items\":{\"$ref\":\"#/definitions/Day\"},\"type\":\"array\"}"
157−toSchema :: ToSchema a => proxy a -> Schema
189+toSchema :: ToSchema a => Proxy a -> Schema
158toSchema = _namedSchemaSchema . toNamedSchema
190toSchema = _namedSchemaSchema . toNamedSchema
159
191
160-- | Convert a type into a referenced schema if possible.
192-- | Convert a type into a referenced schema if possible.
@@ -165,7 +197,7 @@ toSchema = _namedSchemaSchema . toNamedSchema
165--
197--
166-- >>> encode $ toSchemaRef (Proxy :: Proxy Day)
198-- >>> encode $ toSchemaRef (Proxy :: Proxy Day)
167-- "{\"$ref\":\"#/definitions/Day\"}"
199-- "{\"$ref\":\"#/definitions/Day\"}"
168−toSchemaRef :: ToSchema a => proxy a -> Referenced Schema
200+toSchemaRef :: ToSchema a => Proxy a -> Referenced Schema
169toSchemaRef = undeclare . declareSchemaRef
201toSchemaRef = undeclare . declareSchemaRef
170
202
171-- | Convert a type into a referenced schema if possible
203-- | Convert a type into a referenced schema if possible
@@ -175,7 +207,7 @@ toSchemaRef = undeclare . declareSchemaRef
175-- Schema definitions are typically declared for every referenced schema.
207-- Schema definitions are typically declared for every referenced schema.
176-- If @'declareSchemaRef'@ returns a reference, a corresponding schema
208-- If @'declareSchemaRef'@ returns a reference, a corresponding schema
177-- will be declared (regardless of whether it is recusive or not).
209-- will be declared (regardless of whether it is recusive or not).
178−declareSchemaRef :: ToSchema a => proxy a -> Declare (Definitions Schema) (Referenced Schema)
210+declareSchemaRef :: ToSchema a => Proxy a -> Declare (Definitions Schema) (Referenced Schema)
179declareSchemaRef proxy = do
211declareSchemaRef proxy = do
180 case toNamedSchema proxy of
212 case toNamedSchema proxy of
181 NamedSchema (Just name) schema -> do
213 NamedSchema (Just name) schema -> do
@@ -187,7 +219,7 @@ declareSchemaRef proxy = do
187 -- have already declared it.
219 -- have already declared it.
188 -- If we have, we don't need to declare anything for
220 -- If we have, we don't need to declare anything for
189 -- this schema this time and thus simply return the reference.
221 -- this schema this time and thus simply return the reference.
190− known <- looks (HashMap.member name)
222+ known <- looks (InsOrdHashMap.member name)
191 when (not known) $ do
223 when (not known) $ do
192 declare [(name, schema)]
224 declare [(name, schema)]
193 void $ declareNamedSchema proxy
225 void $ declareNamedSchema proxy
@@ -206,7 +238,7 @@ inlineSchemasWhen p defs = template %~ deref
206 where
238 where
207 deref r@(Ref (Reference name))
239 deref r@(Ref (Reference name))
208 | p name =
240 | p name =
209− case HashMap.lookup name defs of
241+ case InsOrdHashMap.lookup name defs of
210 Just schema -> Inline (inlineSchemasWhen p defs schema)
242 Just schema -> Inline (inlineSchemasWhen p defs schema)
211 Nothing -> r
243 Nothing -> r
212 | otherwise = r
244 | otherwise = r
@@ -233,11 +265,11 @@ inlineAllSchemas = inlineSchemasWhen (const True)
233-- | Convert a type into a schema without references.
265-- | Convert a type into a schema without references.
234--
266--
235-- >>> encode $ toInlinedSchema (Proxy :: Proxy [Day])
267-- >>> encode $ toInlinedSchema (Proxy :: Proxy [Day])
236−-- "{\"items\":{\"format\":\"date\",\"type\":\"string\"},\"type\":\"array\"}"
268+-- "{\"items\":{\"example\":\"2016-07-22\",\"format\":\"date\",\"type\":\"string\"},\"type\":\"array\"}"
237--
269--
238-- __WARNING:__ @'toInlinedSchema'@ will produce infinite schema
270-- __WARNING:__ @'toInlinedSchema'@ will produce infinite schema
239-- when inlining recursive schemas.
271-- when inlining recursive schemas.
240−toInlinedSchema :: ToSchema a => proxy a -> Schema
272+toInlinedSchema :: ToSchema a => Proxy a -> Schema
241toInlinedSchema proxy = inlineAllSchemas defs schema
273toInlinedSchema proxy = inlineAllSchemas defs schema
242 where
274 where
243 (defs, schema) = runDeclare (declareSchema proxy) mempty
275 (defs, schema) = runDeclare (declareSchema proxy) mempty
@@ -248,7 +280,7 @@ inlineNonRecursiveSchemas :: Data s => (Definitions Schema) -> s -> s
248inlineNonRecursiveSchemas defs = inlineSchemasWhen nonRecursive defs
280inlineNonRecursiveSchemas defs = inlineSchemasWhen nonRecursive defs
249 where
281 where
250 nonRecursive name =
282 nonRecursive name =
251− case HashMap.lookup name defs of
283+ case InsOrdHashMap.lookup name defs of
252 Just schema -> name `notElem` execDeclare (usedNames schema) mempty
284 Just schema -> name `notElem` execDeclare (usedNames schema) mempty
253 Nothing -> False
285 Nothing -> False
254
286
@@ -260,22 +292,141 @@ inlineNonRecursiveSchemas defs = inlineSchemasWhen nonRecursive defs
260 seen <- looks (name `elem`)
292 seen <- looks (name `elem`)
261 when (not seen) $ do
293 when (not seen) $ do
262 declare [name]
294 declare [name]
263− traverse_ usedNames (HashMap.lookup name defs)
295+ traverse_ usedNames (InsOrdHashMap.lookup name defs)
264 Inline subschema -> usedNames subschema
296 Inline subschema -> usedNames subschema
265
297
298+-- | Default schema for binary data (any sequence of octets).
299+binarySchema :: Schema
300+binarySchema = mempty
301+ & type_ ?~ SwaggerString
302+ & format ?~ "binary"
303+
304+-- | Default schema for binary data (base64 encoded).
305+byteSchema :: Schema
306+byteSchema = mempty
307+ & type_ ?~ SwaggerString
308+ & format ?~ "byte"
309+
310+-- | Default schema for password string.
311+-- @"password"@ format is used to hint UIs the input needs to be obscured.
312+passwordSchema :: Schema
313+passwordSchema = mempty
314+ & type_ ?~ SwaggerString
315+ & format ?~ "password"
316+
317+-- | Make an unrestrictive sketch of a @'Schema'@ based on a @'ToJSON'@ instance.
318+-- Produced schema can be used for further refinement.
319+--
320+-- >>> encode $ sketchSchema "hello"
321+-- "{\"example\":\"hello\",\"type\":\"string\"}"
322+--
323+-- >>> encode $ sketchSchema (1, 2, 3)
324+-- "{\"example\":[1,2,3],\"items\":{\"type\":\"number\"},\"type\":\"array\"}"
325+--
326+-- >>> encode $ sketchSchema ("Jack", 25)
327+-- "{\"example\":[\"Jack\",25],\"items\":[{\"type\":\"string\"},{\"type\":\"number\"}],\"type\":\"array\"}"
328+--
329+-- >>> data Person = Person { name :: String, age :: Int } deriving (Generic)
330+-- >>> instance ToJSON Person
331+-- >>> encode $ sketchSchema (Person "Jack" 25)
332+-- "{\"required\":[\"age\",\"name\"],\"properties\":{\"age\":{\"type\":\"number\"},\"name\":{\"type\":\"string\"}},\"example\":{\"age\":25,\"name\":\"Jack\"},\"type\":\"object\"}"
333+sketchSchema :: ToJSON a => a -> Schema
334+sketchSchema = sketch . toJSON
335+ where
336+ sketch Null = go Null
337+ sketch js@(Bool _) = go js
338+ sketch js = go js & example ?~ js
339+
340+ go Null = mempty & type_ ?~ SwaggerNull
341+ go (Bool _) = mempty & type_ ?~ SwaggerBoolean
342+ go (String _) = mempty & type_ ?~ SwaggerString
343+ go (Number _) = mempty & type_ ?~ SwaggerNumber
344+ go (Array xs) = mempty
345+ & type_ ?~ SwaggerArray
346+ & items ?~ case ischema of
347+ Just s -> SwaggerItemsObject (Inline s)
348+ _ -> SwaggerItemsArray (map Inline ys)
349+ where
350+ ys = map go (V.toList xs)
351+ allSame = and ((zipWith (==)) ys (tail ys))
352+
353+ ischema = case ys of
354+ (z:_) | allSame -> Just z
355+ _ -> Nothing
356+ go (Object o) = mempty
357+ & type_ ?~ SwaggerObject
358+ & required .~ HashMap.keys o
359+ & properties .~ fmap (Inline . go) (InsOrdHashMap.fromHashMap o)
360+
361+-- | Make a restrictive sketch of a @'Schema'@ based on a @'ToJSON'@ instance.
362+-- Produced schema uses as much constraints as possible.
363+--
364+-- >>> encode $ sketchStrictSchema "hello"
365+-- "{\"maxLength\":5,\"pattern\":\"hello\",\"minLength\":5,\"type\":\"string\",\"enum\":[\"hello\"]}"
366+--
367+-- >>> encode $ sketchStrictSchema (1, 2, 3)
368+-- "{\"minItems\":3,\"uniqueItems\":true,\"items\":[{\"maximum\":1,\"minimum\":1,\"multipleOf\":1,\"type\":\"number\",\"enum\":[1]},{\"maximum\":2,\"minimum\":2,\"multipleOf\":2,\"type\":\"number\",\"enum\":[2]},{\"maximum\":3,\"minimum\":3,\"multipleOf\":3,\"type\":\"number\",\"enum\":[3]}],\"maxItems\":3,\"type\":\"array\",\"enum\":[[1,2,3]]}"
369+--
370+-- >>> encode $ sketchStrictSchema ("Jack", 25)
371+-- "{\"minItems\":2,\"uniqueItems\":true,\"items\":[{\"maxLength\":4,\"pattern\":\"Jack\",\"minLength\":4,\"type\":\"string\",\"enum\":[\"Jack\"]},{\"maximum\":25,\"minimum\":25,\"multipleOf\":25,\"type\":\"number\",\"enum\":[25]}],\"maxItems\":2,\"type\":\"array\",\"enum\":[[\"Jack\",25]]}"
372+--
373+-- >>> data Person = Person { name :: String, age :: Int } deriving (Generic)
374+-- >>> instance ToJSON Person
375+-- >>> encode $ sketchStrictSchema (Person "Jack" 25)
376+-- "{\"required\":[\"age\",\"name\"],\"properties\":{\"age\":{\"maximum\":25,\"minimum\":25,\"multipleOf\":25,\"type\":\"number\",\"enum\":[25]},\"name\":{\"maxLength\":4,\"pattern\":\"Jack\",\"minLength\":4,\"type\":\"string\",\"enum\":[\"Jack\"]}},\"maxProperties\":2,\"minProperties\":2,\"type\":\"object\",\"enum\":[{\"age\":25,\"name\":\"Jack\"}]}"
377+sketchStrictSchema :: ToJSON a => a -> Schema
378+sketchStrictSchema = go . toJSON
379+ where
380+ go Null = mempty & type_ ?~ SwaggerNull
381+ go js@(Bool _) = mempty
382+ & type_ ?~ SwaggerBoolean
383+ & enum_ ?~ [js]
384+ go js@(String s) = mempty
385+ & type_ ?~ SwaggerString
386+ & maxLength ?~ fromIntegral (T.length s)
387+ & minLength ?~ fromIntegral (T.length s)
388+ & pattern ?~ s
389+ & enum_ ?~ [js]
390+ go js@(Number n) = mempty
391+ & type_ ?~ SwaggerNumber
392+ & maximum_ ?~ n
393+ & minimum_ ?~ n
394+ & multipleOf ?~ n
395+ & enum_ ?~ [js]
396+ go js@(Array xs) = mempty
397+ & type_ ?~ SwaggerArray
398+ & maxItems ?~ fromIntegral sz
399+ & minItems ?~ fromIntegral sz
400+ & items ?~ SwaggerItemsArray (map (Inline . go) (V.toList xs))
401+ & uniqueItems ?~ allUnique
402+ & enum_ ?~ [js]
403+ where
404+ sz = length xs
405+ allUnique = sz == HashSet.size (HashSet.fromList (V.toList xs))
406+ go js@(Object o) = mempty
407+ & type_ ?~ SwaggerObject
408+ & required .~ names
409+ & properties .~ fmap (Inline . go) (InsOrdHashMap.fromHashMap o)
410+ & maxProperties ?~ fromIntegral (length names)
411+ & minProperties ?~ fromIntegral (length names)
412+ & enum_ ?~ [js]
413+ where
414+ names = HashMap.keys o
415+
266class GToSchema (f :: * -> *) where
416class GToSchema (f :: * -> *) where
267− gdeclareNamedSchema :: SchemaOptions -> proxy f -> Schema -> Declare (Definitions Schema) NamedSchema
417+ gdeclareNamedSchema :: SchemaOptions -> Proxy f -> Schema -> Declare (Definitions Schema) NamedSchema
268
418
269instance OVERLAPPABLE_ ToSchema a => ToSchema [a] where
419instance OVERLAPPABLE_ ToSchema a => ToSchema [a] where
270 declareNamedSchema _ = do
420 declareNamedSchema _ = do
271 ref <- declareSchemaRef (Proxy :: Proxy a)
421 ref <- declareSchemaRef (Proxy :: Proxy a)
272 return $ unnamed $ mempty
422 return $ unnamed $ mempty
273− & type_ .~ SwaggerArray
423+ & type_ ?~ SwaggerArray
274 & items ?~ SwaggerItemsObject ref
424 & items ?~ SwaggerItemsObject ref
275
425
276instance OVERLAPPING_ ToSchema String where declareNamedSchema = plain . paramSchemaToSchema
426instance OVERLAPPING_ ToSchema String where declareNamedSchema = plain . paramSchemaToSchema
277instance ToSchema Bool where declareNamedSchema = plain . paramSchemaToSchema
427instance ToSchema Bool where declareNamedSchema = plain . paramSchemaToSchema
278instance ToSchema Integer where declareNamedSchema = plain . paramSchemaToSchema
428instance ToSchema Integer where declareNamedSchema = plain . paramSchemaToSchema
429+instance ToSchema Natural where declareNamedSchema = plain . paramSchemaToSchema
279instance ToSchema Int where declareNamedSchema = plain . paramSchemaToSchema
430instance ToSchema Int where declareNamedSchema = plain . paramSchemaToSchema
280instance ToSchema Int8 where declareNamedSchema = plain . paramSchemaToSchema
431instance ToSchema Int8 where declareNamedSchema = plain . paramSchemaToSchema
281instance ToSchema Int16 where declareNamedSchema = plain . paramSchemaToSchema
432instance ToSchema Int16 where declareNamedSchema = plain . paramSchemaToSchema
@@ -287,11 +438,16 @@ instance ToSchema Word16 where declareNamedSchema = plain . paramSchemaToSchema
287instance ToSchema Word32 where declareNamedSchema = plain . paramSchemaToSchema
438instance ToSchema Word32 where declareNamedSchema = plain . paramSchemaToSchema
288instance ToSchema Word64 where declareNamedSchema = plain . paramSchemaToSchema
439instance ToSchema Word64 where declareNamedSchema = plain . paramSchemaToSchema
289
440
441+instance ToSchema Char where
290−instance ToSchema Char where declareNamedSchema = plain . paramSchemaToSchema
442+ declareNamedSchema proxy = plain (paramSchemaToSchema proxy)
443+ & mapped.Swagger.schema.example ?~ toJSON '?'
444+
291instance ToSchema Scientific where declareNamedSchema = plain . paramSchemaToSchema
445instance ToSchema Scientific where declareNamedSchema = plain . paramSchemaToSchema
292instance ToSchema Double where declareNamedSchema = plain . paramSchemaToSchema
446instance ToSchema Double where declareNamedSchema = plain . paramSchemaToSchema
293instance ToSchema Float where declareNamedSchema = plain . paramSchemaToSchema
447instance ToSchema Float where declareNamedSchema = plain . paramSchemaToSchema
294
448
449+instance HasResolution a => ToSchema (Fixed a) where declareNamedSchema = plain . paramSchemaToSchema
450+
295instance ToSchema a => ToSchema (Maybe a) where
451instance ToSchema a => ToSchema (Maybe a) where
296 declareNamedSchema _ = declareNamedSchema (Proxy :: Proxy a)
452 declareNamedSchema _ = declareNamedSchema (Proxy :: Proxy a)
297
453
@@ -300,6 +456,11 @@ instance (ToSchema a, ToSchema b) => ToSchema (Either a b)
300instance ToSchema () where
456instance ToSchema () where
301 declareNamedSchema _ = pure (NamedSchema Nothing nullarySchema)
457 declareNamedSchema _ = pure (NamedSchema Nothing nullarySchema)
302
458
459+-- | For 'ToJSON' instance, see <http://hackage.haskell.org/package/uuid-aeson uuid-aeson> package.
460+instance ToSchema UUID.UUID where
461+ declareNamedSchema p = pure $ named "UUID" $ paramSchemaToSchema p
462+ & example ?~ toJSON (UUID.toText UUID.nil)
463+
303instance (ToSchema a, ToSchema b) => ToSchema (a, b)
464instance (ToSchema a, ToSchema b) => ToSchema (a, b)
304instance (ToSchema a, ToSchema b, ToSchema c) => ToSchema (a, b, c)
465instance (ToSchema a, ToSchema b, ToSchema c) => ToSchema (a, b, c)
305instance (ToSchema a, ToSchema b, ToSchema c, ToSchema d) => ToSchema (a, b, c, d)
466instance (ToSchema a, ToSchema b, ToSchema c, ToSchema d) => ToSchema (a, b, c, d)
@@ -309,46 +470,81 @@ instance (ToSchema a, ToSchema b, ToSchema c, ToSchema d, ToSchema e, ToSchema f
309
470
310timeSchema :: T.Text -> Schema
471timeSchema :: T.Text -> Schema
311timeSchema fmt = mempty
472timeSchema fmt = mempty
312− & type_ .~ SwaggerString
473+ & type_ ?~ SwaggerString
313 & format ?~ fmt
474 & format ?~ fmt
314
475
315-- | Format @"date"@ corresponds to @yyyy-mm-dd@ format.
476-- | Format @"date"@ corresponds to @yyyy-mm-dd@ format.
316instance ToSchema Day where
477instance ToSchema Day where
317− declareNamedSchema _ = pure $ named "Day" (timeSchema "date")
478+ declareNamedSchema _ = pure $ named "Day" $ timeSchema "date"
479+ & example ?~ toJSON (fromGregorian 2016 7 22)
318
480
319-- |
481-- |
320-- >>> toSchema (Proxy :: Proxy LocalTime) ^. format
482-- >>> toSchema (Proxy :: Proxy LocalTime) ^. format
321-- Just "yyyy-mm-ddThh:MM:ss"
483-- Just "yyyy-mm-ddThh:MM:ss"
322instance ToSchema LocalTime where
484instance ToSchema LocalTime where
323− declareNamedSchema _ = pure $ named "LocalTime" (timeSchema "yyyy-mm-ddThh:MM:ss")
485+ declareNamedSchema _ = pure $ named "LocalTime" $ timeSchema "yyyy-mm-ddThh:MM:ss"
486+ & example ?~ toJSON (LocalTime (fromGregorian 2016 7 22) (TimeOfDay 7 40 0))
324
487
325-- | Format @"date"@ corresponds to @yyyy-mm-ddThh:MM:ss(Z|+hh:MM)@ format.
488-- | Format @"date"@ corresponds to @yyyy-mm-ddThh:MM:ss(Z|+hh:MM)@ format.
326instance ToSchema ZonedTime where
489instance ToSchema ZonedTime where
327 declareNamedSchema _ = pure $ named "ZonedTime" $ timeSchema "date-time"
490 declareNamedSchema _ = pure $ named "ZonedTime" $ timeSchema "date-time"
491+ & example ?~ toJSON (ZonedTime (LocalTime (fromGregorian 2016 7 22) (TimeOfDay 7 40 0)) (hoursToTimeZone 3))
328
492
329instance ToSchema NominalDiffTime where
493instance ToSchema NominalDiffTime where
330− declareNamedSchema _ = declareNamedSchema (Proxy :: Proxy Integer)
494+ declareNamedSchema _ = declareNamedSchema (Proxy :: Proxy Pico)
331
495
332-- |
496-- |
333-- >>> toSchema (Proxy :: Proxy UTCTime) ^. format
497-- >>> toSchema (Proxy :: Proxy UTCTime) ^. format
334-- Just "yyyy-mm-ddThh:MM:ssZ"
498-- Just "yyyy-mm-ddThh:MM:ssZ"
335instance ToSchema UTCTime where
499instance ToSchema UTCTime where
336− declareNamedSchema _ = pure $ named "UTCTime" (timeSchema "yyyy-mm-ddThh:MM:ssZ")
500+ declareNamedSchema _ = pure $ named "UTCTime" $ timeSchema "yyyy-mm-ddThh:MM:ssZ"
501+ & example ?~ toJSON (UTCTime (fromGregorian 2016 7 22) 0)
337
502
338instance ToSchema T.Text where declareNamedSchema = plain . paramSchemaToSchema
503instance ToSchema T.Text where declareNamedSchema = plain . paramSchemaToSchema
339instance ToSchema TL.Text where declareNamedSchema = plain . paramSchemaToSchema
504instance ToSchema TL.Text where declareNamedSchema = plain . paramSchemaToSchema
340
505
506+instance ToSchema Version where declareNamedSchema = plain . paramSchemaToSchema
507+
508+#if __GLASGOW_HASKELL__ < 800
509+#else
510+type family ToSchemaByteStringError bs where
511+ ToSchemaByteStringError bs = TypeError
512+ ( Text "Impossible to have an instance " :<>: ShowType (ToSchema bs) :<>: Text "."
513+ :$$: Text "Please, use a newtype wrapper around " :<>: ShowType bs :<>: Text " instead."
514+ :$$: Text "Consider using byteSchema or binarySchema templates." )
515+
516+instance ToSchemaByteStringError BS.ByteString => ToSchema BS.ByteString where declareNamedSchema = error "impossible"
517+instance ToSchemaByteStringError BSL.ByteString => ToSchema BSL.ByteString where declareNamedSchema = error "impossible"
518+#endif
519+
341instance ToSchema IntSet where declareNamedSchema _ = declareNamedSchema (Proxy :: Proxy (Set Int))
520instance ToSchema IntSet where declareNamedSchema _ = declareNamedSchema (Proxy :: Proxy (Set Int))
342
521
343-- | NOTE: This schema does not account for the uniqueness of keys.
522-- | NOTE: This schema does not account for the uniqueness of keys.
344instance ToSchema a => ToSchema (IntMap a) where
523instance ToSchema a => ToSchema (IntMap a) where
345 declareNamedSchema _ = declareNamedSchema (Proxy :: Proxy [(Int, a)])
524 declareNamedSchema _ = declareNamedSchema (Proxy :: Proxy [(Int, a)])
346
525
526+#if MIN_VERSION_aeson(1,0,0)
527+instance (ToJSONKey k, ToSchema k, ToSchema v) => ToSchema (Map k v) where
528+ declareNamedSchema _ = case toJSONKey :: ToJSONKeyFunction k of
529+ ToJSONKeyText _ _ -> declareObjectMapSchema
530+ ToJSONKeyValue _ _ -> declareNamedSchema (Proxy :: Proxy [(k, v)])
531+ where
532+ declareObjectMapSchema = do
533+ schema <- declareSchemaRef (Proxy :: Proxy v)
534+ return $ unnamed $ mempty
535+ & type_ ?~ SwaggerObject
536+ & additionalProperties ?~ AdditionalPropertiesSchema schema
537+
538+instance (ToJSONKey k, ToSchema k, ToSchema v) => ToSchema (HashMap k v) where
539+ declareNamedSchema _ = declareNamedSchema (Proxy :: Proxy (Map k v))
540+
541+#else
542+
347instance ToSchema a => ToSchema (Map String a) where
543instance ToSchema a => ToSchema (Map String a) where
348 declareNamedSchema _ = do
544 declareNamedSchema _ = do
349− schema <- declareSchema (Proxy :: Proxy a)
545+ schema <- declareSchemaRef (Proxy :: Proxy a)
350 return $ unnamed $ mempty
546 return $ unnamed $ mempty
351− & type_ .~ SwaggerObject
547+ & type_ ?~ SwaggerObject
352 & additionalProperties ?~ schema
548 & additionalProperties ?~ schema
353
549
354instance ToSchema a => ToSchema (Map T.Text a) where declareNamedSchema _ = declareNamedSchema (Proxy :: Proxy (Map String a))
550instance ToSchema a => ToSchema (Map T.Text a) where declareNamedSchema _ = declareNamedSchema (Proxy :: Proxy (Map String a))
@@ -358,6 +554,19 @@ instance ToSchema a => ToSchema (HashMap String a) where declareNamedSchema _ =
358instance ToSchema a => ToSchema (HashMap T.Text a) where declareNamedSchema _ = declareNamedSchema (Proxy :: Proxy (Map String a))
554instance ToSchema a => ToSchema (HashMap T.Text a) where declareNamedSchema _ = declareNamedSchema (Proxy :: Proxy (Map String a))
359instance ToSchema a => ToSchema (HashMap TL.Text a) where declareNamedSchema _ = declareNamedSchema (Proxy :: Proxy (Map String a))
555instance ToSchema a => ToSchema (HashMap TL.Text a) where declareNamedSchema _ = declareNamedSchema (Proxy :: Proxy (Map String a))
360
556
557+#endif
558+
559+instance OVERLAPPING_ ToSchema Object where
560+ declareNamedSchema _ = pure $ NamedSchema (Just "Object") $ mempty
561+ & type_ ?~ SwaggerObject
562+ & description ?~ "Arbitrary JSON object."
563+ & additionalProperties ?~ AdditionalPropertiesAllowed True
564+
565+instance ToSchema a => ToSchema (V.Vector a) where declareNamedSchema _ = declareNamedSchema (Proxy :: Proxy [a])
566+instance ToSchema a => ToSchema (VU.Vector a) where declareNamedSchema _ = declareNamedSchema (Proxy :: Proxy [a])
567+instance ToSchema a => ToSchema (VS.Vector a) where declareNamedSchema _ = declareNamedSchema (Proxy :: Proxy [a])
568+instance ToSchema a => ToSchema (VP.Vector a) where declareNamedSchema _ = declareNamedSchema (Proxy :: Proxy [a])
569+
361instance ToSchema a => ToSchema (Set a) where
570instance ToSchema a => ToSchema (Set a) where
362 declareNamedSchema _ = do
571 declareNamedSchema _ = do
363 schema <- declareSchema (Proxy :: Proxy [a])
572 schema <- declareSchema (Proxy :: Proxy [a])
@@ -366,6 +575,13 @@ instance ToSchema a => ToSchema (Set a) where
366
575
367instance ToSchema a => ToSchema (HashSet a) where declareNamedSchema _ = declareNamedSchema (Proxy :: Proxy (Set a))
576instance ToSchema a => ToSchema (HashSet a) where declareNamedSchema _ = declareNamedSchema (Proxy :: Proxy (Set a))
368
577
578+-- | @since 2.2.1
579+instance ToSchema a => ToSchema (NonEmpty a) where
580+ declareNamedSchema _ = do
581+ schema <- declareSchema (Proxy :: Proxy [a])
582+ return $ unnamed $ schema
583+ & minItems .~ Just 1
584+
369instance ToSchema All where declareNamedSchema = plain . paramSchemaToSchema
585instance ToSchema All where declareNamedSchema = plain . paramSchemaToSchema
370instance ToSchema Any where declareNamedSchema = plain . paramSchemaToSchema
586instance ToSchema Any where declareNamedSchema = plain . paramSchemaToSchema
371
587
@@ -375,67 +591,147 @@ instance ToSchema a => ToSchema (First a) where declareNamedSchema _ = unname
375instance ToSchema a => ToSchema (Last a) where declareNamedSchema _ = unname <$> declareNamedSchema (Proxy :: Proxy a)
591instance ToSchema a => ToSchema (Last a) where declareNamedSchema _ = unname <$> declareNamedSchema (Proxy :: Proxy a)
376instance ToSchema a => ToSchema (Dual a) where declareNamedSchema _ = unname <$> declareNamedSchema (Proxy :: Proxy a)
592instance ToSchema a => ToSchema (Dual a) where declareNamedSchema _ = unname <$> declareNamedSchema (Proxy :: Proxy a)
377
593
594+instance ToSchema a => ToSchema (Identity a) where declareNamedSchema _ = declareNamedSchema (Proxy :: Proxy a)
595+
378-- | Default schema for @'Bounded'@, @'Integral'@ types.
596-- | Default schema for @'Bounded'@, @'Integral'@ types.
379--
597--
380-- >>> encode $ toSchemaBoundedIntegral (Proxy :: Proxy Int16)
598-- >>> encode $ toSchemaBoundedIntegral (Proxy :: Proxy Int16)
381-- "{\"maximum\":32767,\"minimum\":-32768,\"type\":\"integer\"}"
599-- "{\"maximum\":32767,\"minimum\":-32768,\"type\":\"integer\"}"
382−toSchemaBoundedIntegral :: forall a proxy. (Bounded a, Integral a) => proxy a -> Schema
600+toSchemaBoundedIntegral :: forall a. (Bounded a, Integral a) => Proxy a -> Schema
383toSchemaBoundedIntegral _ = mempty
601toSchemaBoundedIntegral _ = mempty
384− & type_ .~ SwaggerInteger
602+ & type_ ?~ SwaggerInteger
385 & minimum_ ?~ fromInteger (toInteger (minBound :: a))
603 & minimum_ ?~ fromInteger (toInteger (minBound :: a))
386 & maximum_ ?~ fromInteger (toInteger (maxBound :: a))
604 & maximum_ ?~ fromInteger (toInteger (maxBound :: a))
387
605
388-- | Default generic named schema for @'Bounded'@, @'Integral'@ types.
606-- | Default generic named schema for @'Bounded'@, @'Integral'@ types.
389−genericToNamedSchemaBoundedIntegral :: forall a d f proxy.
607+genericToNamedSchemaBoundedIntegral :: forall a d f.
390 ( Bounded a, Integral a
608 ( Bounded a, Integral a
391 , Generic a, Rep a ~ D1 d f, Datatype d)
609 , Generic a, Rep a ~ D1 d f, Datatype d)
392− => SchemaOptions -> proxy a -> NamedSchema
610+ => SchemaOptions -> Proxy a -> NamedSchema
393genericToNamedSchemaBoundedIntegral opts proxy
611genericToNamedSchemaBoundedIntegral opts proxy
394− = NamedSchema (gdatatypeSchemaName opts (Proxy :: Proxy d)) (toSchemaBoundedIntegral proxy)
612+ = genericNameSchema opts proxy (toSchemaBoundedIntegral proxy)
613+
614+-- | Declare a named schema for a @newtype@ wrapper.
615+genericDeclareNamedSchemaNewtype :: forall a d c s i inner.
616+ (Generic a, Datatype d, Rep a ~ D1 d (C1 c (S1 s (K1 i inner))))
617+ => SchemaOptions -- ^ How to derive the name.
618+ -> (Proxy inner -> Declare (Definitions Schema) Schema) -- ^ How to create a schema for the wrapped type.
619+ -> Proxy a
620+ -> Declare (Definitions Schema) NamedSchema
621+genericDeclareNamedSchemaNewtype opts f proxy = genericNameSchema opts proxy <$> f (Proxy :: Proxy inner)
622+
623+-- | Declare 'Schema' for a mapping with 'Bounded' 'Enum' keys.
624+-- This makes a much more useful schema when there aren't many options for key values.
625+--
626+-- >>> data ButtonState = Neutral | Focus | Active | Hover | Disabled deriving (Show, Bounded, Enum, Generic)
627+-- >>> instance ToJSON ButtonState
628+-- >>> instance ToSchema ButtonState
629+-- >>> instance ToJSONKey ButtonState where toJSONKey = toJSONKeyText (T.pack . show)
630+-- >>> type ImageUrl = T.Text
631+-- >>> encode $ toSchemaBoundedEnumKeyMapping (Proxy :: Proxy (Map ButtonState ImageUrl))
632+-- "{\"properties\":{\"Neutral\":{\"type\":\"string\"},\"Focus\":{\"type\":\"string\"},\"Active\":{\"type\":\"string\"},\"Hover\":{\"type\":\"string\"},\"Disabled\":{\"type\":\"string\"}},\"type\":\"object\"}"
633+--
634+-- Note: this is only useful when @key@ is encoded with 'ToJSONKeyText'.
635+-- If it is encoded with 'ToJSONKeyValue' then a regular schema for @[(key, value)]@ is used.
636+declareSchemaBoundedEnumKeyMapping :: forall map key value.
637+ (Bounded key, Enum key, ToJSONKey key, ToSchema key, ToSchema value)
638+ => Proxy (map key value) -> Declare (Definitions Schema) Schema
639+declareSchemaBoundedEnumKeyMapping _ = case toJSONKey :: ToJSONKeyFunction key of
640+ ToJSONKeyText keyToText _ -> objectSchema keyToText
641+ ToJSONKeyValue _ _ -> declareSchema (Proxy :: Proxy [(key, value)])
642+ where
643+ objectSchema keyToText = do
644+ valueRef <- declareSchemaRef (Proxy :: Proxy value)
645+ let allKeys = [minBound..maxBound :: key]
646+ mkPair k = (keyToText k, valueRef)
647+ return $ mempty
648+ & type_ ?~ SwaggerObject
649+ & properties .~ InsOrdHashMap.fromList (map mkPair allKeys)
650+
651+-- | A 'Schema' for a mapping with 'Bounded' 'Enum' keys.
652+-- This makes a much more useful schema when there aren't many options for key values.
653+--
654+-- >>> data ButtonState = Neutral | Focus | Active | Hover | Disabled deriving (Show, Bounded, Enum, Generic)
655+-- >>> instance ToJSON ButtonState
656+-- >>> instance ToSchema ButtonState
657+-- >>> instance ToJSONKey ButtonState where toJSONKey = toJSONKeyText (T.pack . show)
658+-- >>> type ImageUrl = T.Text
659+-- >>> encode $ toSchemaBoundedEnumKeyMapping (Proxy :: Proxy (Map ButtonState ImageUrl))
660+-- "{\"properties\":{\"Neutral\":{\"type\":\"string\"},\"Focus\":{\"type\":\"string\"},\"Active\":{\"type\":\"string\"},\"Hover\":{\"type\":\"string\"},\"Disabled\":{\"type\":\"string\"}},\"type\":\"object\"}"
661+--
662+-- Note: this is only useful when @key@ is encoded with 'ToJSONKeyText'.
663+-- If it is encoded with 'ToJSONKeyValue' then a regular schema for @[(key, value)]@ is used.
664+toSchemaBoundedEnumKeyMapping :: forall map key value.
665+ (Bounded key, Enum key, ToJSONKey key, ToSchema key, ToSchema value)
666+ => Proxy (map key value) -> Schema
667+toSchemaBoundedEnumKeyMapping = flip evalDeclare mempty . declareSchemaBoundedEnumKeyMapping
395
668
396-- | A configurable generic @'Schema'@ creator.
669-- | A configurable generic @'Schema'@ creator.
670+genericDeclareSchema :: (Generic a, GToSchema (Rep a), TypeHasSimpleShape a "genericDeclareSchemaUnrestricted") =>
397−genericDeclareSchema :: (Generic a, GToSchema (Rep a)) => SchemaOptions -> proxy a -> Declare (Definitions Schema) Schema
671+ SchemaOptions -> Proxy a -> Declare (Definitions Schema) Schema
398−genericDeclareSchema opts proxy = _namedSchemaSchema <$> genericDeclareNamedSchema opts proxy
672+genericDeclareSchema = genericDeclareSchemaUnrestricted
399
673
400-- | A configurable generic @'NamedSchema'@ creator.
674-- | A configurable generic @'NamedSchema'@ creator.
401-- This function applied to @'defaultSchemaOptions'@
675-- This function applied to @'defaultSchemaOptions'@
402-- is used as the default for @'declareNamedSchema'@
676-- is used as the default for @'declareNamedSchema'@
403-- when the type is an instance of @'Generic'@.
677-- when the type is an instance of @'Generic'@.
678+genericDeclareNamedSchema :: (Generic a, GToSchema (Rep a), TypeHasSimpleShape a "genericDeclareNamedSchemaUnrestricted") =>
404−genericDeclareNamedSchema :: forall a proxy. (Generic a, GToSchema (Rep a)) => SchemaOptions -> proxy a -> Declare (Definitions Schema) NamedSchema
679+ SchemaOptions -> Proxy a -> Declare (Definitions Schema) NamedSchema
405−genericDeclareNamedSchema opts _ = gdeclareNamedSchema opts (Proxy :: Proxy (Rep a)) mempty
680+genericDeclareNamedSchema = genericDeclareNamedSchemaUnrestricted
406
681
682+-- | A configurable generic @'Schema'@ creator.
683+--
684+-- Unlike 'genericDeclareSchema' also works for mixed sum types.
685+-- Use with care since some Swagger tools do not support well schemas for mixed sum types.
686+genericDeclareSchemaUnrestricted :: (Generic a, GToSchema (Rep a)) => SchemaOptions -> Proxy a -> Declare (Definitions Schema) Schema
687+genericDeclareSchemaUnrestricted opts proxy = _namedSchemaSchema <$> genericDeclareNamedSchemaUnrestricted opts proxy
688+
689+-- | A configurable generic @'NamedSchema'@ creator.
690+--
691+-- Unlike 'genericDeclareNamedSchema' also works for mixed sum types.
692+-- Use with care since some Swagger tools do not support well schemas for mixed sum types.
693+genericDeclareNamedSchemaUnrestricted :: forall a. (Generic a, GToSchema (Rep a)) =>
694+ SchemaOptions -> Proxy a -> Declare (Definitions Schema) NamedSchema
695+genericDeclareNamedSchemaUnrestricted opts _ = gdeclareNamedSchema opts (Proxy :: Proxy (Rep a)) mempty
696+
697+-- | Derive a 'Generic'-based name for a datatype and assign it to a given 'Schema'.
698+genericNameSchema :: forall a d f.
699+ (Generic a, Rep a ~ D1 d f, Datatype d)
700+ => SchemaOptions -> Proxy a -> Schema -> NamedSchema
701+genericNameSchema opts _ = NamedSchema (gdatatypeSchemaName opts (Proxy :: Proxy d))
702+
407−gdatatypeSchemaName :: forall proxy d. Datatype d => SchemaOptions -> proxy d -> Maybe T.Text
703+gdatatypeSchemaName :: forall d. Datatype d => SchemaOptions -> Proxy d -> Maybe T.Text
408−gdatatypeSchemaName opts _ = case name of
704+gdatatypeSchemaName opts _ = case orig of
409 (c:_) | isAlpha c && isUpper c -> Just (T.pack name)
705 (c:_) | isAlpha c && isUpper c -> Just (T.pack name)
410 _ -> Nothing
706 _ -> Nothing
411 where
707 where
412− name = datatypeNameModifier opts (datatypeName (Proxy3 :: Proxy3 d f a))
708+ orig = datatypeName (Proxy3 :: Proxy3 d f a)
709+ name = datatypeNameModifier opts orig
413
710
414-- | Lift a plain @'ParamSchema'@ into a model @'NamedSchema'@.
711-- | Lift a plain @'ParamSchema'@ into a model @'NamedSchema'@.
415−paramSchemaToNamedSchema :: forall a d f proxy.
416− (ToParamSchema a, Generic a, Rep a ~ D1 d f, Datatype d)
712+paramSchemaToNamedSchema :: (ToParamSchema a, Generic a, Rep a ~ D1 d f, Datatype d) =>
417− => SchemaOptions -> proxy a -> NamedSchema
713+ SchemaOptions -> Proxy a -> NamedSchema
418−paramSchemaToNamedSchema opts proxy = NamedSchema (gdatatypeSchemaName opts (Proxy :: Proxy d)) (paramSchemaToSchema proxy)
714+paramSchemaToNamedSchema opts proxy = genericNameSchema opts proxy (paramSchemaToSchema proxy)
419
715
420-- | Lift a plain @'ParamSchema'@ into a model @'Schema'@.
716-- | Lift a plain @'ParamSchema'@ into a model @'Schema'@.
421−paramSchemaToSchema :: forall a proxy. ToParamSchema a => proxy a -> Schema
717+paramSchemaToSchema :: ToParamSchema a => Proxy a -> Schema
422−paramSchemaToSchema _ = mempty & paramSchema .~ toParamSchema (Proxy :: Proxy a)
718+paramSchemaToSchema proxy = mempty & paramSchema .~ toParamSchema proxy
423
719
424nullarySchema :: Schema
720nullarySchema :: Schema
425nullarySchema = mempty
721nullarySchema = mempty
426− & type_ .~ SwaggerArray
722+ & type_ ?~ SwaggerArray
427 & items ?~ SwaggerItemsArray []
723 & items ?~ SwaggerItemsArray []
428
724
429−gtoNamedSchema :: GToSchema f => SchemaOptions -> proxy f -> NamedSchema
725+gtoNamedSchema :: GToSchema f => SchemaOptions -> Proxy f -> NamedSchema
430gtoNamedSchema opts proxy = undeclare $ gdeclareNamedSchema opts proxy mempty
726gtoNamedSchema opts proxy = undeclare $ gdeclareNamedSchema opts proxy mempty
431
727
432−gdeclareSchema :: GToSchema f => SchemaOptions -> proxy f -> Declare (Definitions Schema) Schema
728+gdeclareSchema :: GToSchema f => SchemaOptions -> Proxy f -> Declare (Definitions Schema) Schema
433gdeclareSchema opts proxy = _namedSchemaSchema <$> gdeclareNamedSchema opts proxy mempty
729gdeclareSchema opts proxy = _namedSchemaSchema <$> gdeclareNamedSchema opts proxy mempty
434
730
435instance (GToSchema f, GToSchema g) => GToSchema (f :*: g) where
731instance (GToSchema f, GToSchema g) => GToSchema (f :*: g) where
436 gdeclareNamedSchema opts _ schema = do
732 gdeclareNamedSchema opts _ schema = do
437− NamedSchema _ gschema <- gdeclareNamedSchema opts (Proxy :: Proxy g) schema
733+ NamedSchema _ gschema <- gdeclareNamedSchema opts (Proxy :: Proxy f) schema
438− gdeclareNamedSchema opts (Proxy :: Proxy f) gschema
734+ gdeclareNamedSchema opts (Proxy :: Proxy g) gschema
439
735
440instance (Datatype d, GToSchema f) => GToSchema (D1 d f) where
736instance (Datatype d, GToSchema f) => GToSchema (D1 d f) where
441 gdeclareNamedSchema opts _ s = rename name <$> gdeclareNamedSchema opts (Proxy :: Proxy f) s
737 gdeclareNamedSchema opts _ s = rename name <$> gdeclareNamedSchema opts (Proxy :: Proxy f) s
@@ -449,7 +745,7 @@ instance OVERLAPPING_ Constructor c => GToSchema (C1 c U1) where
449 gdeclareNamedSchema = gdeclareNamedSumSchema
745 gdeclareNamedSchema = gdeclareNamedSumSchema
450
746
451-- | Single field constructor.
747-- | Single field constructor.
452−instance (Selector s, GToSchema f) => GToSchema (C1 c (S1 s f)) where
748+instance (Selector s, GToSchema f, GToSchema (S1 s f)) => GToSchema (C1 c (S1 s f)) where
453 gdeclareNamedSchema opts _ s
749 gdeclareNamedSchema opts _ s
454 | unwrapUnaryRecords opts = fieldSchema
750 | unwrapUnaryRecords opts = fieldSchema
455 | otherwise =
751 | otherwise =
@@ -463,7 +759,7 @@ instance (Selector s, GToSchema f) => GToSchema (C1 c (S1 s f)) where
463 recordSchema = gdeclareNamedSchema opts (Proxy :: Proxy (S1 s f)) s
759 recordSchema = gdeclareNamedSchema opts (Proxy :: Proxy (S1 s f)) s
464 fieldSchema = gdeclareNamedSchema opts (Proxy :: Proxy f) s
760 fieldSchema = gdeclareNamedSchema opts (Proxy :: Proxy f) s
465
761
466−gdeclareSchemaRef :: GToSchema a => SchemaOptions -> proxy a -> Declare (Definitions Schema) (Referenced Schema)
762+gdeclareSchemaRef :: GToSchema a => SchemaOptions -> Proxy a -> Declare (Definitions Schema) (Referenced Schema)
467gdeclareSchemaRef opts proxy = do
763gdeclareSchemaRef opts proxy = do
468 case gtoNamedSchema opts proxy of
764 case gtoNamedSchema opts proxy of
469 NamedSchema (Just name) schema -> do
765 NamedSchema (Just name) schema -> do
@@ -475,16 +771,16 @@ gdeclareSchemaRef opts proxy = do
475 -- have already declared it.
771 -- have already declared it.
476 -- If we have, we don't need to declare anything for
772 -- If we have, we don't need to declare anything for
477 -- this schema this time and thus simply return the reference.
773 -- this schema this time and thus simply return the reference.
478− known <- looks (HashMap.member name)
774+ known <- looks (InsOrdHashMap.member name)
479 when (not known) $ do
775 when (not known) $ do
480 declare [(name, schema)]
776 declare [(name, schema)]
481 void $ gdeclareNamedSchema opts proxy mempty
777 void $ gdeclareNamedSchema opts proxy mempty
482 return $ Ref (Reference name)
778 return $ Ref (Reference name)
483 _ -> Inline <$> gdeclareSchema opts proxy
779 _ -> Inline <$> gdeclareSchema opts proxy
484
780
485−appendItem :: Referenced Schema -> Maybe (SwaggerItems Schema) -> Maybe (SwaggerItems Schema)
781+appendItem :: Referenced Schema -> Maybe (SwaggerItems 'SwaggerKindSchema) -> Maybe (SwaggerItems 'SwaggerKindSchema)
486appendItem x Nothing = Just (SwaggerItemsArray [x])
782appendItem x Nothing = Just (SwaggerItemsArray [x])
487−appendItem x (Just (SwaggerItemsArray xs)) = Just (SwaggerItemsArray (x:xs))
783+appendItem x (Just (SwaggerItemsArray xs)) = Just (SwaggerItemsArray (xs ++ [x]))
488appendItem _ _ = error "GToSchema.appendItem: cannot append to SwaggerItemsObject"
784appendItem _ _ = error "GToSchema.appendItem: cannot append to SwaggerItemsObject"
489
785
490withFieldSchema :: forall proxy s f. (Selector s, GToSchema f) =>
786withFieldSchema :: forall proxy s f. (Selector s, GToSchema f) =>
@@ -494,13 +790,15 @@ withFieldSchema opts _ isRequiredField schema = do
494 return $
790 return $
495 if T.null fname
791 if T.null fname
496 then schema
792 then schema
497− & type_ .~ SwaggerArray
793+ & type_ ?~ SwaggerArray
498 & items %~ appendItem ref
794 & items %~ appendItem ref
795+ & maxItems %~ Just . maybe 1 (+1) -- increment maxItems
796+ & minItems %~ Just . maybe 1 (+1) -- increment minItems
499 else schema
797 else schema
500− & type_ .~ SwaggerObject
798+ & type_ ?~ SwaggerObject
501 & properties . at fname ?~ ref
799 & properties . at fname ?~ ref
502 & if isRequiredField
800 & if isRequiredField
503− then required %~ (fname :)
801+ then required %~ (++ [fname])
504 else id
802 else id
505 where
803 where
506 fname = T.pack (fieldLabelModifier opts (selName (Proxy3 :: Proxy3 s f p)))
804 fname = T.pack (fieldLabelModifier opts (selName (Proxy3 :: Proxy3 s f p)))
@@ -519,10 +817,13 @@ instance OVERLAPPING_ ToSchema c => GToSchema (K1 i (Maybe c)) where
519instance OVERLAPPABLE_ ToSchema c => GToSchema (K1 i c) where
817instance OVERLAPPABLE_ ToSchema c => GToSchema (K1 i c) where
520 gdeclareNamedSchema _ _ _ = declareNamedSchema (Proxy :: Proxy c)
818 gdeclareNamedSchema _ _ _ = declareNamedSchema (Proxy :: Proxy c)
521
819
522−instance (GSumToSchema f, GSumToSchema g) => GToSchema (f :+: g) where
820+instance ( GSumToSchema f
821+ , GSumToSchema g
822+ ) => GToSchema (f :+: g)
823+ where
523 gdeclareNamedSchema = gdeclareNamedSumSchema
824 gdeclareNamedSchema = gdeclareNamedSumSchema
524
825
525−gdeclareNamedSumSchema :: GSumToSchema f => SchemaOptions -> proxy f -> Schema -> Declare (Definitions Schema) NamedSchema
826+gdeclareNamedSumSchema :: GSumToSchema f => SchemaOptions -> Proxy f -> Schema -> Declare (Definitions Schema) NamedSchema
526gdeclareNamedSumSchema opts proxy s
827gdeclareNamedSumSchema opts proxy s
527 | allNullaryToStringTag opts && allNullary = pure $ unnamed (toStringTag sumSchema)
828 | allNullaryToStringTag opts && allNullary = pure $ unnamed (toStringTag sumSchema)
528 | otherwise = (unnamed . fst) <$> runWriterT declareSumSchema
829 | otherwise = (unnamed . fst) <$> runWriterT declareSumSchema
@@ -531,29 +832,29 @@ gdeclareNamedSumSchema opts proxy s
531 (sumSchema, All allNullary) = undeclare (runWriterT declareSumSchema)
832 (sumSchema, All allNullary) = undeclare (runWriterT declareSumSchema)
532
833
533 toStringTag schema = mempty
834 toStringTag schema = mempty
534− & type_ .~ SwaggerString
835+ & type_ ?~ SwaggerString
535− & enum_ ?~ map toJSON (schema ^.. properties.ifolded.asIndex)
836+ & enum_ ?~ map toJSON (schema ^.. properties.ifolded.asIndex)
536
837
537type AllNullary = All
838type AllNullary = All
538
839
539−class GSumToSchema f where
840+class GSumToSchema (f :: * -> *) where
540− gsumToSchema :: SchemaOptions -> proxy f -> Schema -> WriterT AllNullary (Declare (Definitions Schema)) Schema
841+ gsumToSchema :: SchemaOptions -> Proxy f -> Schema -> WriterT AllNullary (Declare (Definitions Schema)) Schema
541
842
542instance (GSumToSchema f, GSumToSchema g) => GSumToSchema (f :+: g) where
843instance (GSumToSchema f, GSumToSchema g) => GSumToSchema (f :+: g) where
543− gsumToSchema opts _ = gsumToSchema opts (Proxy :: Proxy f) <=< gsumToSchema opts (Proxy :: Proxy g)
844+ gsumToSchema opts _ = gsumToSchema opts (Proxy :: Proxy f) >=> gsumToSchema opts (Proxy :: Proxy g)
544
845
545−gsumConToSchemaWith :: forall c f proxy. (GToSchema (C1 c f), Constructor c) =>
846+gsumConToSchemaWith :: forall c f. (GToSchema (C1 c f), Constructor c) =>
546− Referenced Schema -> SchemaOptions -> proxy (C1 c f) -> Schema -> Schema
847+ Referenced Schema -> SchemaOptions -> Proxy (C1 c f) -> Schema -> Schema
547gsumConToSchemaWith ref opts _ schema = schema
848gsumConToSchemaWith ref opts _ schema = schema
548− & type_ .~ SwaggerObject
849+ & type_ ?~ SwaggerObject
549 & properties . at tag ?~ ref
850 & properties . at tag ?~ ref
550 & maxProperties ?~ 1
851 & maxProperties ?~ 1
551 & minProperties ?~ 1
852 & minProperties ?~ 1
552 where
853 where
553 tag = T.pack (constructorTagModifier opts (conName (Proxy3 :: Proxy3 c f p)))
854 tag = T.pack (constructorTagModifier opts (conName (Proxy3 :: Proxy3 c f p)))
554
855
555−gsumConToSchema :: forall c f proxy. (GToSchema (C1 c f), Constructor c) =>
856+gsumConToSchema :: (GToSchema (C1 c f), Constructor c) =>
556− SchemaOptions -> proxy (C1 c f) -> Schema -> Declare (Definitions Schema) Schema
857+ SchemaOptions -> Proxy (C1 c f) -> Schema -> Declare (Definitions Schema) Schema
557gsumConToSchema opts proxy schema = do
858gsumConToSchema opts proxy schema = do
558 ref <- gdeclareSchemaRef opts proxy
859 ref <- gdeclareSchemaRef opts proxy
559 return $ gsumConToSchemaWith ref opts proxy schema
860 return $ gsumConToSchemaWith ref opts proxy schema
@@ -575,3 +876,7 @@ data Proxy2 a b = Proxy2
575
876
576data Proxy3 a b c = Proxy3
877data Proxy3 a b c = Proxy3
577
878
879+-- $setup
880+-- >>> import Data.Swagger
881+-- >>> import Data.Aeson (encode)
882+-- >>> import Data.Aeson.Types (toJSONKeyText)
src/Data/Swagger/Internal/Schema/Validation.hsnew file+511
@@ -0,0 +1,511 @@
1+{-# OPTIONS_GHC -Wall #-}
2+{-# LANGUAGE DataKinds #-}
3+{-# LANGUAGE DeriveFunctor #-}
4+{-# LANGUAGE FlexibleInstances #-}
5+{-# LANGUAGE FunctionalDependencies #-}
6+{-# LANGUAGE GADTs #-}
7+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
8+{-# LANGUAGE LambdaCase #-}
9+{-# LANGUAGE MultiParamTypeClasses #-}
10+{-# LANGUAGE PackageImports #-}
11+{-# LANGUAGE RankNTypes #-}
12+{-# LANGUAGE ScopedTypeVariables #-}
13+{-# LANGUAGE TemplateHaskell #-}
14+{-# LANGUAGE UndecidableInstances #-}
15+-- |
16+-- Module: Data.Swagger.Internal.Schema.Validation
17+-- Copyright: (c) 2015 GetShopTV
18+-- License: BSD3
19+-- Maintainer: Nickolay Kudasov <nickolay@getshoptv.com>
20+-- Stability: experimental
21+--
22+-- Validate JSON values with Swagger Schema.
23+module Data.Swagger.Internal.Schema.Validation where
24+
25+import Prelude ()
26+import Prelude.Compat
27+
28+import Control.Applicative
29+import Control.Lens
30+import Control.Monad (when)
31+
32+import Data.Aeson hiding (Result)
33+import Data.Aeson.Encode.Pretty (encodePretty)
34+import Data.Foldable (for_, sequenceA_,
35+ traverse_)
36+import Data.HashMap.Strict (HashMap)
37+import qualified Data.HashMap.Strict as HashMap
38+import qualified Data.HashMap.Strict.InsOrd as InsOrdHashMap
39+import qualified "unordered-containers" Data.HashSet as HashSet
40+import Data.Proxy
41+import Data.Scientific (Scientific, isInteger)
42+import Data.Text (Text)
43+import qualified Data.Text as Text
44+import qualified Data.Text.Lazy as TL
45+import qualified Data.Text.Lazy.Encoding as TL
46+import Data.Vector (Vector)
47+import qualified Data.Vector as Vector
48+
49+import Data.Swagger.Declare
50+import Data.Swagger.Internal
51+import Data.Swagger.Internal.Schema
52+import Data.Swagger.Lens
53+
54+-- | Validate @'ToJSON'@ instance matches @'ToSchema'@ for a given value.
55+-- This can be used with QuickCheck to ensure those instances are coherent:
56+--
57+-- prop> validateToJSON (x :: Int) == []
58+--
59+-- /NOTE:/ @'validateToJSON'@ does not perform string pattern validation.
60+-- See @'validateToJSONWithPatternChecker'@.
61+--
62+-- See 'renderValidationErrors' on how the output is structured.
63+validatePrettyToJSON :: forall a. (ToJSON a, ToSchema a) => a -> Maybe String
64+validatePrettyToJSON = renderValidationErrors validateToJSON
65+
66+-- | Variant of 'validatePrettyToJSON' with typed output.
67+validateToJSON :: forall a. (ToJSON a, ToSchema a) => a -> [ValidationError]
68+validateToJSON = validateToJSONWithPatternChecker (\_pattern _str -> True)
69+
70+-- | Validate @'ToJSON'@ instance matches @'ToSchema'@ for a given value and pattern checker.
71+-- This can be used with QuickCheck to ensure those instances are coherent.
72+--
73+-- For validation without patterns see @'validateToJSON'@. See also:
74+-- 'renderValidationErrors'.
75+validateToJSONWithPatternChecker :: forall a. (ToJSON a, ToSchema a) => (Pattern -> Text -> Bool) -> a -> [ValidationError]
76+validateToJSONWithPatternChecker checker = validateJSONWithPatternChecker checker defs sch . toJSON
77+ where
78+ (defs, sch) = runDeclare (declareSchema (Proxy :: Proxy a)) mempty
79+
80+-- | Pretty print validation errors
81+-- together with actual JSON and Swagger Schema
82+-- (using 'encodePretty').
83+--
84+-- >>> import Data.Aeson as Aeson
85+-- >>> import Data.Foldable (traverse_)
86+-- >>> import GHC.Generics
87+-- >>> data Phone = Phone { value :: String } deriving (Generic)
88+-- >>> data Person = Person { name :: String, phone :: Phone } deriving (Generic)
89+-- >>> instance ToJSON Person where toJSON p = object [ "name" Aeson..= name p ]
90+-- >>> instance ToSchema Phone
91+-- >>> instance ToSchema Person
92+-- >>> let person = Person { name = "John", phone = Phone "123456" }
93+-- >>> traverse_ putStrLn $ renderValidationErrors validateToJSON person
94+-- Validation against the schema fails:
95+-- * property "phone" is required, but not found in "{\"name\":\"John\"}"
96+-- <BLANKLINE>
97+-- JSON value:
98+-- {
99+-- "name": "John"
100+-- }
101+-- <BLANKLINE>
102+-- Swagger Schema:
103+-- {
104+-- "required": [
105+-- "name",
106+-- "phone"
107+-- ],
108+-- "type": "object",
109+-- "properties": {
110+-- "phone": {
111+-- "$ref": "#/definitions/Phone"
112+-- },
113+-- "name": {
114+-- "type": "string"
115+-- }
116+-- }
117+-- }
118+-- <BLANKLINE>
119+-- Swagger Description Context:
120+-- {
121+-- "Phone": {
122+-- "required": [
123+-- "value"
124+-- ],
125+-- "type": "object",
126+-- "properties": {
127+-- "value": {
128+-- "type": "string"
129+-- }
130+-- }
131+-- }
132+-- }
133+-- <BLANKLINE>
134+renderValidationErrors
135+ :: forall a. (ToJSON a, ToSchema a)
136+ => (a -> [ValidationError]) -> a -> Maybe String
137+renderValidationErrors f x =
138+ case f x of
139+ [] -> Nothing
140+ errors -> Just $ unlines
141+ [ "Validation against the schema fails:"
142+ , unlines (map (" * " ++) errors)
143+ , "JSON value:"
144+ , ppJSONString (toJSON x)
145+ , ""
146+ , "Swagger Schema:"
147+ , ppJSONString (toJSON schema_)
148+ , ""
149+ , "Swagger Description Context:"
150+ , ppJSONString (toJSON refs_)
151+ ]
152+ where
153+ ppJSONString = TL.unpack . TL.decodeUtf8 . encodePretty
154+ (refs_, schema_) = runDeclare (declareSchema (Proxy :: Proxy a)) mempty
155+
156+-- | Validate JSON @'Value'@ against Swagger @'Schema'@.
157+--
158+-- prop> validateJSON mempty (toSchema (Proxy :: Proxy Int)) (toJSON (x :: Int)) == []
159+--
160+-- /NOTE:/ @'validateJSON'@ does not perform string pattern validation.
161+-- See @'validateJSONWithPatternChecker'@.
162+validateJSON :: Definitions Schema -> Schema -> Value -> [ValidationError]
163+validateJSON = validateJSONWithPatternChecker (\_pattern _str -> True)
164+
165+-- | Validate JSON @'Value'@ agains Swagger @'ToSchema'@ for a given value and pattern checker.
166+--
167+-- For validation without patterns see @'validateJSON'@.
168+validateJSONWithPatternChecker :: (Pattern -> Text -> Bool) -> Definitions Schema -> Schema -> Value -> [ValidationError]
169+validateJSONWithPatternChecker checker defs sch js =
170+ case runValidation (validateWithSchema js) cfg sch of
171+ Failed xs -> xs
172+ Passed _ -> mempty
173+ where
174+ cfg = defaultConfig
175+ { configPatternChecker = checker
176+ , configDefinitions = defs }
177+
178+-- | Validation error message.
179+type ValidationError = String
180+
181+-- | Validation result type.
182+data Result a
183+ = Failed [ValidationError] -- ^ Validation failed with a list of error messages.
184+ | Passed a -- ^ Validation passed.
185+ deriving (Eq, Show, Functor)
186+
187+instance Applicative Result where
188+ pure = Passed
189+ Passed f <*> Passed x = Passed (f x)
190+ Failed xs <*> Failed ys = Failed (xs <> ys)
191+ Failed xs <*> _ = Failed xs
192+ _ <*> Failed ys = Failed ys
193+
194+instance Alternative Result where
195+ empty = Failed mempty
196+ Passed x <|> _ = Passed x
197+ _ <|> y = y
198+
199+instance Monad Result where
200+ return = pure
201+ Passed x >>= f = f x
202+ Failed xs >>= _ = Failed xs
203+
204+-- | Validation configuration.
205+data Config = Config
206+ { -- | Pattern checker for @'_paramSchemaPattern'@ validation.
207+ configPatternChecker :: Pattern -> Text -> Bool
208+ -- | Schema definitions in scope to resolve references.
209+ , configDefinitions :: Definitions Schema
210+ }
211+
212+-- | Default @'Config'@:
213+--
214+-- @
215+-- defaultConfig = 'Config'
216+-- { 'configPatternChecker' = \\_pattern _str -> True
217+-- , 'configDefinitions' = mempty
218+-- }
219+-- @
220+defaultConfig :: Config
221+defaultConfig = Config
222+ { configPatternChecker = \_pattern _str -> True
223+ , configDefinitions = mempty
224+ }
225+
226+-- | Value validation.
227+newtype Validation s a = Validation { runValidation :: Config -> s -> Result a }
228+ deriving (Functor)
229+
230+instance Applicative (Validation schema) where
231+ pure x = Validation (\_ _ -> pure x)
232+ Validation f <*> Validation x = Validation (\c s -> f c s <*> x c s)
233+
234+instance Alternative (Validation schema) where
235+ empty = Validation (\_ _ -> empty)
236+ Validation x <|> Validation y = Validation (\c s -> x c s <|> y c s)
237+
238+instance Profunctor Validation where
239+ dimap f g (Validation k) = Validation (\c s -> fmap g (k c (f s)))
240+
241+instance Choice Validation where
242+ left' (Validation g) = Validation (\c -> either (fmap Left . g c) (pure . Right))
243+ right' (Validation g) = Validation (\c -> either (pure . Left) (fmap Right . g c))
244+
245+instance Monad (Validation s) where
246+ return = pure
247+ Validation x >>= f = Validation (\c s -> x c s >>= \y -> runValidation (f y) c s)
248+ (>>) = (*>)
249+
250+withConfig :: (Config -> Validation s a) -> Validation s a
251+withConfig f = Validation (\c -> runValidation (f c) c)
252+
253+withSchema :: (s -> Validation s a) -> Validation s a
254+withSchema f = Validation (\c s -> runValidation (f s) c s)
255+
256+-- | Issue an error message.
257+invalid :: String -> Validation schema a
258+invalid msg = Validation (\_ _ -> Failed [msg])
259+
260+-- | Validation passed.
261+valid :: Validation schema ()
262+valid = pure ()
263+
264+-- | Validate schema's property given a lens into that property
265+-- and property checker.
266+checkMissing :: Validation s () -> Lens' s (Maybe a) -> (a -> Validation s ()) -> Validation s ()
267+checkMissing missing l g = withSchema $ \sch ->
268+ case sch ^. l of
269+ Nothing -> missing
270+ Just x -> g x
271+
272+-- | Validate schema's property given a lens into that property
273+-- and property checker.
274+-- If property is missing in schema, consider it valid.
275+check :: Lens' s (Maybe a) -> (a -> Validation s ()) -> Validation s ()
276+check = checkMissing valid
277+
278+-- | Validate same value with different schema.
279+sub :: t -> Validation t a -> Validation s a
280+sub = lmap . const
281+
282+-- | Validate same value with a part of the original schema.
283+sub_ :: Getting a s a -> Validation a r -> Validation s r
284+sub_ = lmap . view
285+
286+-- | Validate value against a schema given schema reference and validation function.
287+withRef :: Reference -> (Schema -> Validation s a) -> Validation s a
288+withRef (Reference ref) f = withConfig $ \cfg ->
289+ case InsOrdHashMap.lookup ref (configDefinitions cfg) of
290+ Nothing -> invalid $ "unknown schema " ++ show ref
291+ Just s -> f s
292+
293+validateWithSchemaRef :: Referenced Schema -> Value -> Validation s ()
294+validateWithSchemaRef (Ref ref) js = withRef ref $ \sch -> sub sch (validateWithSchema js)
295+validateWithSchemaRef (Inline s) js = sub s (validateWithSchema js)
296+
297+-- | Validate JSON @'Value'@ with Swagger @'Schema'@.
298+validateWithSchema :: Value -> Validation Schema ()
299+validateWithSchema value = do
300+ validateSchemaType value
301+ sub_ paramSchema $ validateEnum value
302+
303+-- | Validate JSON @'Value'@ with Swagger @'ParamSchema'@.
304+validateWithParamSchema :: Value -> Validation (ParamSchema t) ()
305+validateWithParamSchema value = do
306+ validateParamSchemaType value
307+ validateEnum value
308+
309+validateInteger :: Scientific -> Validation (ParamSchema t) ()
310+validateInteger n = do
311+ when (not (isInteger n)) $
312+ invalid ("not an integer")
313+ validateNumber n
314+
315+validateNumber :: Scientific -> Validation (ParamSchema t) ()
316+validateNumber n = withConfig $ \_cfg -> withSchema $ \sch -> do
317+ let exMax = Just True == sch ^. exclusiveMaximum
318+ exMin = Just True == sch ^. exclusiveMinimum
319+
320+ check maximum_ $ \m ->
321+ when (if exMax then (n >= m) else (n > m)) $
322+ invalid ("value " ++ show n ++ " exceeds maximum (should be " ++ if exMax then "<" else "<=" ++ show m ++ ")")
323+
324+ check minimum_ $ \m ->
325+ when (if exMin then (n <= m) else (n < m)) $
326+ invalid ("value " ++ show n ++ " falls below minimum (should be " ++ if exMin then ">" else ">=" ++ show m ++ ")")
327+
328+ check multipleOf $ \k ->
329+ when (not (isInteger (n / k))) $
330+ invalid ("expected a multiple of " ++ show k ++ " but got " ++ show n)
331+
332+validateString :: Text -> Validation (ParamSchema t) ()
333+validateString s = do
334+ check maxLength $ \n ->
335+ when (len > fromInteger n) $
336+ invalid ("string is too long (length should be <=" ++ show n ++ ")")
337+
338+ check minLength $ \n ->
339+ when (len < fromInteger n) $
340+ invalid ("string is too short (length should be >=" ++ show n ++ ")")
341+
342+ check pattern $ \regex -> do
343+ withConfig $ \cfg -> do
344+ when (not (configPatternChecker cfg regex s)) $
345+ invalid ("string does not match pattern " ++ show regex)
346+ where
347+ len = Text.length s
348+
349+validateArray :: Vector Value -> Validation (ParamSchema t) ()
350+validateArray xs = do
351+ check maxItems $ \n ->
352+ when (len > fromInteger n) $
353+ invalid ("array exceeds maximum size (should be <=" ++ show n ++ ")")
354+
355+ check minItems $ \n ->
356+ when (len < fromInteger n) $
357+ invalid ("array is too short (size should be >=" ++ show n ++ ")")
358+
359+ check items $ \case
360+ SwaggerItemsPrimitive _ itemSchema -> sub itemSchema $ traverse_ validateWithParamSchema xs
361+ SwaggerItemsObject itemSchema -> traverse_ (validateWithSchemaRef itemSchema) xs
362+ SwaggerItemsArray itemSchemas -> do
363+ when (len /= length itemSchemas) $
364+ invalid ("array size is invalid (should be exactly " ++ show (length itemSchemas) ++ ")")
365+ sequenceA_ (zipWith validateWithSchemaRef itemSchemas (Vector.toList xs))
366+
367+ check uniqueItems $ \unique ->
368+ when (unique && not allUnique) $
369+ invalid ("array is expected to contain unique items, but it does not")
370+ where
371+ len = Vector.length xs
372+ allUnique = len == HashSet.size (HashSet.fromList (Vector.toList xs))
373+
374+validateObject :: HashMap Text Value -> Validation Schema ()
375+validateObject o = withSchema $ \sch ->
376+ case sch ^. discriminator of
377+ Just pname -> case fromJSON <$> HashMap.lookup pname o of
378+ Just (Success ref) -> validateWithSchemaRef ref (Object o)
379+ Just (Error msg) -> invalid ("failed to parse discriminator property " ++ show pname ++ ": " ++ show msg)
380+ Nothing -> invalid ("discriminator property " ++ show pname ++ "is missing")
381+ Nothing -> do
382+ check maxProperties $ \n ->
383+ when (size > n) $
384+ invalid ("object size exceeds maximum (total number of properties should be <=" ++ show n ++ ")")
385+
386+ check minProperties $ \n ->
387+ when (size < n) $
388+ invalid ("object size is too small (total number of properties should be >=" ++ show n ++ ")")
389+
390+ validateRequired
391+ validateProps
392+ where
393+ size = fromIntegral (HashMap.size o)
394+
395+ validateRequired = withSchema $ \sch -> traverse_ validateReq (sch ^. required)
396+ validateReq n =
397+ when (not (HashMap.member n o)) $
398+ invalid ("property " ++ show n ++ " is required, but not found in " ++ show (encode o))
399+
400+ validateProps = withSchema $ \sch -> do
401+ for_ (HashMap.toList o) $ \(k, v) ->
402+ case v of
403+ Null | not (k `elem` (sch ^. required)) -> valid -- null is fine for non-required property
404+ _ ->
405+ case InsOrdHashMap.lookup k (sch ^. properties) of
406+ Nothing -> checkMissing (unknownProperty k) additionalProperties $ validateAdditional k v
407+ Just s -> validateWithSchemaRef s v
408+
409+ validateAdditional _ _ (AdditionalPropertiesAllowed True) = valid
410+ validateAdditional k _ (AdditionalPropertiesAllowed False) = invalid $ "additionalProperties=false but extra property " <> show k <> " found"
411+ validateAdditional _ v (AdditionalPropertiesSchema s) = validateWithSchemaRef s v
412+
413+ unknownProperty :: Text -> Validation s a
414+ unknownProperty pname = invalid $
415+ "property " <> show pname <> " is found in JSON value, but it is not mentioned in Swagger schema"
416+
417+validateEnum :: Value -> Validation (ParamSchema t) ()
418+validateEnum value = do
419+ check enum_ $ \xs ->
420+ when (value `notElem` xs) $
421+ invalid ("expected one of " ++ show (encode xs) ++ " but got " ++ show value)
422+
423+-- | Infer schema type based on used properties.
424+--
425+-- This is like 'inferParamSchemaTypes', but also works for objects:
426+--
427+-- >>> inferSchemaTypes <$> decode "{\"minProperties\": 1}"
428+-- Just [SwaggerObject]
429+inferSchemaTypes :: Schema -> [SwaggerType 'SwaggerKindSchema]
430+inferSchemaTypes sch = inferParamSchemaTypes (sch ^. paramSchema) ++
431+ [ SwaggerObject | any ($ sch)
432+ [ has (additionalProperties._Just)
433+ , has (maxProperties._Just)
434+ , has (minProperties._Just)
435+ , has (properties.folded)
436+ , has (required.folded) ] ]
437+
438+-- | Infer schema type based on used properties.
439+--
440+-- >>> inferSchemaTypes <$> decode "{\"minLength\": 2}"
441+-- Just [SwaggerString]
442+--
443+-- >>> inferSchemaTypes <$> decode "{\"maxItems\": 0}"
444+-- Just [SwaggerArray]
445+--
446+-- From numeric properties 'SwaggerInteger' type is inferred.
447+-- If you want 'SwaggerNumber' instead, you must specify it explicitly.
448+--
449+-- >>> inferSchemaTypes <$> decode "{\"minimum\": 1}"
450+-- Just [SwaggerInteger]
451+inferParamSchemaTypes :: ParamSchema t -> [SwaggerType t]
452+inferParamSchemaTypes sch = concat
453+ [ [ SwaggerArray | any ($ sch)
454+ [ has (items._Just)
455+ , has (maxItems._Just)
456+ , has (minItems._Just)
457+ , has (uniqueItems._Just) ] ]
458+ , [ SwaggerInteger | any ($ sch)
459+ [ has (exclusiveMaximum._Just)
460+ , has (exclusiveMinimum._Just)
461+ , has (maximum_._Just)
462+ , has (minimum_._Just)
463+ , has (multipleOf._Just) ] ]
464+ , [ SwaggerString | any ($ sch)
465+ [ has (maxLength._Just)
466+ , has (minLength._Just)
467+ , has (pattern._Just) ] ]
468+ ]
469+
470+validateSchemaType :: Value -> Validation Schema ()
471+validateSchemaType value = withSchema $ \sch ->
472+ case (sch ^. type_, value) of
473+ (Just SwaggerNull, Null) -> valid
474+ (Just SwaggerBoolean, Bool _) -> valid
475+ (Just SwaggerInteger, Number n) -> sub_ paramSchema (validateInteger n)
476+ (Just SwaggerNumber, Number n) -> sub_ paramSchema (validateNumber n)
477+ (Just SwaggerString, String s) -> sub_ paramSchema (validateString s)
478+ (Just SwaggerArray, Array xs) -> sub_ paramSchema (validateArray xs)
479+ (Just SwaggerObject, Object o) -> validateObject o
480+ (Nothing, Null) -> valid
481+ (Nothing, Bool _) -> valid
482+ -- Number by default
483+ (Nothing, Number n) -> sub_ paramSchema (validateNumber n)
484+ (Nothing, String s) -> sub_ paramSchema (validateString s)
485+ (Nothing, Array xs) -> sub_ paramSchema (validateArray xs)
486+ (Nothing, Object o) -> validateObject o
487+ bad -> invalid $ "expected JSON value of type " ++ showType bad
488+
489+validateParamSchemaType :: Value -> Validation (ParamSchema t) ()
490+validateParamSchemaType value = withSchema $ \sch ->
491+ case (sch ^. type_, value) of
492+ (Just SwaggerBoolean, Bool _) -> valid
493+ (Just SwaggerInteger, Number n) -> validateInteger n
494+ (Just SwaggerNumber, Number n) -> validateNumber n
495+ (Just SwaggerString, String s) -> validateString s
496+ (Just SwaggerArray, Array xs) -> validateArray xs
497+ (Nothing, Bool _) -> valid
498+ -- Number by default
499+ (Nothing, Number n) -> validateNumber n
500+ (Nothing, String s) -> validateString s
501+ (Nothing, Array xs) -> validateArray xs
502+ bad -> invalid $ "expected JSON value of type " ++ showType bad
503+
504+showType :: (Maybe (SwaggerType t), Value) -> String
505+showType (Just type_, _) = show type_
506+showType (Nothing, Null) = "SwaggerNull"
507+showType (Nothing, Bool _) = "SwaggerBoolean"
508+showType (Nothing, Number _) = "SwaggerNumber"
509+showType (Nothing, String _) = "SwaggerString"
510+showType (Nothing, Array _) = "SwaggerArray"
511+showType (Nothing, Object _) = "SwaggerObject"
src/Data/Swagger/Internal/TypeShape.hsnew file+66
@@ -0,0 +1,66 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE ConstraintKinds #-}
3+{-# LANGUAGE DataKinds #-}
4+{-# LANGUAGE KindSignatures #-}
5+{-# LANGUAGE TypeFamilies #-}
6+{-# LANGUAGE TypeOperators #-}
7+{-# LANGUAGE UndecidableInstances #-}
8+
9+module Data.Swagger.Internal.TypeShape where
10+
11+import Data.Proxy
12+import GHC.Generics
13+import GHC.TypeLits
14+import GHC.Exts (Constraint)
15+
16+-- | Shape of a datatype.
17+data TypeShape
18+ = Enumeration -- ^ A simple enumeration.
19+ | SumOfProducts -- ^ A product or a sum of non-unit products.
20+ | Mixed -- ^ Mixed sum type with both unit and non-unit constructors.
21+
22+-- | A combined shape for a product type.
23+type family ProdCombine (a :: TypeShape) (b :: TypeShape) :: TypeShape where
24+ ProdCombine Mixed b = Mixed -- technically this cannot happen since Haskell types are sums of products
25+ ProdCombine a Mixed = Mixed -- technically this cannot happen since Haskell types are sums of products
26+ ProdCombine a b = SumOfProducts
27+
28+-- | A combined shape for a sum type.
29+type family SumCombine (a :: TypeShape) (b :: TypeShape) :: TypeShape where
30+ SumCombine Enumeration Enumeration = Enumeration
31+ SumCombine SumOfProducts SumOfProducts = SumOfProducts
32+ SumCombine a b = Mixed
33+
34+type family TypeHasSimpleShape t (f :: Symbol) :: Constraint where
35+ TypeHasSimpleShape t f = GenericHasSimpleShape t f (GenericShape (Rep t))
36+
37+type family GenericHasSimpleShape t (f :: Symbol) (s :: TypeShape) :: Constraint where
38+ GenericHasSimpleShape t f Enumeration = ()
39+ GenericHasSimpleShape t f SumOfProducts = ()
40+#if __GLASGOW_HASKELL__ < 800
41+ GenericHasSimpleShape t f Mixed = CannotDeriveSchemaForMixedSumType t
42+
43+class CannotDeriveSchemaForMixedSumType t where
44+#else
45+ GenericHasSimpleShape t f Mixed =
46+ TypeError
47+ ( Text "Cannot derive Generic-based Swagger Schema for " :<>: ShowType t
48+ :$$: ShowType t :<>: Text " is a mixed sum type (has both unit and non-unit constructors)."
49+ :$$: Text "Swagger does not have a good representation for these types."
50+ :$$: Text "Use " :<>: Text f :<>: Text " if you want to derive schema"
51+ :$$: Text "that matches aeson's Generic-based toJSON,"
52+ :$$: Text "but that's not supported by some Swagger tools."
53+ )
54+#endif
55+
56+-- | Infer a 'TypeShape' for a generic representation of a type.
57+type family GenericShape (g :: * -> *) :: TypeShape
58+
59+type instance GenericShape (f :*: g) = ProdCombine (GenericShape f) (GenericShape g)
60+type instance GenericShape (f :+: g) = SumCombine (GenericShape f) (GenericShape g)
61+type instance GenericShape (D1 d f) = GenericShape f
62+type instance GenericShape (C1 c U1) = Enumeration
63+type instance GenericShape (C1 c (S1 s f)) = SumOfProducts
64+type instance GenericShape (C1 c (f :*: g)) = SumOfProducts
65+
66+
src/Data/Swagger/Internal/Utils.hs+9−46
@@ -9,8 +9,6 @@ module Data.Swagger.Internal.Utils where
9import Prelude ()
9import Prelude ()
10import Prelude.Compat
10import Prelude.Compat
11
11
12−import Control.Arrow (first)
13−import Control.Applicative
14import Control.Lens ((&), (%~))
12import Control.Lens ((&), (%~))
15import Control.Lens.TH
13import Control.Lens.TH
16import Data.Aeson
14import Data.Aeson
@@ -20,12 +18,13 @@ import Data.Data
20import Data.Hashable (Hashable)
18import Data.Hashable (Hashable)
21import Data.HashMap.Strict (HashMap)
19import Data.HashMap.Strict (HashMap)
22import qualified Data.HashMap.Strict as HashMap
20import qualified Data.HashMap.Strict as HashMap
21+import Data.HashMap.Strict.InsOrd (InsOrdHashMap)
22+import qualified Data.HashMap.Strict.InsOrd as InsOrdHashMap
23import Data.Map (Map)
23import Data.Map (Map)
24−import Data.Monoid
24+import Data.Set (Set)
25import Data.Text (Text)
25import Data.Text (Text)
26import GHC.Generics
26import GHC.Generics
27import Language.Haskell.TH (mkName)
27import Language.Haskell.TH (mkName)
28−import Text.Read (readMaybe)
29
28
30swaggerFieldRules :: LensRules
29swaggerFieldRules :: LensRules
31swaggerFieldRules = defaultFieldRules & lensField %~ swaggerFieldNamer
30swaggerFieldRules = defaultFieldRules & lensField %~ swaggerFieldNamer
@@ -44,6 +43,7 @@ swaggerFieldRules = defaultFieldRules & lensField %~ swaggerFieldNamer
44 fixName' "minimum" = "minimum_" -- Prelude conflict
43 fixName' "minimum" = "minimum_" -- Prelude conflict
45 fixName' "maximum" = "maximum_" -- Prelude conflict
44 fixName' "maximum" = "maximum_" -- Prelude conflict
46 fixName' "enum" = "enum_" -- Control.Lens conflict
45 fixName' "enum" = "enum_" -- Control.Lens conflict
46+ fixName' "head" = "head_" -- Prelude conflict
47 fixName' n = n
47 fixName' n = n
48
48
49gunfoldEnum :: String -> [a] -> (forall b r. Data b => c (b -> r) -> c r) -> (forall r. r -> c r) -> Constr -> c a
49gunfoldEnum :: String -> [a] -> (forall b r. Data b => c (b -> r) -> c r) -> (forall r. r -> c r) -> Constr -> c a
@@ -51,17 +51,6 @@ gunfoldEnum tname xs _k z c = case lookup (constrIndex c) (zip [1..] xs) of
51 Just x -> z x
51 Just x -> z x
52 Nothing -> error $ "Data.Data.gunfold: Constructor " ++ show c ++ " is not of type " ++ tname ++ "."
52 Nothing -> error $ "Data.Data.gunfold: Constructor " ++ show c ++ " is not of type " ++ tname ++ "."
53
53
54−hashMapMapKeys :: (Eq k', Hashable k') => (k -> k') -> HashMap k v -> HashMap k' v
55−hashMapMapKeys f = HashMap.fromList . map (first f) . HashMap.toList
56−
57−hashMapTraverseKeys :: (Eq k', Hashable k', Applicative f) => (k -> f k') -> HashMap k v -> f (HashMap k' v)
58−hashMapTraverseKeys f = fmap HashMap.fromList . traverse g . HashMap.toList
59− where
60− g (x, y) = (\a -> (a, y)) <$> f x
61−
62−hashMapReadKeys :: (Eq k, Read k, Hashable k, Alternative f) => HashMap String v -> f (HashMap k v)
63−hashMapReadKeys = hashMapTraverseKeys (maybe empty pure . readMaybe)
64−
65jsonPrefix :: String -> Options
54jsonPrefix :: String -> Options
66jsonPrefix prefix = defaultOptions
55jsonPrefix prefix = defaultOptions
67 { fieldLabelModifier = modifier . drop 1
56 { fieldLabelModifier = modifier . drop 1
@@ -83,40 +72,10 @@ parseOneOf xs js =
83 where
72 where
84 ys = zip (map toJSON xs) xs
73 ys = zip (map toJSON xs) xs
85
74
86−omitEmptiesExcept :: (Text -> Value -> Bool) -> Value -> Value
87−omitEmptiesExcept f (Object o) = Object (HashMap.filterWithKey nonEmpty o)
88− where
89− nonEmpty k js = f k js || (js /= Object mempty) && (js /= Array mempty) && (js /= Null)
90−omitEmptiesExcept _ js = js
91−
92−omitEmpties :: Value -> Value
93−omitEmpties = omitEmptiesExcept (\_ _ -> False)
94−
95−genericToJSONWithSub :: (Generic a, GToJSON (Rep a)) => Text -> Options -> a -> Value
96−genericToJSONWithSub sub opts x =
97− case genericToJSON opts x of
98− Object o ->
99− case HashMap.lookup sub o of
100− Just so -> Object (HashMap.delete sub o) <+> so
101− Nothing -> Object o -- no subjson, leaving object as is
102− _ -> error "genericToJSONWithSub: subjson is not an object"
103−
104−genericParseJSONWithSub :: (Generic a, GFromJSON (Rep a)) => Text -> Options -> Value -> Parser a
105−genericParseJSONWithSub sub opts js@(Object o)
106− = genericParseJSON opts js -- try without subjson
107− <|> genericParseJSON opts js' -- try with subjson
108− where
109− js' = Object (HashMap.insert sub (Object o) o)
110−genericParseJSONWithSub _ _ _ = error "genericParseJSONWithSub: given json is not an object"
111−
112(<+>) :: Value -> Value -> Value
75(<+>) :: Value -> Value -> Value
113Object x <+> Object y = Object (x <> y)
76Object x <+> Object y = Object (x <> y)
114_ <+> _ = error "<+>: merging non-objects"
77_ <+> _ = error "<+>: merging non-objects"
115
78
116−withDefaults :: (Value -> Parser a) -> [Pair] -> Value -> Parser a
117−withDefaults parser defs js@(Object _) = parser (js <+> object defs)
118−withDefaults _ _ _ = empty
119−
120genericMempty :: (Generic a, GMonoid (Rep a)) => a
79genericMempty :: (Generic a, GMonoid (Rep a)) => a
121genericMempty = to gmempty
80genericMempty = to gmempty
122
81
@@ -152,12 +111,17 @@ class SwaggerMonoid m where
152 swaggerMappend = mappend
111 swaggerMappend = mappend
153
112
154instance SwaggerMonoid [a]
113instance SwaggerMonoid [a]
114+instance Ord a => SwaggerMonoid (Set a)
155instance Ord k => SwaggerMonoid (Map k v)
115instance Ord k => SwaggerMonoid (Map k v)
156
116
157instance (Eq k, Hashable k) => SwaggerMonoid (HashMap k v) where
117instance (Eq k, Hashable k) => SwaggerMonoid (HashMap k v) where
158 swaggerMempty = mempty
118 swaggerMempty = mempty
159 swaggerMappend = HashMap.unionWith (\_old new -> new)
119 swaggerMappend = HashMap.unionWith (\_old new -> new)
160
120
121+instance (Eq k, Hashable k) => SwaggerMonoid (InsOrdHashMap k v) where
122+ swaggerMempty = mempty
123+ swaggerMappend = InsOrdHashMap.unionWith (\_old new -> new)
124+
161instance SwaggerMonoid Text where
125instance SwaggerMonoid Text where
162 swaggerMempty = mempty
126 swaggerMempty = mempty
163 swaggerMappend x "" = x
127 swaggerMappend x "" = x
@@ -167,4 +131,3 @@ instance SwaggerMonoid (Maybe a) where
167 swaggerMempty = Nothing
131 swaggerMempty = Nothing
168 swaggerMappend x Nothing = x
132 swaggerMappend x Nothing = x
169 swaggerMappend _ y = y
133 swaggerMappend _ y = y
170−
src/Data/Swagger/Lens.hs+30−9
@@ -7,9 +7,16 @@
7{-# LANGUAGE RankNTypes #-}
7{-# LANGUAGE RankNTypes #-}
8{-# LANGUAGE TemplateHaskell #-}
8{-# LANGUAGE TemplateHaskell #-}
9{-# LANGUAGE TypeFamilies #-}
9{-# LANGUAGE TypeFamilies #-}
10+{-# LANGUAGE DataKinds #-}
10{-# LANGUAGE UndecidableInstances #-}
11{-# LANGUAGE UndecidableInstances #-}
11{-# OPTIONS_GHC -fno-warn-orphans #-}
12{-# OPTIONS_GHC -fno-warn-orphans #-}
12#include "overlapping-compat.h"
13#include "overlapping-compat.h"
14+-- |
15+-- Module: Data.Swagger.Lens
16+-- Maintainer: Nickolay Kudasov <nickolay@getshoptv.com>
17+-- Stability: experimental
18+--
19+-- Lenses and prisms for Swagger.
13module Data.Swagger.Lens where
20module Data.Swagger.Lens where
14
21
15import Control.Lens
22import Control.Lens
@@ -26,7 +33,7 @@ makeFields ''Host
26makeFields ''Info
33makeFields ''Info
27makeFields ''Contact
34makeFields ''Contact
28makeFields ''License
35makeFields ''License
29−makeFields ''PathItem
36+makeLensesWith swaggerFieldRules ''PathItem
30makeFields ''Tag
37makeFields ''Tag
31makeFields ''Operation
38makeFields ''Operation
32makeFields ''Param
39makeFields ''Param
@@ -48,22 +55,28 @@ makeFields ''ExternalDocs
48makePrisms ''ParamAnySchema
55makePrisms ''ParamAnySchema
49-- ** 'SecuritySchemeType' prisms
56-- ** 'SecuritySchemeType' prisms
50makePrisms ''SecuritySchemeType
57makePrisms ''SecuritySchemeType
58+-- ** 'Referenced' prisms
59+makePrisms ''Referenced
51
60
52-- ** 'SwaggerItems' prisms
61-- ** 'SwaggerItems' prisms
53
62
54−_SwaggerItemsArray :: forall t. (t ~ Schema) => Review (SwaggerItems t) [Referenced Schema]
63+_SwaggerItemsArray :: Review (SwaggerItems 'SwaggerKindSchema) [Referenced Schema]
55_SwaggerItemsArray
64_SwaggerItemsArray
56− = prism (\x -> SwaggerItemsArray x) $ \x -> case x of
65+ = unto (\x -> SwaggerItemsArray x)
66+{- \x -> case x of
57 SwaggerItemsPrimitive c p -> Left (SwaggerItemsPrimitive c p)
67 SwaggerItemsPrimitive c p -> Left (SwaggerItemsPrimitive c p)
58 SwaggerItemsObject o -> Left (SwaggerItemsObject o)
68 SwaggerItemsObject o -> Left (SwaggerItemsObject o)
59 SwaggerItemsArray a -> Right a
69 SwaggerItemsArray a -> Right a
70+-}
60
71
61−_SwaggerItemsObject :: forall t. (t ~ Schema) => Review (SwaggerItems t) (Referenced Schema)
72+_SwaggerItemsObject :: Review (SwaggerItems 'SwaggerKindSchema) (Referenced Schema)
62_SwaggerItemsObject
73_SwaggerItemsObject
63− = prism (\x -> SwaggerItemsObject x) $ \x -> case x of
74+ = unto (\x -> SwaggerItemsObject x)
75+{- \x -> case x of
64 SwaggerItemsPrimitive c p -> Left (SwaggerItemsPrimitive c p)
76 SwaggerItemsPrimitive c p -> Left (SwaggerItemsPrimitive c p)
65 SwaggerItemsObject o -> Right o
77 SwaggerItemsObject o -> Right o
66 SwaggerItemsArray a -> Left (SwaggerItemsArray a)
78 SwaggerItemsArray a -> Left (SwaggerItemsArray a)
79+-}
67
80
68_SwaggerItemsPrimitive :: forall t p f. (Profunctor p, Bifunctor p, Functor f) => Optic' p f (SwaggerItems t) (Maybe (CollectionFormat t), ParamSchema t)
81_SwaggerItemsPrimitive :: forall t p f. (Profunctor p, Bifunctor p, Functor f) => Optic' p f (SwaggerItems t) (Maybe (CollectionFormat t), ParamSchema t)
69_SwaggerItemsPrimitive = unto (\(c, p) -> SwaggerItemsPrimitive c p)
82_SwaggerItemsPrimitive = unto (\(c, p) -> SwaggerItemsPrimitive c p)
@@ -83,11 +96,19 @@ instance At Responses where at n = responses . at n
83instance Ixed Operation where ix n = responses . ix n
96instance Ixed Operation where ix n = responses . ix n
84instance At Operation where at n = responses . at n
97instance At Operation where at n = responses . at n
85
98
99+type instance Index SecurityDefinitions = Text
100+type instance IxValue SecurityDefinitions = SecurityScheme
101+
102+instance Ixed SecurityDefinitions where ix n = (coerced :: Lens' SecurityDefinitions (Definitions SecurityScheme)). ix n
103+instance At SecurityDefinitions where at n = (coerced :: Lens' SecurityDefinitions (Definitions SecurityScheme)). at n
104+
105+instance HasParamSchema NamedSchema (ParamSchema 'SwaggerKindSchema) where paramSchema = schema.paramSchema
106+
86-- HasType instances
107-- HasType instances
87−instance HasType Header (SwaggerType Header) where type_ = paramSchema.type_
108+instance HasType Header (Maybe (SwaggerType ('SwaggerKindNormal Header))) where type_ = paramSchema.type_
88−instance HasType Schema (SwaggerType Schema) where type_ = paramSchema.type_
109+instance HasType Schema (Maybe (SwaggerType 'SwaggerKindSchema)) where type_ = paramSchema.type_
89−instance HasType NamedSchema (SwaggerType Schema) where type_ = schema.paramSchema.type_
110+instance HasType NamedSchema (Maybe (SwaggerType 'SwaggerKindSchema)) where type_ = paramSchema.type_
90−instance HasType ParamOtherSchema (SwaggerType ParamOtherSchema) where type_ = paramSchema.type_
111+instance HasType ParamOtherSchema (Maybe (SwaggerType 'SwaggerKindParamOtherSchema)) where type_ = paramSchema.type_
91
112
92-- HasDefault instances
113-- HasDefault instances
93instance HasDefault Header (Maybe Value) where default_ = paramSchema.default_
114instance HasDefault Header (Maybe Value) where default_ = paramSchema.default_
src/Data/Swagger/Operation.hsnew file+193
@@ -0,0 +1,193 @@
1+{-# LANGUAGE RankNTypes #-}
2+-- |
3+-- Module: Data.Swagger.Operation
4+-- Maintainer: Nickolay Kudasov <nickolay@getshoptv.com>
5+-- Stability: experimental
6+--
7+-- Helper traversals and functions for Swagger operations manipulations.
8+-- These might be useful when you already have Swagger specification
9+-- generated by something else.
10+module Data.Swagger.Operation (
11+ -- * Operation traversals
12+ allOperations,
13+ operationsOf,
14+
15+ -- * Manipulation
16+ -- ** Tags
17+ applyTags,
18+ applyTagsFor,
19+
20+ -- ** Responses
21+ setResponse,
22+ setResponseWith,
23+ setResponseFor,
24+ setResponseForWith,
25+
26+ -- ** Paths
27+ prependPath,
28+
29+ -- * Miscellaneous
30+ declareResponse,
31+) where
32+
33+import Prelude ()
34+import Prelude.Compat
35+
36+import Control.Lens
37+import Data.Data.Lens
38+import Data.List.Compat
39+import Data.Maybe (mapMaybe)
40+import Data.Proxy
41+import qualified Data.Set as Set
42+
43+import Data.Swagger.Declare
44+import Data.Swagger.Internal
45+import Data.Swagger.Lens
46+import Data.Swagger.Schema
47+
48+import qualified Data.HashMap.Strict.InsOrd as InsOrdHashMap
49+import qualified Data.HashSet.InsOrd as InsOrdHS
50+
51+-- $setup
52+-- >>> import Data.Aeson
53+-- >>> import Data.Proxy
54+-- >>> import Data.Time
55+
56+-- | Prepend path piece to all operations of the spec.
57+-- Leading and trailing slashes are trimmed/added automatically.
58+--
59+-- >>> let api = (mempty :: Swagger) & paths .~ [("/info", mempty)]
60+-- >>> encode $ prependPath "user/{user_id}" api ^. paths
61+-- "{\"/user/{user_id}/info\":{}}"
62+prependPath :: FilePath -> Swagger -> Swagger
63+prependPath path = paths %~ InsOrdHashMap.mapKeys (path </>)
64+ where
65+ x </> y = case trim y of
66+ "" -> "/" <> trim x
67+ y' -> "/" <> trim x <> "/" <> y'
68+
69+ trim = dropWhile (== '/') . dropWhileEnd (== '/')
70+
71+-- | All operations of a Swagger spec.
72+allOperations :: Traversal' Swagger Operation
73+allOperations = paths.traverse.template
74+
75+-- | @'operationsOf' sub@ will traverse only those operations
76+-- that are present in @sub@. Note that @'Operation'@ is determined
77+-- by both path and method.
78+--
79+-- >>> let ok = (mempty :: Operation) & at 200 ?~ "OK"
80+-- >>> let api = (mempty :: Swagger) & paths .~ [("/user", mempty & get ?~ ok & post ?~ ok)]
81+-- >>> let sub = (mempty :: Swagger) & paths .~ [("/user", mempty & get ?~ mempty)]
82+-- >>> encode api
83+-- "{\"swagger\":\"2.0\",\"info\":{\"version\":\"\",\"title\":\"\"},\"paths\":{\"/user\":{\"get\":{\"responses\":{\"200\":{\"description\":\"OK\"}}},\"post\":{\"responses\":{\"200\":{\"description\":\"OK\"}}}}}}"
84+-- >>> encode $ api & operationsOf sub . at 404 ?~ "Not found"
85+-- "{\"swagger\":\"2.0\",\"info\":{\"version\":\"\",\"title\":\"\"},\"paths\":{\"/user\":{\"get\":{\"responses\":{\"404\":{\"description\":\"Not found\"},\"200\":{\"description\":\"OK\"}}},\"post\":{\"responses\":{\"200\":{\"description\":\"OK\"}}}}}}"
86+operationsOf :: Swagger -> Traversal' Swagger Operation
87+operationsOf sub = paths.itraversed.withIndex.subops
88+ where
89+ -- | Traverse operations that correspond to paths and methods of the sub API.
90+ subops :: Traversal' (FilePath, PathItem) Operation
91+ subops f (path, item) = case InsOrdHashMap.lookup path (sub ^. paths) of
92+ Just subitem -> (,) path <$> methodsOf subitem f item
93+ Nothing -> pure (path, item)
94+
95+ -- | Traverse operations that exist in a given @'PathItem'@
96+ -- This is used to traverse only the operations that exist in sub API.
97+ methodsOf :: PathItem -> Traversal' PathItem Operation
98+ methodsOf pathItem = partsOf template . itraversed . indices (`elem` ns) . _Just
99+ where
100+ ops = pathItem ^.. template :: [Maybe Operation]
101+ ns = mapMaybe (fmap fst . sequenceA) $ zip [0..] ops
102+
103+-- | Apply tags to all operations and update the global list of tags.
104+--
105+-- @
106+-- 'applyTags' = 'applyTagsFor' 'allOperations'
107+-- @
108+applyTags :: [Tag] -> Swagger -> Swagger
109+applyTags = applyTagsFor allOperations
110+
111+-- | Apply tags to a part of Swagger spec and update the global
112+-- list of tags.
113+applyTagsFor :: Traversal' Swagger Operation -> [Tag] -> Swagger -> Swagger
114+applyTagsFor ops ts swag = swag
115+ & ops . tags %~ (<> InsOrdHS.fromList (map _tagName ts))
116+ & tags %~ (<> InsOrdHS.fromList ts)
117+
118+-- | Construct a response with @'Schema'@ while declaring all
119+-- necessary schema definitions.
120+--
121+-- >>> encode $ runDeclare (declareResponse (Proxy :: Proxy Day)) mempty
122+-- "[{\"Day\":{\"example\":\"2016-07-22\",\"format\":\"date\",\"type\":\"string\"}},{\"description\":\"\",\"schema\":{\"$ref\":\"#/definitions/Day\"}}]"
123+declareResponse :: ToSchema a => Proxy a -> Declare (Definitions Schema) Response
124+declareResponse proxy = do
125+ s <- declareSchemaRef proxy
126+ return (mempty & schema ?~ s)
127+
128+-- | Set response for all operations.
129+-- This will also update global schema definitions.
130+--
131+-- If the response already exists it will be overwritten.
132+--
133+-- @
134+-- 'setResponse' = 'setResponseFor' 'allOperations'
135+-- @
136+--
137+-- Example:
138+--
139+-- >>> let api = (mempty :: Swagger) & paths .~ [("/user", mempty & get ?~ mempty)]
140+-- >>> let res = declareResponse (Proxy :: Proxy Day)
141+-- >>> encode $ api & setResponse 200 res
142+-- "{\"swagger\":\"2.0\",\"info\":{\"version\":\"\",\"title\":\"\"},\"paths\":{\"/user\":{\"get\":{\"responses\":{\"200\":{\"schema\":{\"$ref\":\"#/definitions/Day\"},\"description\":\"\"}}}}},\"definitions\":{\"Day\":{\"example\":\"2016-07-22\",\"format\":\"date\",\"type\":\"string\"}}}"
143+--
144+-- See also @'setResponseWith'@.
145+setResponse :: HttpStatusCode -> Declare (Definitions Schema) Response -> Swagger -> Swagger
146+setResponse = setResponseFor allOperations
147+
148+-- | Set or update response for all operations.
149+-- This will also update global schema definitions.
150+--
151+-- If the response already exists, but it can't be dereferenced (invalid @\$ref@),
152+-- then just the new response is used.
153+--
154+-- @
155+-- 'setResponseWith' = 'setResponseForWith' 'allOperations'
156+-- @
157+--
158+-- See also @'setResponse'@.
159+setResponseWith :: (Response -> Response -> Response) -> HttpStatusCode -> Declare (Definitions Schema) Response -> Swagger -> Swagger
160+setResponseWith = setResponseForWith allOperations
161+
162+-- | Set response for specified operations.
163+-- This will also update global schema definitions.
164+--
165+-- If the response already exists it will be overwritten.
166+--
167+-- See also @'setResponseForWith'@.
168+setResponseFor :: Traversal' Swagger Operation -> HttpStatusCode -> Declare (Definitions Schema) Response -> Swagger -> Swagger
169+setResponseFor ops code dres swag = swag
170+ & definitions %~ (<> defs)
171+ & ops . at code ?~ Inline res
172+ where
173+ (defs, res) = runDeclare dres mempty
174+
175+-- | Set or update response for specified operations.
176+-- This will also update global schema definitions.
177+--
178+-- If the response already exists, but it can't be dereferenced (invalid @\$ref@),
179+-- then just the new response is used.
180+--
181+-- See also @'setResponseFor'@.
182+setResponseForWith :: Traversal' Swagger Operation -> (Response -> Response -> Response) -> HttpStatusCode -> Declare (Definitions Schema) Response -> Swagger -> Swagger
183+setResponseForWith ops f code dres swag = swag
184+ & definitions %~ (<> defs)
185+ & ops . at code %~ Just . Inline . combine
186+ where
187+ (defs, new) = runDeclare dres mempty
188+
189+ combine (Just (Ref (Reference n))) = case swag ^. responses.at n of
190+ Just old -> f old new
191+ Nothing -> new -- response name can't be dereferenced, replacing with new response
192+ combine (Just (Inline old)) = f old new
193+ combine Nothing = new
src/Data/Swagger/Optics.hsnew file+597
@@ -0,0 +1,597 @@
1+{-# LANGUAGE DataKinds #-}
2+{-# LANGUAGE FlexibleInstances #-}
3+{-# LANGUAGE MultiParamTypeClasses #-}
4+{-# LANGUAGE OverloadedLabels #-}
5+{-# LANGUAGE TemplateHaskell #-}
6+{-# LANGUAGE TypeFamilies #-}
7+{-# LANGUAGE UndecidableInstances #-}
8+{-# OPTIONS_GHC -fno-warn-orphans #-}
9+-- |
10+-- Module: Data.Swagger.Optics
11+-- Maintainer: Andrzej Rybczak <andrzej@rybczak.net>
12+-- Stability: experimental
13+--
14+-- Lenses and prisms for the <https://hackage.haskell.org/package/optics optics>
15+-- library.
16+--
17+-- >>> import Data.Aeson
18+-- >>> import Optics.Core
19+-- >>> :set -XOverloadedLabels
20+--
21+-- Example from the "Data.Swagger" module using @optics@:
22+--
23+-- >>> :{
24+-- encode $ (mempty :: Swagger)
25+-- & #definitions .~ [ ("User", mempty & #type ?~ SwaggerString) ]
26+-- & #paths .~
27+-- [ ("/user", mempty & #get ?~ (mempty
28+-- & #produces ?~ MimeList ["application/json"]
29+-- & at 200 ?~ ("OK" & #_Inline % #schema ?~ Ref (Reference "User"))
30+-- & at 404 ?~ "User info not found")) ]
31+-- :}
32+-- "{\"swagger\":\"2.0\",\"info\":{\"version\":\"\",\"title\":\"\"},\"paths\":{\"/user\":{\"get\":{\"produces\":[\"application/json\"],\"responses\":{\"404\":{\"description\":\"User info not found\"},\"200\":{\"schema\":{\"$ref\":\"#/definitions/User\"},\"description\":\"OK\"}}}}},\"definitions\":{\"User\":{\"type\":\"string\"}}}"
33+--
34+-- For convenience optics are defined as /labels/. It means that field accessor
35+-- names can be overloaded for different types. One such common field is
36+-- @#description@. Many components of a Swagger specification can have
37+-- descriptions, and you can use the same name for them:
38+--
39+-- >>> encode $ (mempty :: Response) & #description .~ "No content"
40+-- "{\"description\":\"No content\"}"
41+-- >>> :{
42+-- encode $ (mempty :: Schema)
43+-- & #type ?~ SwaggerBoolean
44+-- & #description ?~ "To be or not to be"
45+-- :}
46+-- "{\"description\":\"To be or not to be\",\"type\":\"boolean\"}"
47+--
48+-- @'ParamSchema'@ is basically the /base schema specification/ and many types
49+-- contain it. So for convenience, all @'ParamSchema'@ fields are transitively
50+-- made fields of the type that has it. For example, you can use @#type@ to
51+-- access @'SwaggerType'@ of @'Header'@ schema without having to use
52+-- @#paramSchema@:
53+--
54+-- >>> encode $ (mempty :: Header) & #type ?~ SwaggerNumber
55+-- "{\"type\":\"number\"}"
56+--
57+-- Additionally, to simplify working with @'Response'@, both @'Operation'@ and
58+-- @'Responses'@ have direct access to it via @'Optics.Core.At.at'@. Example:
59+--
60+-- >>> :{
61+-- encode $ (mempty :: Operation)
62+-- & at 404 ?~ "Not found"
63+-- :}
64+-- "{\"responses\":{\"404\":{\"description\":\"Not found\"}}}"
65+--
66+module Data.Swagger.Optics () where
67+
68+import Data.Aeson (Value)
69+import Data.Scientific (Scientific)
70+import Data.Swagger.Internal
71+import Data.Text (Text)
72+import Optics.Core
73+import Optics.TH
74+
75+-- Lenses
76+
77+makeFieldLabels ''Swagger
78+makeFieldLabels ''Host
79+makeFieldLabels ''Info
80+makeFieldLabels ''Contact
81+makeFieldLabels ''License
82+makeFieldLabels ''PathItem
83+makeFieldLabels ''Tag
84+makeFieldLabels ''Operation
85+makeFieldLabels ''Param
86+makeFieldLabels ''ParamOtherSchema
87+makeFieldLabels ''Header
88+makeFieldLabels ''Schema
89+makeFieldLabels ''NamedSchema
90+makeFieldLabels ''ParamSchema
91+makeFieldLabels ''Xml
92+makeFieldLabels ''Responses
93+makeFieldLabels ''Response
94+makeFieldLabels ''SecurityScheme
95+makeFieldLabels ''ApiKeyParams
96+makeFieldLabels ''OAuth2Params
97+makeFieldLabels ''ExternalDocs
98+
99+-- Prisms
100+
101+makePrismLabels ''ParamAnySchema
102+makePrismLabels ''SecuritySchemeType
103+makePrismLabels ''Referenced
104+
105+-- SwaggerItems prisms
106+
107+instance
108+ ( a ~ [Referenced Schema]
109+ , b ~ [Referenced Schema]
110+ ) => LabelOptic "_SwaggerItemsArray"
111+ A_Review
112+ (SwaggerItems 'SwaggerKindSchema)
113+ (SwaggerItems 'SwaggerKindSchema)
114+ a
115+ b where
116+ labelOptic = unto (\x -> SwaggerItemsArray x)
117+ {-# INLINE labelOptic #-}
118+
119+instance
120+ ( a ~ Referenced Schema
121+ , b ~ Referenced Schema
122+ ) => LabelOptic "_SwaggerItemsObject"
123+ A_Review
124+ (SwaggerItems 'SwaggerKindSchema)
125+ (SwaggerItems 'SwaggerKindSchema)
126+ a
127+ b where
128+ labelOptic = unto (\x -> SwaggerItemsObject x)
129+ {-# INLINE labelOptic #-}
130+
131+instance
132+ ( a ~ (Maybe (CollectionFormat t), ParamSchema t)
133+ , b ~ (Maybe (CollectionFormat t), ParamSchema t)
134+ ) => LabelOptic "_SwaggerItemsPrimitive"
135+ A_Review
136+ (SwaggerItems t)
137+ (SwaggerItems t)
138+ a
139+ b where
140+ labelOptic = unto (\(c, p) -> SwaggerItemsPrimitive c p)
141+ {-# INLINE labelOptic #-}
142+
143+-- =============================================================
144+-- More helpful instances for easier access to schema properties
145+
146+type instance Index Responses = HttpStatusCode
147+type instance Index Operation = HttpStatusCode
148+
149+type instance IxValue Responses = Referenced Response
150+type instance IxValue Operation = Referenced Response
151+
152+instance Ixed Responses where
153+ ix n = #responses % ix n
154+ {-# INLINE ix #-}
155+instance At Responses where
156+ at n = #responses % at n
157+ {-# INLINE at #-}
158+
159+instance Ixed Operation where
160+ ix n = #responses % ix n
161+ {-# INLINE ix #-}
162+instance At Operation where
163+ at n = #responses % at n
164+ {-# INLINE at #-}
165+
166+-- #paramSchema
167+
168+instance
169+ ( a ~ ParamSchema 'SwaggerKindSchema
170+ , b ~ ParamSchema 'SwaggerKindSchema
171+ ) => LabelOptic "paramSchema" A_Lens NamedSchema NamedSchema a b where
172+ labelOptic = #schema % #paramSchema
173+ {-# INLINE labelOptic #-}
174+
175+-- #type
176+
177+instance
178+ ( a ~ Maybe (SwaggerType ('SwaggerKindNormal Header))
179+ , b ~ Maybe (SwaggerType ('SwaggerKindNormal Header))
180+ ) => LabelOptic "type" A_Lens Header Header a b where
181+ labelOptic = #paramSchema % #type
182+ {-# INLINE labelOptic #-}
183+
184+instance
185+ ( a ~ Maybe (SwaggerType 'SwaggerKindSchema)
186+ , b ~ Maybe (SwaggerType 'SwaggerKindSchema)
187+ ) => LabelOptic "type" A_Lens Schema Schema a b where
188+ labelOptic = #paramSchema % #type
189+ {-# INLINE labelOptic #-}
190+
191+instance
192+ ( a ~ Maybe (SwaggerType 'SwaggerKindSchema)
193+ , b ~ Maybe (SwaggerType 'SwaggerKindSchema)
194+ ) => LabelOptic "type" A_Lens NamedSchema NamedSchema a b where
195+ labelOptic = #paramSchema % #type
196+ {-# INLINE labelOptic #-}
197+
198+instance
199+ ( a ~ Maybe (SwaggerType 'SwaggerKindParamOtherSchema)
200+ , b ~ Maybe (SwaggerType 'SwaggerKindParamOtherSchema)
201+ ) => LabelOptic "type" A_Lens ParamOtherSchema ParamOtherSchema a b where
202+ labelOptic = #paramSchema % #type
203+ {-# INLINE labelOptic #-}
204+
205+-- #default
206+
207+instance
208+ ( a ~ Maybe Value, b ~ Maybe Value
209+ ) => LabelOptic "default" A_Lens Header Header a b where
210+ labelOptic = #paramSchema % #default
211+ {-# INLINE labelOptic #-}
212+
213+instance
214+ ( a ~ Maybe Value, b ~ Maybe Value
215+ ) => LabelOptic "default" A_Lens Schema Schema a b where
216+ labelOptic = #paramSchema % #default
217+ {-# INLINE labelOptic #-}
218+
219+instance
220+ ( a ~ Maybe Value, b ~ Maybe Value
221+ ) => LabelOptic "default" A_Lens NamedSchema NamedSchema a b where
222+ labelOptic = #paramSchema % #default
223+ {-# INLINE labelOptic #-}
224+
225+instance
226+ ( a ~ Maybe Value, b ~ Maybe Value
227+ ) => LabelOptic "default" A_Lens ParamOtherSchema ParamOtherSchema a b where
228+ labelOptic = #paramSchema % #default
229+ {-# INLINE labelOptic #-}
230+
231+-- #format
232+
233+instance
234+ ( a ~ Maybe Format, b ~ Maybe Format
235+ ) => LabelOptic "format" A_Lens Header Header a b where
236+ labelOptic = #paramSchema % #format
237+ {-# INLINE labelOptic #-}
238+
239+instance
240+ ( a ~ Maybe Format, b ~ Maybe Format
241+ ) => LabelOptic "format" A_Lens Schema Schema a b where
242+ labelOptic = #paramSchema % #format
243+ {-# INLINE labelOptic #-}
244+
245+instance
246+ ( a ~ Maybe Format, b ~ Maybe Format
247+ ) => LabelOptic "format" A_Lens NamedSchema NamedSchema a b where
248+ labelOptic = #paramSchema % #format
249+ {-# INLINE labelOptic #-}
250+
251+instance
252+ ( a ~ Maybe Format, b ~ Maybe Format
253+ ) => LabelOptic "format" A_Lens ParamOtherSchema ParamOtherSchema a b where
254+ labelOptic = #paramSchema % #format
255+ {-# INLINE labelOptic #-}
256+
257+-- #items
258+
259+instance
260+ ( a ~ Maybe (SwaggerItems ('SwaggerKindNormal Header))
261+ , b ~ Maybe (SwaggerItems ('SwaggerKindNormal Header))
262+ ) => LabelOptic "items" A_Lens Header Header a b where
263+ labelOptic = #paramSchema % #items
264+ {-# INLINE labelOptic #-}
265+
266+instance
267+ ( a ~ Maybe (SwaggerItems 'SwaggerKindSchema)
268+ , b ~ Maybe (SwaggerItems 'SwaggerKindSchema)
269+ ) => LabelOptic "items" A_Lens Schema Schema a b where
270+ labelOptic = #paramSchema % #items
271+ {-# INLINE labelOptic #-}
272+
273+instance
274+ ( a ~ Maybe (SwaggerItems 'SwaggerKindSchema)
275+ , b ~ Maybe (SwaggerItems 'SwaggerKindSchema)
276+ ) => LabelOptic "items" A_Lens NamedSchema NamedSchema a b where
277+ labelOptic = #paramSchema % #items
278+ {-# INLINE labelOptic #-}
279+
280+instance
281+ ( a ~ Maybe (SwaggerItems 'SwaggerKindParamOtherSchema)
282+ , b ~ Maybe (SwaggerItems 'SwaggerKindParamOtherSchema)
283+ ) => LabelOptic "items" A_Lens ParamOtherSchema ParamOtherSchema a b where
284+ labelOptic = #paramSchema % #items
285+ {-# INLINE labelOptic #-}
286+
287+-- #maximum
288+
289+instance
290+ ( a ~ Maybe Scientific, b ~ Maybe Scientific
291+ ) => LabelOptic "maximum" A_Lens Header Header a b where
292+ labelOptic = #paramSchema % #maximum
293+ {-# INLINE labelOptic #-}
294+
295+instance
296+ ( a ~ Maybe Scientific, b ~ Maybe Scientific
297+ ) => LabelOptic "maximum" A_Lens Schema Schema a b where
298+ labelOptic = #paramSchema % #maximum
299+ {-# INLINE labelOptic #-}
300+
301+instance
302+ ( a ~ Maybe Scientific, b ~ Maybe Scientific
303+ ) => LabelOptic "maximum" A_Lens NamedSchema NamedSchema a b where
304+ labelOptic = #paramSchema % #maximum
305+ {-# INLINE labelOptic #-}
306+
307+instance
308+ ( a ~ Maybe Scientific, b ~ Maybe Scientific
309+ ) => LabelOptic "maximum" A_Lens ParamOtherSchema ParamOtherSchema a b where
310+ labelOptic = #paramSchema % #maximum
311+ {-# INLINE labelOptic #-}
312+
313+-- #exclusiveMaximum
314+
315+instance
316+ ( a ~ Maybe Bool, b ~ Maybe Bool
317+ ) => LabelOptic "exclusiveMaximum" A_Lens Header Header a b where
318+ labelOptic = #paramSchema % #exclusiveMaximum
319+ {-# INLINE labelOptic #-}
320+
321+instance
322+ ( a ~ Maybe Bool, b ~ Maybe Bool
323+ ) => LabelOptic "exclusiveMaximum" A_Lens Schema Schema a b where
324+ labelOptic = #paramSchema % #exclusiveMaximum
325+ {-# INLINE labelOptic #-}
326+
327+instance
328+ ( a ~ Maybe Bool, b ~ Maybe Bool
329+ ) => LabelOptic "exclusiveMaximum" A_Lens NamedSchema NamedSchema a b where
330+ labelOptic = #paramSchema % #exclusiveMaximum
331+ {-# INLINE labelOptic #-}
332+
333+instance
334+ ( a ~ Maybe Bool, b ~ Maybe Bool
335+ ) => LabelOptic "exclusiveMaximum" A_Lens ParamOtherSchema ParamOtherSchema a b where
336+ labelOptic = #paramSchema % #exclusiveMaximum
337+ {-# INLINE labelOptic #-}
338+
339+-- #minimum
340+
341+instance
342+ ( a ~ Maybe Scientific, b ~ Maybe Scientific
343+ ) => LabelOptic "minimum" A_Lens Header Header a b where
344+ labelOptic = #paramSchema % #minimum
345+ {-# INLINE labelOptic #-}
346+
347+instance
348+ ( a ~ Maybe Scientific, b ~ Maybe Scientific
349+ ) => LabelOptic "minimum" A_Lens Schema Schema a b where
350+ labelOptic = #paramSchema % #minimum
351+ {-# INLINE labelOptic #-}
352+
353+instance
354+ ( a ~ Maybe Scientific, b ~ Maybe Scientific
355+ ) => LabelOptic "minimum" A_Lens NamedSchema NamedSchema a b where
356+ labelOptic = #paramSchema % #minimum
357+ {-# INLINE labelOptic #-}
358+
359+instance
360+ ( a ~ Maybe Scientific, b ~ Maybe Scientific
361+ ) => LabelOptic "minimum" A_Lens ParamOtherSchema ParamOtherSchema a b where
362+ labelOptic = #paramSchema % #minimum
363+ {-# INLINE labelOptic #-}
364+
365+-- #exclusiveMinimum
366+
367+instance
368+ ( a ~ Maybe Bool, b ~ Maybe Bool
369+ ) => LabelOptic "exclusiveMinimum" A_Lens Header Header a b where
370+ labelOptic = #paramSchema % #exclusiveMinimum
371+ {-# INLINE labelOptic #-}
372+
373+instance
374+ ( a ~ Maybe Bool, b ~ Maybe Bool
375+ ) => LabelOptic "exclusiveMinimum" A_Lens Schema Schema a b where
376+ labelOptic = #paramSchema % #exclusiveMinimum
377+ {-# INLINE labelOptic #-}
378+
379+instance
380+ ( a ~ Maybe Bool, b ~ Maybe Bool
381+ ) => LabelOptic "exclusiveMinimum" A_Lens NamedSchema NamedSchema a b where
382+ labelOptic = #paramSchema % #exclusiveMinimum
383+ {-# INLINE labelOptic #-}
384+
385+instance
386+ ( a ~ Maybe Bool, b ~ Maybe Bool
387+ ) => LabelOptic "exclusiveMinimum" A_Lens ParamOtherSchema ParamOtherSchema a b where
388+ labelOptic = #paramSchema % #exclusiveMinimum
389+ {-# INLINE labelOptic #-}
390+
391+-- #maxLength
392+
393+instance
394+ ( a ~ Maybe Integer, b ~ Maybe Integer
395+ ) => LabelOptic "maxLength" A_Lens Header Header a b where
396+ labelOptic = #paramSchema % #maxLength
397+ {-# INLINE labelOptic #-}
398+
399+instance
400+ ( a ~ Maybe Integer, b ~ Maybe Integer
401+ ) => LabelOptic "maxLength" A_Lens Schema Schema a b where
402+ labelOptic = #paramSchema % #maxLength
403+ {-# INLINE labelOptic #-}
404+
405+instance
406+ ( a ~ Maybe Integer, b ~ Maybe Integer
407+ ) => LabelOptic "maxLength" A_Lens NamedSchema NamedSchema a b where
408+ labelOptic = #paramSchema % #maxLength
409+ {-# INLINE labelOptic #-}
410+
411+instance
412+ ( a ~ Maybe Integer, b ~ Maybe Integer
413+ ) => LabelOptic "maxLength" A_Lens ParamOtherSchema ParamOtherSchema a b where
414+ labelOptic = #paramSchema % #maxLength
415+ {-# INLINE labelOptic #-}
416+
417+-- #minLength
418+
419+instance
420+ ( a ~ Maybe Integer, b ~ Maybe Integer
421+ ) => LabelOptic "minLength" A_Lens Header Header a b where
422+ labelOptic = #paramSchema % #minLength
423+ {-# INLINE labelOptic #-}
424+
425+instance
426+ ( a ~ Maybe Integer, b ~ Maybe Integer
427+ ) => LabelOptic "minLength" A_Lens Schema Schema a b where
428+ labelOptic = #paramSchema % #minLength
429+ {-# INLINE labelOptic #-}
430+
431+instance
432+ ( a ~ Maybe Integer, b ~ Maybe Integer
433+ ) => LabelOptic "minLength" A_Lens NamedSchema NamedSchema a b where
434+ labelOptic = #paramSchema % #minLength
435+ {-# INLINE labelOptic #-}
436+
437+instance
438+ ( a ~ Maybe Integer, b ~ Maybe Integer
439+ ) => LabelOptic "minLength" A_Lens ParamOtherSchema ParamOtherSchema a b where
440+ labelOptic = #paramSchema % #minLength
441+ {-# INLINE labelOptic #-}
442+
443+-- #pattern
444+
445+instance
446+ ( a ~ Maybe Text, b ~ Maybe Text
447+ ) => LabelOptic "pattern" A_Lens Header Header a b where
448+ labelOptic = #paramSchema % #pattern
449+ {-# INLINE labelOptic #-}
450+
451+instance
452+ ( a ~ Maybe Text, b ~ Maybe Text
453+ ) => LabelOptic "pattern" A_Lens Schema Schema a b where
454+ labelOptic = #paramSchema % #pattern
455+ {-# INLINE labelOptic #-}
456+
457+instance
458+ ( a ~ Maybe Text, b ~ Maybe Text
459+ ) => LabelOptic "pattern" A_Lens NamedSchema NamedSchema a b where
460+ labelOptic = #paramSchema % #pattern
461+ {-# INLINE labelOptic #-}
462+
463+instance
464+ ( a ~ Maybe Text, b ~ Maybe Text
465+ ) => LabelOptic "pattern" A_Lens ParamOtherSchema ParamOtherSchema a b where
466+ labelOptic = #paramSchema % #pattern
467+ {-# INLINE labelOptic #-}
468+
469+-- #maxItems
470+
471+instance
472+ ( a ~ Maybe Integer, b ~ Maybe Integer
473+ ) => LabelOptic "maxItems" A_Lens Header Header a b where
474+ labelOptic = #paramSchema % #maxItems
475+ {-# INLINE labelOptic #-}
476+
477+instance
478+ ( a ~ Maybe Integer, b ~ Maybe Integer
479+ ) => LabelOptic "maxItems" A_Lens Schema Schema a b where
480+ labelOptic = #paramSchema % #maxItems
481+ {-# INLINE labelOptic #-}
482+
483+instance
484+ ( a ~ Maybe Integer, b ~ Maybe Integer
485+ ) => LabelOptic "maxItems" A_Lens NamedSchema NamedSchema a b where
486+ labelOptic = #paramSchema % #maxItems
487+ {-# INLINE labelOptic #-}
488+
489+instance
490+ ( a ~ Maybe Integer, b ~ Maybe Integer
491+ ) => LabelOptic "maxItems" A_Lens ParamOtherSchema ParamOtherSchema a b where
492+ labelOptic = #paramSchema % #maxItems
493+ {-# INLINE labelOptic #-}
494+
495+-- #minItems
496+
497+instance
498+ ( a ~ Maybe Integer, b ~ Maybe Integer
499+ ) => LabelOptic "minItems" A_Lens Header Header a b where
500+ labelOptic = #paramSchema % #minItems
501+ {-# INLINE labelOptic #-}
502+
503+instance
504+ ( a ~ Maybe Integer, b ~ Maybe Integer
505+ ) => LabelOptic "minItems" A_Lens Schema Schema a b where
506+ labelOptic = #paramSchema % #minItems
507+ {-# INLINE labelOptic #-}
508+
509+instance
510+ ( a ~ Maybe Integer, b ~ Maybe Integer
511+ ) => LabelOptic "minItems" A_Lens NamedSchema NamedSchema a b where
512+ labelOptic = #paramSchema % #minItems
513+ {-# INLINE labelOptic #-}
514+
515+instance
516+ ( a ~ Maybe Integer, b ~ Maybe Integer
517+ ) => LabelOptic "minItems" A_Lens ParamOtherSchema ParamOtherSchema a b where
518+ labelOptic = #paramSchema % #minItems
519+ {-# INLINE labelOptic #-}
520+
521+-- #uniqueItems
522+
523+instance
524+ ( a ~ Maybe Bool, b ~ Maybe Bool
525+ ) => LabelOptic "uniqueItems" A_Lens Header Header a b where
526+ labelOptic = #paramSchema % #uniqueItems
527+ {-# INLINE labelOptic #-}
528+
529+instance
530+ ( a ~ Maybe Bool, b ~ Maybe Bool
531+ ) => LabelOptic "uniqueItems" A_Lens Schema Schema a b where
532+ labelOptic = #paramSchema % #uniqueItems
533+ {-# INLINE labelOptic #-}
534+
535+instance
536+ ( a ~ Maybe Bool, b ~ Maybe Bool
537+ ) => LabelOptic "uniqueItems" A_Lens NamedSchema NamedSchema a b where
538+ labelOptic = #paramSchema % #uniqueItems
539+ {-# INLINE labelOptic #-}
540+
541+instance
542+ ( a ~ Maybe Bool, b ~ Maybe Bool
543+ ) => LabelOptic "uniqueItems" A_Lens ParamOtherSchema ParamOtherSchema a b where
544+ labelOptic = #paramSchema % #uniqueItems
545+ {-# INLINE labelOptic #-}
546+
547+-- #enum
548+
549+instance
550+ ( a ~ Maybe [Value], b ~ Maybe [Value]
551+ ) => LabelOptic "enum" A_Lens Header Header a b where
552+ labelOptic = #paramSchema % #enum
553+ {-# INLINE labelOptic #-}
554+
555+instance
556+ ( a ~ Maybe [Value], b ~ Maybe [Value]
557+ ) => LabelOptic "enum" A_Lens Schema Schema a b where
558+ labelOptic = #paramSchema % #enum
559+ {-# INLINE labelOptic #-}
560+
561+instance
562+ ( a ~ Maybe [Value], b ~ Maybe [Value]
563+ ) => LabelOptic "enum" A_Lens NamedSchema NamedSchema a b where
564+ labelOptic = #paramSchema % #enum
565+ {-# INLINE labelOptic #-}
566+
567+instance
568+ ( a ~ Maybe [Value], b ~ Maybe [Value]
569+ ) => LabelOptic "enum" A_Lens ParamOtherSchema ParamOtherSchema a b where
570+ labelOptic = #paramSchema % #enum
571+ {-# INLINE labelOptic #-}
572+
573+-- #multipleOf
574+
575+instance
576+ ( a ~ Maybe Scientific, b ~ Maybe Scientific
577+ ) => LabelOptic "multipleOf" A_Lens Header Header a b where
578+ labelOptic = #paramSchema % #multipleOf
579+ {-# INLINE labelOptic #-}
580+
581+instance
582+ ( a ~ Maybe Scientific, b ~ Maybe Scientific
583+ ) => LabelOptic "multipleOf" A_Lens Schema Schema a b where
584+ labelOptic = #paramSchema % #multipleOf
585+ {-# INLINE labelOptic #-}
586+
587+instance
588+ ( a ~ Maybe Scientific, b ~ Maybe Scientific
589+ ) => LabelOptic "multipleOf" A_Lens NamedSchema NamedSchema a b where
590+ labelOptic = #paramSchema % #multipleOf
591+ {-# INLINE labelOptic #-}
592+
593+instance
594+ ( a ~ Maybe Scientific, b ~ Maybe Scientific
595+ ) => LabelOptic "multipleOf" A_Lens ParamOtherSchema ParamOtherSchema a b where
596+ labelOptic = #paramSchema % #multipleOf
597+ {-# INLINE labelOptic #-}
src/Data/Swagger/ParamSchema.hs+5−2
@@ -1,7 +1,5 @@
1-- |
1-- |
2-- Module: Data.Swagger.ParamSchema
2-- Module: Data.Swagger.ParamSchema
3−-- Copyright: (c) 2015 GetShopTV
4−-- License: BSD3
5-- Maintainer: Nickolay Kudasov <nickolay@getshoptv.com>
3-- Maintainer: Nickolay Kudasov <nickolay@getshoptv.com>
6-- Stability: experimental
4-- Stability: experimental
7--
5--
@@ -14,6 +12,11 @@ module Data.Swagger.ParamSchema (
14 genericToParamSchema,
12 genericToParamSchema,
15 toParamSchemaBoundedIntegral,
13 toParamSchemaBoundedIntegral,
16
14
15+ -- * Schema templates
16+ passwordParamSchema,
17+ binaryParamSchema,
18+ byteParamSchema,
19+
17 -- * Generic encoding configuration
20 -- * Generic encoding configuration
18 SchemaOptions(..),
21 SchemaOptions(..),
19 defaultSchemaOptions,
22 defaultSchemaOptions,
src/Data/Swagger/Schema.hs+24−2
@@ -1,7 +1,5 @@
1-- |
1-- |
2-- Module: Data.Swagger.Schema
2-- Module: Data.Swagger.Schema
3−-- Copyright: (c) 2015 GetShopTV
4−-- License: BSD3
5-- Maintainer: Nickolay Kudasov <nickolay@getshoptv.com>
3-- Maintainer: Nickolay Kudasov <nickolay@getshoptv.com>
6-- Stability: experimental
4-- Stability: experimental
7--
5--
@@ -19,11 +17,34 @@ module Data.Swagger.Schema (
19 -- * Generic schema encoding
17 -- * Generic schema encoding
20 genericDeclareNamedSchema,
18 genericDeclareNamedSchema,
21 genericDeclareSchema,
19 genericDeclareSchema,
20+ genericDeclareNamedSchemaNewtype,
21+ genericNameSchema,
22+
23+ -- ** 'Bounded' 'Integral'
22 genericToNamedSchemaBoundedIntegral,
24 genericToNamedSchemaBoundedIntegral,
23 toSchemaBoundedIntegral,
25 toSchemaBoundedIntegral,
26+
27+ -- ** 'Bounded' 'Enum' key mappings
28+ declareSchemaBoundedEnumKeyMapping,
29+ toSchemaBoundedEnumKeyMapping,
30+
31+ -- ** Reusing 'ToParamSchema'
24 paramSchemaToNamedSchema,
32 paramSchemaToNamedSchema,
25 paramSchemaToSchema,
33 paramSchemaToSchema,
26
34
35+ -- ** Unrestricted versions
36+ genericDeclareNamedSchemaUnrestricted,
37+ genericDeclareSchemaUnrestricted,
38+
39+ -- * Schema templates
40+ passwordSchema,
41+ binarySchema,
42+ byteSchema,
43+
44+ -- * Sketching @'Schema'@s using @'ToJSON'@
45+ sketchSchema,
46+ sketchStrictSchema,
47+
27 -- * Inlining @'Schema'@s
48 -- * Inlining @'Schema'@s
28 inlineNonRecursiveSchemas,
49 inlineNonRecursiveSchemas,
29 inlineAllSchemas,
50 inlineAllSchemas,
@@ -33,6 +54,7 @@ module Data.Swagger.Schema (
33 -- * Generic encoding configuration
54 -- * Generic encoding configuration
34 SchemaOptions(..),
55 SchemaOptions(..),
35 defaultSchemaOptions,
56 defaultSchemaOptions,
57+ fromAesonOptions,
36) where
58) where
37
59
38import Data.Swagger.Internal.Schema
60import Data.Swagger.Internal.Schema
src/Data/Swagger/Schema/Generator.hsnew file+114
@@ -0,0 +1,114 @@
1+{-# LANGUAGE GADTs #-}
2+{-# LANGUAGE OverloadedLists #-}
3+{-# LANGUAGE ScopedTypeVariables #-}
4+
5+module Data.Swagger.Schema.Generator where
6+
7+import Prelude ()
8+import Prelude.Compat
9+
10+import Control.Lens.Operators
11+import Control.Monad (filterM)
12+import Data.Aeson
13+import Data.Aeson.Types
14+import qualified Data.HashMap.Strict.InsOrd as M
15+import Data.Maybe
16+import Data.Maybe
17+import Data.Proxy
18+import Data.Scientific
19+import qualified Data.Set as S
20+import Data.Swagger
21+import Data.Swagger.Declare
22+import Data.Swagger.Internal.Schema.Validation (inferSchemaTypes)
23+import qualified Data.Text as T
24+import qualified Data.Vector as V
25+import Test.QuickCheck (arbitrary)
26+import Test.QuickCheck.Gen
27+import Test.QuickCheck.Property
28+
29+-- | Note: 'schemaGen' may 'error', if schema type is not specified,
30+-- and cannot be inferred.
31+schemaGen :: Definitions Schema -> Schema -> Gen Value
32+schemaGen _ schema
33+ | Just cases <- schema ^. paramSchema . enum_ = elements cases
34+schemaGen defns schema =
35+ case schema ^. type_ of
36+ Nothing ->
37+ case inferSchemaTypes schema of
38+ [ inferredType ] -> schemaGen defns (schema & type_ ?~ inferredType)
39+ -- Gen is not MonadFail
40+ _ -> error "unable to infer schema type"
41+ Just SwaggerBoolean -> Bool <$> elements [True, False]
42+ Just SwaggerNull -> pure Null
43+ Just SwaggerNumber
44+ | Just min <- schema ^. minimum_
45+ , Just max <- schema ^. maximum_ ->
46+ Number . fromFloatDigits <$>
47+ choose (toRealFloat min, toRealFloat max :: Double)
48+ | otherwise -> Number .fromFloatDigits <$> (arbitrary :: Gen Double)
49+ Just SwaggerInteger
50+ | Just min <- schema ^. minimum_
51+ , Just max <- schema ^. maximum_ ->
52+ Number . fromInteger <$>
53+ choose (truncate min, truncate max)
54+ | otherwise -> Number . fromInteger <$> arbitrary
55+ Just SwaggerArray
56+ | Just 0 <- schema ^. maxLength -> pure $ Array V.empty
57+ | Just items <- schema ^. items ->
58+ case items of
59+ SwaggerItemsObject ref -> do
60+ size <- getSize
61+ let itemSchema = dereference defns ref
62+ minLength' = fromMaybe 0 $ fromInteger <$> schema ^. minItems
63+ maxLength' = fromMaybe size $ fromInteger <$> schema ^. maxItems
64+ arrayLength <- choose (minLength', max minLength' maxLength')
65+ generatedArray <- vectorOf arrayLength $ schemaGen defns itemSchema
66+ return . Array $ V.fromList generatedArray
67+ SwaggerItemsArray refs ->
68+ let itemGens = schemaGen defns . dereference defns <$> refs
69+ in fmap (Array . V.fromList) $ sequence itemGens
70+ Just SwaggerString -> do
71+ size <- getSize
72+ let minLength' = fromMaybe 0 $ fromInteger <$> schema ^. minLength
73+ let maxLength' = fromMaybe size $ fromInteger <$> schema ^. maxLength
74+ length <- choose (minLength', max minLength' maxLength')
75+ str <- vectorOf length arbitrary
76+ return . String $ T.pack str
77+ Just SwaggerObject -> do
78+ size <- getSize
79+ let props = dereference defns <$> schema ^. properties
80+ reqKeys = S.fromList $ schema ^. required
81+ allKeys = S.fromList . M.keys $ schema ^. properties
82+ optionalKeys = allKeys S.\\ reqKeys
83+ minProps' = fromMaybe (length reqKeys) $
84+ fromInteger <$> schema ^. minProperties
85+ maxProps' = fromMaybe size $ fromInteger <$> schema ^. maxProperties
86+ shuffledOptional <- shuffle $ S.toList optionalKeys
87+ numProps <- choose (minProps', max minProps' maxProps')
88+ let presentKeys = take numProps $ S.toList reqKeys ++ shuffledOptional
89+ let presentProps = M.filterWithKey (\k _ -> k `elem` presentKeys) props
90+ let gens = schemaGen defns <$> presentProps
91+ additionalGens <- case schema ^. additionalProperties of
92+ Just (AdditionalPropertiesSchema addlSchema) -> do
93+ additionalKeys <- sequence . take (numProps - length presentProps) . repeat $ T.pack <$> arbitrary
94+ return . M.fromList $ zip additionalKeys (repeat . schemaGen defns $ dereference defns addlSchema)
95+ _ -> return []
96+ x <- sequence $ gens <> additionalGens
97+ return . Object $ M.toHashMap x
98+ where
99+ dereference :: Definitions a -> Referenced a -> a
100+ dereference _ (Inline a) = a
101+ dereference defs (Ref (Reference ref)) = fromJust $ M.lookup ref defs
102+
103+genValue :: (ToSchema a) => Proxy a -> Gen Value
104+genValue p =
105+ let (defs, NamedSchema _ schema) = runDeclare (declareNamedSchema p) M.empty
106+ in schemaGen defs schema
107+
108+validateFromJSON :: forall a . (ToSchema a, FromJSON a) => Proxy a -> Property
109+validateFromJSON p = forAll (genValue p) $
110+ \val -> case parseEither parseJSON val of
111+ Right (_ :: a) -> succeeded
112+ Left err -> failed
113+ { reason = err
114+ }
src/Data/Swagger/Schema/Validation.hs+74−292
@@ -1,308 +1,90 @@
1−{-# LANGUAGE DeriveFunctor #-}
2−{-# LANGUAGE FlexibleInstances #-}
3−{-# LANGUAGE FunctionalDependencies #-}
4−{-# LANGUAGE GADTs #-}
5−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
6−{-# LANGUAGE LambdaCase #-}
7−{-# LANGUAGE MultiParamTypeClasses #-}
8−{-# LANGUAGE PackageImports #-}
9−{-# LANGUAGE RankNTypes #-}
10−{-# LANGUAGE ScopedTypeVariables #-}
11−{-# LANGUAGE TemplateHaskell #-}
12−{-# LANGUAGE UndecidableInstances #-}
13-- |
1-- |
14−-- Module: Data.Swagger.Schema.Validate
2+-- Module: Data.Swagger.Schema.Validation
15−-- Copyright: (c) 2015 GetShopTV
16−-- License: BSD3
17-- Maintainer: Nickolay Kudasov <nickolay@getshoptv.com>
3-- Maintainer: Nickolay Kudasov <nickolay@getshoptv.com>
18-- Stability: experimental
4-- Stability: experimental
19--
5--
20-- Validate JSON values with Swagger Schema.
6-- Validate JSON values with Swagger Schema.
21−module Data.Swagger.Schema.Validation where
7+module Data.Swagger.Schema.Validation (
8+ -- * How to use validation
9+ -- $howto
22
10
23−import Control.Applicative
11+ -- ** Examples
24−import Control.Lens
12+ -- $examples
25−import Control.Lens.TH
26−import Control.Monad (when)
27
13
28−import Data.Aeson hiding (Result)
14+ -- ** Validating @'Maybe'@
29−import Data.Foldable (traverse_, for_, sequenceA_)
15+ -- $maybe
30−import Data.HashMap.Strict (HashMap)
31−import qualified Data.HashMap.Strict as HashMap
32−import qualified "unordered-containers" Data.HashSet as HashSet
33−import Data.Monoid
34−import Data.Proxy
35−import Data.Scientific (Scientific, isInteger)
36−import Data.Text (Text)
37−import qualified Data.Text as Text
38−import Data.Vector (Vector)
39−import qualified Data.Vector as Vector
40
16
41−import Data.Swagger.Declare
17+ -- * JSON validation
42−import Data.Swagger.Internal
43−import Data.Swagger.Internal.Schema
44−import Data.Swagger.Lens
45
18
46−-- | Validate @'ToJSON'@ instance matches @'ToSchema'@ for a given value.
19+ ValidationError,
47−-- This can be used with QuickCheck to ensure those instances are coherent:
48−--
49−-- prop> validateToJSON (x :: Int) == []
50−validateToJSON :: forall a. (ToJSON a, ToSchema a) => a -> [String]
51−validateToJSON x = case runValidation (validateWithSchema js) cfg schema of
52− Failed xs -> xs
53− Passed _ -> mempty
54− where
55− js = toJSON x
56− cfg = defaultConfig { configDefinitions = defs }
57− (defs, schema) = runDeclare (declareSchema (Proxy :: Proxy a)) mempty
58−
59−-- | Validation result type.
60−data Result a
61− = Failed [String] -- ^ Validation failed with a list of error messages.
62− | Passed a -- ^ Validation passed.
63− deriving (Eq, Show, Functor)
64
20
65−instance Applicative Result where
21+ -- ** Using 'ToJSON' and 'ToSchema'
66− pure = Passed
22+ validatePrettyToJSON,
67− Passed f <*> Passed x = Passed (f x)
23+ validateToJSON,
68− Failed xs <*> Failed ys = Failed (xs <> ys)
24+ validateToJSONWithPatternChecker,
69− Failed xs <*> _ = Failed xs
25+ renderValidationErrors,
70− _ <*> Failed ys = Failed ys
71
26
72−instance Alternative Result where
27+ -- ** Using 'Value' and 'Schema'
73− empty = Failed mempty
28+ validateJSON,
74− Passed x <|> _ = Passed x
29+ validateJSONWithPatternChecker,
75− _ <|> y = y
30+) where
76
31
77−instance Monad Result where
32+import Data.Swagger.Internal.Schema.Validation
78− return = pure
79− Passed x >>= f = f x
80− Failed xs >>= f = Failed xs
81
33
82−-- | Validation configuration.
34+-- $setup
83−data Config = Config
35+-- >>> import Control.Lens
84− { -- | Pattern checker for @'_paramSchemaPattern'@ validation.
36+-- >>> import Data.Aeson
85− configPatternChecker :: Pattern -> Text -> Bool
37+-- >>> import Data.Proxy
86− -- | Schema definitions in scope to resolve references.
38+-- >>> import Data.Swagger
87− , configDefinitions :: Definitions Schema
39+-- >>> import GHC.Generics
88− }
40+-- >>> :set -XDeriveGeneric
89
41
90−-- | Default @'Config'@:
42+-- $howto
91--
43--
92−-- @
44+-- This module provides helpful functions for JSON validation.
93−-- defaultConfig = 'Config'
45+-- These functions are meant to be used in test suites for your application
94−-- { 'configPatternChecker' = \\_pattern _str -> True
46+-- to ensure that JSON respresentation for your data corresponds to
95−-- , 'configDefinitions' = mempty
47+-- schemas you're using for the Swagger specification.
96−-- }
48+--
97−-- @
49+-- It is recommended to use validation functions as QuickCheck properties
98−defaultConfig :: Config
50+-- (see <http://hackage.haskell.org/package/QuickCheck>).
99−defaultConfig = Config
100− { configPatternChecker = \_pattern _str -> True
101− , configDefinitions = mempty
102− }
103−
104−-- | Value validation.
105−newtype Validation s a = Validation { runValidation :: Config -> s -> Result a }
106− deriving (Functor)
107−
108−instance Applicative (Validation schema) where
109− pure x = Validation (\_ _ -> pure x)
110− Validation f <*> Validation x = Validation (\c s -> f c s <*> x c s)
111−
112−instance Alternative (Validation schema) where
113− empty = Validation (\_ _ -> empty)
114− Validation x <|> Validation y = Validation (\c s -> x c s <|> y c s)
115−
116−instance Profunctor Validation where
117− dimap f g (Validation k) = Validation (\c s -> fmap g (k c (f s)))
118−
119−instance Choice Validation where
120− left' (Validation g) = Validation (\c -> either (fmap Left . g c) (pure . Right))
121− right' (Validation g) = Validation (\c -> either (pure . Left) (fmap Right . g c))
122−
123−instance Monad (Validation s) where
124− return = pure
125− Validation x >>= f = Validation (\c s -> x c s >>= \x -> runValidation (f x) c s)
126− (>>) = (*>)
127−
128−withConfig :: (Config -> Validation s a) -> Validation s a
129−withConfig f = Validation (\c -> runValidation (f c) c)
130−
131−withSchema :: (s -> Validation s a) -> Validation s a
132−withSchema f = Validation (\c s -> runValidation (f s) c s)
133−
134−-- | Issue an error message.
135−invalid :: String -> Validation schema a
136−invalid msg = Validation (\_ _ -> Failed [msg])
137−
138−-- | Validation passed.
139−valid :: Validation schema ()
140−valid = pure ()
141−
142−-- | Validate schema's property given a lens into that property
143−-- and property checker.
144−check :: Lens' s (Maybe a) -> (a -> Validation s ()) -> Validation s ()
145−check l g = withSchema $ \schema ->
146− case schema ^. l of
147− Nothing -> valid
148− Just x -> g x
149−
150−-- | Validate same value with different schema.
151−sub :: t -> Validation t a -> Validation s a
152−sub = lmap . const
153−
154−-- | Validate same value with a part of the original schema.
155−sub_ :: Getting a s a -> Validation a r -> Validation s r
156−sub_ = lmap . view
157−
158−-- | Validate value against a schema given schema reference and validation function.
159−withRef :: Reference -> (Schema -> Validation s a) -> Validation s a
160−withRef (Reference ref) f = withConfig $ \cfg ->
161− case HashMap.lookup ref (configDefinitions cfg) of
162− Nothing -> invalid $ "unknown schema " ++ show ref
163− Just s -> f s
164−
165−validateWithSchemaRef :: Referenced Schema -> Value -> Validation s ()
166−validateWithSchemaRef (Ref ref) js = withRef ref $ \schema -> sub schema (validateWithSchema js)
167−validateWithSchemaRef (Inline s) js = sub s (validateWithSchema js)
168−
169−-- | Validate JSON @'Value'@ with Swagger @'Schema'@.
170−validateWithSchema :: Value -> Validation Schema ()
171−validateWithSchema value = do
172− validateSchemaType value
173− sub_ paramSchema $ validateEnum value
174−
175−-- | Validate JSON @'Value'@ with Swagger @'ParamSchema'@.
176−validateWithParamSchema :: Value -> Validation (ParamSchema t) ()
177−validateWithParamSchema value = do
178− validateParamSchemaType value
179− validateEnum value
180−
181−validateInteger :: Scientific -> Validation (ParamSchema t) ()
182−validateInteger n = do
183− when (not (isInteger n)) $
184− invalid ("not an integer")
185− validateNumber n
186−
187−validateNumber :: Scientific -> Validation (ParamSchema t) ()
188−validateNumber n = withConfig $ \cfg -> withSchema $ \schema -> do
189− let exMax = Just True == schema ^. exclusiveMaximum
190− exMin = Just True == schema ^. exclusiveMinimum
191−
192− check maximum_ $ \m ->
193− when (if exMax then (n >= m) else (n > m)) $
194− invalid ("value " ++ show n ++ " exceeds maximum (should be " ++ if exMax then "<" else "<=" ++ show m ++ ")")
195−
196− check minimum_ $ \m ->
197− when (if exMin then (n <= m) else (n < m)) $
198− invalid ("value " ++ show n ++ " falls below minimum (should be " ++ if exMin then ">" else ">=" ++ show m ++ ")")
199−
200− check multipleOf $ \k ->
201− when (not (isInteger (n / k))) $
202− invalid ("expected a multiple of " ++ show k ++ " but got " ++ show n)
203−
204−validateString :: Text -> Validation (ParamSchema t) ()
205−validateString s = do
206− check maxLength $ \n ->
207− when (len > fromInteger n) $
208− invalid ("string is too long (length should be <=" ++ show n ++ ")")
209−
210− check minLength $ \n ->
211− when (len < fromInteger n) $
212− invalid ("string is too short (length should be >=" ++ show n ++ ")")
213−
214− check pattern $ \regex -> do
215− withConfig $ \cfg -> do
216− when (not (configPatternChecker cfg regex s)) $
217− invalid ("string does not match pattern " ++ show regex)
218− where
219− len = Text.length s
220−
221−validateArray :: Vector Value -> Validation (ParamSchema t) ()
222−validateArray xs = do
223− check maxItems $ \n ->
224− when (len > fromInteger n) $
225− invalid ("array exceeds maximum size (should be <=" ++ show n ++ ")")
226−
227− check minItems $ \n ->
228− when (len < fromInteger n) $
229− invalid ("array is too short (size should be >=" ++ show n ++ ")")
230−
231− check items $ \case
232− SwaggerItemsPrimitive _ itemSchema -> sub itemSchema $ traverse_ validateWithParamSchema xs
233− SwaggerItemsObject itemSchema -> traverse_ (validateWithSchemaRef itemSchema) xs
234− SwaggerItemsArray itemSchemas -> do
235− when (len /= length itemSchemas) $
236− invalid ("array size is invalid (should be exactly " ++ show (length itemSchemas) ++ ")")
237− sequenceA_ (zipWith validateWithSchemaRef itemSchemas (Vector.toList xs))
238−
239− check uniqueItems $ \unique ->
240− when (unique && not allUnique) $
241− invalid ("array is expected to contain unique items, but it does not")
242− where
243− len = Vector.length xs
244− allUnique = len == HashSet.size (HashSet.fromList (Vector.toList xs))
245−
246−validateObject :: HashMap Text Value -> Validation Schema ()
247−validateObject o = withSchema $ \schema ->
248− case schema ^. discriminator of
249− Just pname -> case fromJSON <$> HashMap.lookup pname o of
250− Just (Success ref) -> validateWithSchemaRef ref (Object o)
251− Just (Error msg) -> invalid ("failed to parse discriminator property " ++ show pname ++ ": " ++ show msg)
252− Nothing -> invalid ("discriminator property " ++ show pname ++ "is missing")
253− Nothing -> do
254− check maxProperties $ \n ->
255− when (size > n) $
256− invalid ("object size exceeds maximum (total number of properties should be <=" ++ show n ++ ")")
257−
258− check minProperties $ \n ->
259− when (size < n) $
260− invalid ("object size is too small (total number of properties should be >=" ++ show n ++ ")")
261−
262− validateRequired
263− validateProps
264− where
265− size = fromIntegral (HashMap.size o)
266−
267− validateRequired = withSchema $ \schema -> traverse_ validateReq (schema ^. required)
268− validateReq name =
269− when (not (HashMap.member name o)) $
270− invalid ("property " ++ show name ++ " is required, but not found in " ++ show (encode o))
271−
272− validateProps = withSchema $ \schema -> do
273− for_ (HashMap.toList o) $ \(k, v) ->
274− case v of
275− Null | not (k `elem` (schema ^. required)) -> valid -- null is fine for non-required property
276− _ ->
277− case HashMap.lookup k (schema ^. properties) of
278− Nothing -> check additionalProperties $ \s -> sub s $ validateWithSchema v
279− Just s -> validateWithSchemaRef s v
280−
281−validateEnum :: Value -> Validation (ParamSchema t) ()
282−validateEnum value = do
283− check enum_ $ \xs ->
284− when (value `notElem` xs) $
285− invalid ("expected one of " ++ show (encode xs) ++ " but got " ++ show value)
286−
287−validateSchemaType :: Value -> Validation Schema ()
288−validateSchemaType value = withSchema $ \schema ->
289− case (schema ^. type_, value) of
290− (SwaggerNull, Null) -> valid
291− (SwaggerBoolean, Bool _) -> valid
292− (SwaggerInteger, Number n) -> sub_ paramSchema (validateInteger n)
293− (SwaggerNumber, Number n) -> sub_ paramSchema (validateNumber n)
294− (SwaggerString, String s) -> sub_ paramSchema (validateString s)
295− (SwaggerArray, Array xs) -> sub_ paramSchema (validateArray xs)
296− (SwaggerObject, Object o) -> validateObject o
297− (t, _) -> invalid $ "expected JSON value of type " ++ show t
298−
299−validateParamSchemaType :: Value -> Validation (ParamSchema t) ()
300−validateParamSchemaType value = withSchema $ \schema ->
301− case (schema ^. type_, value) of
302− (SwaggerBoolean, Bool _) -> valid
303− (SwaggerInteger, Number n) -> validateInteger n
304− (SwaggerNumber, Number n) -> validateNumber n
305− (SwaggerString, String s) -> validateString s
306− (SwaggerArray, Array xs) -> validateArray xs
307− (t, _) -> invalid $ "expected JSON value of type " ++ show t
308
51
52+-- $examples
53+--
54+-- >>> validateToJSON "hello"
55+-- []
56+--
57+-- >>> validateToJSON False
58+-- []
59+--
60+-- >>> newtype Nat = Nat Integer deriving Generic
61+-- >>> instance ToJSON Nat where toJSON (Nat n) = toJSON n
62+-- >>> instance ToSchema Nat where declareNamedSchema proxy = genericDeclareNamedSchema defaultSchemaOptions proxy & mapped.minimum_ ?~ 0
63+-- >>> validateToJSON (Nat 10)
64+-- []
65+-- >>> validateToJSON (Nat (-5))
66+-- ["value -5.0 falls below minimum (should be >=0.0)"]
67+
68+-- $maybe
69+--
70+-- Because @'Maybe' a@ has the same schema as @a@, validation
71+-- generally fails for @null@ JSON:
72+--
73+-- >>> validateToJSON (Nothing :: Maybe String)
74+-- ["expected JSON value of type SwaggerString"]
75+-- >>> validateToJSON ([Just "hello", Nothing] :: [Maybe String])
76+-- ["expected JSON value of type SwaggerString"]
77+-- >>> validateToJSON (123, Nothing :: Maybe String)
78+-- ["expected JSON value of type SwaggerString"]
79+--
80+-- However, when @'Maybe' a@ is a type of a record field,
81+-- validation takes @'required'@ property of the @'Schema'@
82+-- into account:
83+--
84+-- >>> data Person = Person { name :: String, age :: Maybe Int } deriving Generic
85+-- >>> instance ToJSON Person
86+-- >>> instance ToSchema Person
87+-- >>> validateToJSON (Person "Nick" (Just 24))
88+-- []
89+-- >>> validateToJSON (Person "Nick" Nothing)
90+-- []
src/Data/Swagger/SchemaOptions.hs+35
@@ -1,5 +1,14 @@
1+{-# LANGUAGE RecordWildCards #-}
2+-- |
3+-- Module: Data.Swagger.SchemaOptions
4+-- Maintainer: Nickolay Kudasov <nickolay@getshoptv.com>
5+-- Stability: experimental
6+--
7+-- Generic deriving options for @'ToParamSchema'@ and @'ToSchema'@.
1module Data.Swagger.SchemaOptions where
8module Data.Swagger.SchemaOptions where
2
9
10+import qualified Data.Aeson.Types as Aeson
11+
3-- | Options that specify how to encode your type to Swagger schema.
12-- | Options that specify how to encode your type to Swagger schema.
4data SchemaOptions = SchemaOptions
13data SchemaOptions = SchemaOptions
5 { -- | Function applied to field labels. Handy for removing common record prefixes for example.
14 { -- | Function applied to field labels. Handy for removing common record prefixes for example.
@@ -35,3 +44,29 @@ defaultSchemaOptions = SchemaOptions
35 , unwrapUnaryRecords = False
44 , unwrapUnaryRecords = False
36 }
45 }
37
46
47+-- | Convert 'Aeson.Options' to 'SchemaOptions'.
48+--
49+-- Specifically the following fields get copied:
50+--
51+-- * 'fieldLabelModifier'
52+-- * 'constructorTagModifier'
53+-- * 'allNullaryToStringTag'
54+-- * 'unwrapUnaryRecords'
55+--
56+-- Note that these fields have no effect on `SchemaOptions`:
57+--
58+-- * 'Aeson.omitNothingFields'
59+-- * 'Aeson.sumEncoding'
60+-- * 'Aeson.tagSingleConstructors'
61+--
62+-- The rest is defined as in 'defaultSchemaOptions'.
63+--
64+-- @since 2.2.1
65+--
66+fromAesonOptions :: Aeson.Options -> SchemaOptions
67+fromAesonOptions opts = defaultSchemaOptions
68+ { fieldLabelModifier = Aeson.fieldLabelModifier opts
69+ , constructorTagModifier = Aeson.constructorTagModifier opts
70+ , allNullaryToStringTag = Aeson.allNullaryToStringTag opts
71+ , unwrapUnaryRecords = Aeson.unwrapUnaryRecords opts
72+ }
stack-lts-2.yamldeleted−5
@@ -1,5 +0,0 @@
1−flags: {}
2−packages:
3−- '.'
4−extra-deps: []
5−resolver: lts-2.22
stack.yaml+7−3
@@ -1,5 +1,9 @@
1−flags: {}
1+resolver: lts-14.3
2packages:
2packages:
3- '.'
3- '.'
4−extra-deps: []
4+extra-deps:
5−resolver: nightly-2016-01-26
5+- optics-core-0.2
6+- optics-th-0.2
7+- optics-extra-0.2
8+- indexed-profunctors-0.1
9+- insert-ordered-containers-0.2.3
swagger2.cabal+103−42
@@ -1,23 +1,38 @@
1+cabal-version: >=1.10
1name: swagger2
2name: swagger2
2−version: 1.2.1
3+version: 2.5
4+
3synopsis: Swagger 2.0 data model
5synopsis: Swagger 2.0 data model
6+category: Web, Swagger
4−description: Please see README.md
7+description:
8+ This library is intended to be used for decoding and encoding Swagger 2.0 API
9+ specifications as well as manipulating them.
10+ .
11+ The original Swagger 2.0 specification is available at http://swagger.io/specification/.
12+
5homepage: https://github.com/GetShopTV/swagger2
13homepage: https://github.com/GetShopTV/swagger2
6bug-reports: https://github.com/GetShopTV/swagger2/issues
14bug-reports: https://github.com/GetShopTV/swagger2/issues
7license: BSD3
15license: BSD3
8license-file: LICENSE
16license-file: LICENSE
9author: Nickolay Kudasov
17author: Nickolay Kudasov
10maintainer: nickolay@getshoptv.com
18maintainer: nickolay@getshoptv.com
11−copyright: (c) 2015, GetShopTV
19+copyright: (c) 2015-2016, GetShopTV
12−category: Web
13−build-type: Simple
20+build-type: Custom
14extra-source-files:
21extra-source-files:
15 README.md
22 README.md
16 , CHANGELOG.md
23 , CHANGELOG.md
17 , examples/*.hs
24 , examples/*.hs
18 , include/overlapping-compat.h
25 , include/overlapping-compat.h
19−cabal-version: >=1.10
26+tested-with:
20−tested-with: GHC==7.8.4, GHC==7.10.3
27+ GHC ==8.0.2
28+ || ==8.2.2
29+ || ==8.4.4
30+ || ==8.6.5
31+ || ==8.8.1
32+
33+custom-setup
34+ setup-depends:
35+ base, Cabal, cabal-doctest >=1.0.6 && <1.1
21
36
22library
37library
23 hs-source-dirs: src
38 hs-source-dirs: src
@@ -26,66 +41,112 @@ library
26 Data.Swagger
41 Data.Swagger
27 Data.Swagger.Declare
42 Data.Swagger.Declare
28 Data.Swagger.Lens
43 Data.Swagger.Lens
44+ Data.Swagger.Operation
45+ Data.Swagger.Optics
29 Data.Swagger.ParamSchema
46 Data.Swagger.ParamSchema
30 Data.Swagger.Schema
47 Data.Swagger.Schema
48+ Data.Swagger.Schema.Generator
31 Data.Swagger.Schema.Validation
49 Data.Swagger.Schema.Validation
32 Data.Swagger.SchemaOptions
50 Data.Swagger.SchemaOptions
33
51
34 -- internal modules
52 -- internal modules
35 Data.Swagger.Internal
53 Data.Swagger.Internal
36 Data.Swagger.Internal.Schema
54 Data.Swagger.Internal.Schema
55+ Data.Swagger.Internal.Schema.Validation
37 Data.Swagger.Internal.ParamSchema
56 Data.Swagger.Internal.ParamSchema
38 Data.Swagger.Internal.Utils
57 Data.Swagger.Internal.Utils
58+ Data.Swagger.Internal.AesonUtils
59+ Data.Swagger.Internal.TypeShape
60+
61+ -- GHC boot libraries
39− build-depends: base >=4.7 && <4.10
62+ build-depends:
40− , base-compat >=0.6.0 && <0.10
63+ base >=4.9 && <4.14
64+ , aeson-pretty >=0.8.7 && <0.9
65+ , bytestring >=0.10.4.0 && <0.11
66+ , containers >=0.5.5.1 && <0.7
67+ , template-haskell >=2.9.0.0 && <2.16
68+ , time >=1.4.2 && <1.10
69+ , transformers >=0.3.0.0 && <0.6
70+
71+ build-depends:
72+ mtl >=2.1 && <2.3
73+ , text >=1.2.3.0 && <1.3
74+
75+ -- other dependencies
76+ build-depends:
77+ base-compat-batteries >=0.10.4 && <0.12
41− , aeson
78+ , aeson >=1.4.2.0 && <1.5
42− , containers
79+ -- cookie 0.4.3 is needed by GHC 7.8 due to time>=1.4 constraint
80+ , cookie >=0.4.3 && <0.5
81+ , generics-sop >=0.3.2.0 && <0.6
43− , hashable
82+ , hashable >=1.2.7.0 && <1.4
44− , http-media
83+ , http-media >=0.7.1.2 && <0.9
84+ , insert-ordered-containers >=0.2.3 && <0.3
45− , lens
85+ , lens >=4.16.1 && <4.19
46− , mtl
47− , network
86+ , network >=2.6.3.5 && <3.2
87+ , optics-core >=0.2 && <0.3
88+ , optics-th >=0.2 && <0.3
48− , scientific
89+ , scientific >=0.3.6.2 && <0.4
49− , text
90+ , transformers-compat >=0.3 && <0.7
50− , template-haskell
51− , time
52− , transformers
53− , unordered-containers
91+ , unordered-containers >=0.2.9.0 && <0.3
92+ , uuid-types >=1.0.3 && <1.1
54− , vector
93+ , vector >=0.12.0.1 && <0.13
94+ , QuickCheck >=2.10.1 && <2.14
95+
55 default-language: Haskell2010
96 default-language: Haskell2010
56
97
57test-suite spec
98test-suite spec
58 type: exitcode-stdio-1.0
99 type: exitcode-stdio-1.0
59 hs-source-dirs: test
100 hs-source-dirs: test
60 main-is: Spec.hs
101 main-is: Spec.hs
102+
103+ -- From library parat
104+ -- We need aeson's toEncoding for doctests too
61− build-depends: base
105+ build-depends:
106+ base
107+ , swagger2
108+ , aeson
62− , base-compat
109+ , base-compat-batteries
63− , aeson
110+ , bytestring
64− , aeson-qq
65− , containers
111+ , containers
66− , hashable
112+ , hashable
67− , hspec
113+ , insert-ordered-containers
68− , HUnit
114+ , lens
69− , mtl
115+ , mtl
70− , QuickCheck
116+ , template-haskell
71− , swagger2
72− , text
117+ , text
73− , time
118+ , time
74− , unordered-containers
119+ , unordered-containers
75− , vector
120+ , vector
76− , lens
121+ , QuickCheck
122+
123+ -- test-suite only dependencies
124+ build-depends:
125+ hspec >=2.5.5 && <2.8
126+ , HUnit >=1.6.0.0 && <1.7
127+ , quickcheck-instances >=0.3.19 && <0.14
128+ , utf8-string >=1.0.1.1 && <1.1
129+
130+ -- https://github.com/haskell/cabal/issues/3708
131+ build-tool-depends:
132+ hspec-discover:hspec-discover >=2.5.5 && <2.8
133+
77 other-modules:
134 other-modules:
78 SpecCommon
135 SpecCommon
79 Data.SwaggerSpec
136 Data.SwaggerSpec
137+ Data.Swagger.CommonTestTypes
138+ Data.Swagger.ParamSchemaSpec
80 Data.Swagger.SchemaSpec
139 Data.Swagger.SchemaSpec
81 Data.Swagger.Schema.ValidationSpec
140 Data.Swagger.Schema.ValidationSpec
141+ Data.Swagger.Schema.GeneratorSpec
82 default-language: Haskell2010
142 default-language: Haskell2010
83
143
84−test-suite doctest
144+test-suite doctests
145+ -- See QuickCheck note in https://github.com/phadej/cabal-doctest#notes
85− build-depends: base, doctest, Glob
146+ build-depends: base, doctest, Glob, QuickCheck
86 default-language: Haskell2010
147 default-language: Haskell2010
87 hs-source-dirs: test
148 hs-source-dirs: test
88− main-is: DocTest.hs
149+ main-is: doctests.hs
89 type: exitcode-stdio-1.0
150 type: exitcode-stdio-1.0
90
151
91source-repository head
152source-repository head
test/Data/Swagger/CommonTestTypes.hsnew file+679
@@ -0,0 +1,679 @@
1+{-# LANGUAGE DeriveGeneric #-}
2+{-# LANGUAGE QuasiQuotes #-}
3+{-# LANGUAGE ScopedTypeVariables #-}
4+
5+module Data.Swagger.CommonTestTypes where
6+
7+import Prelude ()
8+import Prelude.Compat
9+
10+import Data.Aeson (ToJSON (..), ToJSONKey (..), Value)
11+import Data.Aeson.QQ.Simple
12+import Data.Aeson.Types (toJSONKeyText)
13+import Data.Char
14+import Data.Map (Map)
15+import Data.Proxy
16+import Data.Set (Set)
17+import qualified Data.Text as Text
18+import GHC.Generics
19+
20+import Data.Swagger
21+
22+-- ========================================================================
23+-- Unit type
24+-- ========================================================================
25+
26+data Unit = Unit deriving (Generic)
27+instance ToParamSchema Unit
28+instance ToSchema Unit
29+
30+unitSchemaJSON :: Value
31+unitSchemaJSON = [aesonQQ|
32+{
33+ "type": "string",
34+ "enum": ["Unit"]
35+}
36+|]
37+
38+-- ========================================================================
39+-- Color (enum)
40+-- ========================================================================
41+data Color
42+ = Red
43+ | Green
44+ | Blue
45+ deriving (Generic)
46+instance ToParamSchema Color
47+instance ToSchema Color
48+
49+colorSchemaJSON :: Value
50+colorSchemaJSON = [aesonQQ|
51+{
52+ "type": "string",
53+ "enum": ["Red", "Green", "Blue"]
54+}
55+|]
56+
57+-- ========================================================================
58+-- Shade (paramSchemaToNamedSchema)
59+-- ========================================================================
60+
61+data Shade = Dim | Bright deriving (Generic)
62+instance ToParamSchema Shade
63+
64+instance ToSchema Shade where declareNamedSchema = pure . paramSchemaToNamedSchema defaultSchemaOptions
65+
66+shadeSchemaJSON :: Value
67+shadeSchemaJSON = [aesonQQ|
68+{
69+ "type": "string",
70+ "enum": ["Dim", "Bright"]
71+}
72+|]
73+
74+-- ========================================================================
75+-- Paint (record with bounded enum property)
76+-- ========================================================================
77+
78+newtype Paint = Paint { color :: Color }
79+ deriving (Generic)
80+instance ToSchema Paint
81+
82+paintSchemaJSON :: Value
83+paintSchemaJSON = [aesonQQ|
84+{
85+ "type": "object",
86+ "properties":
87+ {
88+ "color":
89+ {
90+ "$ref": "#/definitions/Color"
91+ }
92+ },
93+ "required": ["color"]
94+}
95+|]
96+
97+paintInlinedSchemaJSON :: Value
98+paintInlinedSchemaJSON = [aesonQQ|
99+{
100+ "type": "object",
101+ "properties":
102+ {
103+ "color":
104+ {
105+ "type": "string",
106+ "enum": ["Red", "Green", "Blue"]
107+ }
108+ },
109+ "required": ["color"]
110+}
111+|]
112+
113+-- ========================================================================
114+-- Status (constructorTagModifier)
115+-- ========================================================================
116+
117+data Status
118+ = StatusOk
119+ | StatusError
120+ deriving (Generic)
121+
122+instance ToParamSchema Status where
123+ toParamSchema = genericToParamSchema defaultSchemaOptions
124+ { constructorTagModifier = map toLower . drop (length "Status") }
125+instance ToSchema Status where
126+ declareNamedSchema = genericDeclareNamedSchema defaultSchemaOptions
127+ { constructorTagModifier = map toLower . drop (length "Status") }
128+
129+statusSchemaJSON :: Value
130+statusSchemaJSON = [aesonQQ|
131+{
132+ "type": "string",
133+ "enum": ["ok", "error"]
134+}
135+|]
136+
137+-- ========================================================================
138+-- Email (newtype with unwrapUnaryRecords set to True)
139+-- ========================================================================
140+
141+newtype Email = Email { getEmail :: String }
142+ deriving (Generic)
143+instance ToParamSchema Email
144+instance ToSchema Email where
145+ declareNamedSchema = genericDeclareNamedSchema defaultSchemaOptions
146+ { unwrapUnaryRecords = True }
147+
148+emailSchemaJSON :: Value
149+emailSchemaJSON = [aesonQQ|
150+{
151+ "type": "string"
152+}
153+|]
154+
155+-- ========================================================================
156+-- UserId (non-record newtype)
157+-- ========================================================================
158+
159+newtype UserId = UserId Integer
160+ deriving (Eq, Ord, Generic)
161+instance ToParamSchema UserId
162+instance ToSchema UserId
163+
164+userIdSchemaJSON :: Value
165+userIdSchemaJSON = [aesonQQ|
166+{
167+ "type": "integer"
168+}
169+|]
170+
171+-- ========================================================================
172+-- UserGroup (set newtype)
173+-- ========================================================================
174+
175+newtype UserGroup = UserGroup (Set UserId)
176+ deriving (Generic)
177+instance ToSchema UserGroup
178+
179+userGroupSchemaJSON :: Value
180+userGroupSchemaJSON = [aesonQQ|
181+{
182+ "type": "array",
183+ "items": { "$ref": "#/definitions/UserId" },
184+ "uniqueItems": true
185+}
186+|]
187+
188+-- ========================================================================
189+-- Person (simple record with optional fields)
190+-- ========================================================================
191+data Person = Person
192+ { name :: String
193+ , phone :: Integer
194+ , email :: Maybe String
195+ } deriving (Generic)
196+
197+instance ToSchema Person
198+
199+personSchemaJSON :: Value
200+personSchemaJSON = [aesonQQ|
201+{
202+ "type": "object",
203+ "properties":
204+ {
205+ "name": { "type": "string" },
206+ "phone": { "type": "integer" },
207+ "email": { "type": "string" }
208+ },
209+ "required": ["name", "phone"]
210+}
211+|]
212+
213+-- ========================================================================
214+-- Player (record newtype)
215+-- ========================================================================
216+
217+newtype Player = Player
218+ { position :: Point
219+ } deriving (Generic)
220+instance ToSchema Player
221+
222+playerSchemaJSON :: Value
223+playerSchemaJSON = [aesonQQ|
224+{
225+ "type": "object",
226+ "properties":
227+ {
228+ "position":
229+ {
230+ "$ref": "#/definitions/Point"
231+ }
232+ },
233+ "required": ["position"]
234+}
235+|]
236+
237+newtype Players = Players [Inlined Player]
238+ deriving (Generic)
239+instance ToSchema Players
240+
241+playersSchemaJSON :: Value
242+playersSchemaJSON = [aesonQQ|
243+{
244+ "type": "array",
245+ "items":
246+ {
247+ "type": "object",
248+ "properties":
249+ {
250+ "position":
251+ {
252+ "$ref": "#/definitions/Point"
253+ }
254+ },
255+ "required": ["position"]
256+ }
257+}
258+|]
259+
260+-- ========================================================================
261+-- Character (sum type with ref and record in alternative)
262+-- ========================================================================
263+
264+data Character
265+ = PC Player
266+ | NPC { npcName :: String, npcPosition :: Point }
267+ deriving (Generic)
268+instance ToSchema Character
269+
270+characterSchemaJSON :: Value
271+characterSchemaJSON = [aesonQQ|
272+{
273+ "type": "object",
274+ "properties":
275+ {
276+ "PC": { "$ref": "#/definitions/Player" },
277+ "NPC":
278+ {
279+ "type": "object",
280+ "properties":
281+ {
282+ "npcName": { "type": "string" },
283+ "npcPosition": { "$ref": "#/definitions/Point" }
284+ },
285+ "required": ["npcName", "npcPosition"]
286+ }
287+ },
288+ "maxProperties": 1,
289+ "minProperties": 1
290+}
291+|]
292+
293+characterInlinedSchemaJSON :: Value
294+characterInlinedSchemaJSON = [aesonQQ|
295+{
296+ "type": "object",
297+ "properties":
298+ {
299+ "PC":
300+ {
301+ "type": "object",
302+ "properties":
303+ {
304+ "position":
305+ {
306+ "type": "object",
307+ "properties":
308+ {
309+ "x": { "type": "number", "format": "double" },
310+ "y": { "type": "number", "format": "double" }
311+ },
312+ "required": ["x", "y"]
313+ }
314+ },
315+ "required": ["position"]
316+ },
317+ "NPC":
318+ {
319+ "type": "object",
320+ "properties":
321+ {
322+ "npcName": { "type": "string" },
323+ "npcPosition":
324+ {
325+ "type": "object",
326+ "properties":
327+ {
328+ "x": { "type": "number", "format": "double" },
329+ "y": { "type": "number", "format": "double" }
330+ },
331+ "required": ["x", "y"]
332+ }
333+ },
334+ "required": ["npcName", "npcPosition"]
335+ }
336+ },
337+ "maxProperties": 1,
338+ "minProperties": 1
339+}
340+|]
341+
342+characterInlinedPlayerSchemaJSON :: Value
343+characterInlinedPlayerSchemaJSON = [aesonQQ|
344+{
345+ "type": "object",
346+ "properties":
347+ {
348+ "PC":
349+ {
350+ "type": "object",
351+ "properties":
352+ {
353+ "position":
354+ {
355+ "$ref": "#/definitions/Point"
356+ }
357+ },
358+ "required": ["position"]
359+ },
360+ "NPC":
361+ {
362+ "type": "object",
363+ "properties":
364+ {
365+ "npcName": { "type": "string" },
366+ "npcPosition": { "$ref": "#/definitions/Point" }
367+ },
368+ "required": ["npcName", "npcPosition"]
369+ }
370+ },
371+ "maxProperties": 1,
372+ "minProperties": 1
373+}
374+|]
375+
376+-- ========================================================================
377+-- ISPair (non-record product data type)
378+-- ========================================================================
379+data ISPair = ISPair Integer String
380+ deriving (Generic)
381+
382+instance ToSchema ISPair
383+
384+ispairSchemaJSON :: Value
385+ispairSchemaJSON = [aesonQQ|
386+{
387+ "type": "array",
388+ "items":
389+ [
390+ { "type": "integer" },
391+ { "type": "string" }
392+ ],
393+ "minItems": 2,
394+ "maxItems": 2
395+}
396+|]
397+
398+-- ========================================================================
399+-- Point (record data type with custom fieldLabelModifier)
400+-- ========================================================================
401+
402+data Point = Point
403+ { pointX :: Double
404+ , pointY :: Double
405+ } deriving (Generic)
406+
407+instance ToSchema Point where
408+ declareNamedSchema = genericDeclareNamedSchema defaultSchemaOptions
409+ { fieldLabelModifier = map toLower . drop (length "point") }
410+
411+pointSchemaJSON :: Value
412+pointSchemaJSON = [aesonQQ|
413+{
414+ "type": "object",
415+ "properties":
416+ {
417+ "x": { "type": "number", "format": "double" },
418+ "y": { "type": "number", "format": "double" }
419+ },
420+ "required": ["x", "y"]
421+}
422+|]
423+
424+-- ========================================================================
425+-- Point (record data type with multiple fields)
426+-- ========================================================================
427+
428+data Point5 = Point5
429+ { point5X :: Double
430+ , point5Y :: Double
431+ , point5Z :: Double
432+ , point5U :: Double
433+ , point5V :: Double -- 5 dimensional!
434+ } deriving (Generic)
435+
436+instance ToSchema Point5 where
437+ declareNamedSchema = genericDeclareNamedSchema defaultSchemaOptions
438+ { fieldLabelModifier = map toLower . drop (length "point5") }
439+
440+point5SchemaJSON :: Value
441+point5SchemaJSON = [aesonQQ|
442+{
443+ "type": "object",
444+ "properties":
445+ {
446+ "x": { "type": "number", "format": "double" },
447+ "y": { "type": "number", "format": "double" },
448+ "z": { "type": "number", "format": "double" },
449+ "u": { "type": "number", "format": "double" },
450+ "v": { "type": "number", "format": "double" }
451+ },
452+ "required": ["x", "y", "z", "u", "v"]
453+}
454+|]
455+
456+point5Properties :: [String]
457+point5Properties = ["x", "y", "z", "u", "v"]
458+
459+-- ========================================================================
460+-- MyRoseTree (custom datatypeNameModifier)
461+-- ========================================================================
462+
463+data MyRoseTree = MyRoseTree
464+ { root :: String
465+ , trees :: [MyRoseTree]
466+ } deriving (Generic)
467+
468+instance ToSchema MyRoseTree where
469+ declareNamedSchema = genericDeclareNamedSchema defaultSchemaOptions
470+ { datatypeNameModifier = drop (length "My") }
471+
472+myRoseTreeSchemaJSON :: Value
473+myRoseTreeSchemaJSON = [aesonQQ|
474+{
475+ "type": "object",
476+ "properties":
477+ {
478+ "root": { "type": "string" },
479+ "trees":
480+ {
481+ "type": "array",
482+ "items":
483+ {
484+ "$ref": "#/definitions/RoseTree"
485+ }
486+ }
487+ },
488+ "required": ["root", "trees"]
489+}
490+|]
491+
492+data MyRoseTree' = MyRoseTree'
493+ { root' :: String
494+ , trees' :: [MyRoseTree']
495+ } deriving (Generic)
496+
497+instance ToSchema MyRoseTree' where
498+ declareNamedSchema = genericDeclareNamedSchema defaultSchemaOptions
499+ { datatypeNameModifier = map toLower }
500+
501+myRoseTreeSchemaJSON' :: Value
502+myRoseTreeSchemaJSON' = [aesonQQ|
503+{
504+ "type": "object",
505+ "properties":
506+ {
507+ "root'": { "type": "string" },
508+ "trees'":
509+ {
510+ "type": "array",
511+ "items":
512+ {
513+ "$ref": "#/definitions/myrosetree'"
514+ }
515+ }
516+ },
517+ "required": ["root'", "trees'"]
518+}
519+|]
520+
521+-- ========================================================================
522+-- Inlined (newtype for inlining schemas)
523+-- ========================================================================
524+
525+newtype Inlined a = Inlined { getInlined :: a }
526+
527+instance ToSchema a => ToSchema (Inlined a) where
528+ declareNamedSchema _ = unname <$> declareNamedSchema (Proxy :: Proxy a)
529+ where
530+ unname (NamedSchema _ s) = NamedSchema Nothing s
531+
532+-- ========================================================================
533+-- Light (sum type with unwrapUnaryRecords)
534+-- ========================================================================
535+
536+data Light
537+ = NoLight
538+ | LightFreq Double
539+ | LightColor Color
540+ | LightWaveLength { waveLength :: Double }
541+ deriving (Generic)
542+
543+instance ToSchema Light where
544+ declareNamedSchema = genericDeclareNamedSchemaUnrestricted defaultSchemaOptions
545+ { unwrapUnaryRecords = True }
546+
547+lightSchemaJSON :: Value
548+lightSchemaJSON = [aesonQQ|
549+{
550+ "type": "object",
551+ "properties":
552+ {
553+ "NoLight": { "type": "array", "items": {}, "maxItems": 0, "example": [] },
554+ "LightFreq": { "type": "number", "format": "double" },
555+ "LightColor": { "$ref": "#/definitions/Color" },
556+ "LightWaveLength": { "type": "number", "format": "double" }
557+ },
558+ "maxProperties": 1,
559+ "minProperties": 1
560+}
561+|]
562+
563+lightInlinedSchemaJSON :: Value
564+lightInlinedSchemaJSON = [aesonQQ|
565+{
566+ "type": "object",
567+ "properties":
568+ {
569+ "NoLight": { "type": "array", "items": {}, "maxItems": 0, "example": [] },
570+ "LightFreq": { "type": "number", "format": "double" },
571+ "LightColor":
572+ {
573+ "type": "string",
574+ "enum": ["Red", "Green", "Blue"]
575+ },
576+ "LightWaveLength": { "type": "number", "format": "double" }
577+ },
578+ "maxProperties": 1,
579+ "minProperties": 1
580+}
581+|]
582+
583+-- ========================================================================
584+-- ResourceId (series of newtypes)
585+-- ========================================================================
586+
587+newtype Id = Id String deriving (Generic)
588+instance ToSchema Id
589+
590+newtype ResourceId = ResourceId Id deriving (Generic)
591+instance ToSchema ResourceId
592+
593+-- ========================================================================
594+-- ButtonImages (bounded enum key mapping)
595+-- ========================================================================
596+
597+data ButtonState = Neutral | Focus | Active | Hover | Disabled
598+ deriving (Show, Bounded, Enum, Generic)
599+
600+instance ToJSON ButtonState
601+instance ToSchema ButtonState
602+instance ToJSONKey ButtonState where toJSONKey = toJSONKeyText (Text.pack . show)
603+
604+type ImageUrl = Text.Text
605+
606+newtype ButtonImages = ButtonImages { getButtonImages :: Map ButtonState ImageUrl }
607+ deriving (Generic)
608+
609+instance ToJSON ButtonImages where
610+ toJSON = toJSON . getButtonImages
611+
612+instance ToSchema ButtonImages where
613+ declareNamedSchema = genericDeclareNamedSchemaNewtype defaultSchemaOptions
614+ declareSchemaBoundedEnumKeyMapping
615+
616+buttonImagesSchemaJSON :: Value
617+buttonImagesSchemaJSON = [aesonQQ|
618+{
619+ "type": "object",
620+ "properties":
621+ {
622+ "Neutral": { "type": "string" },
623+ "Focus": { "type": "string" },
624+ "Active": { "type": "string" },
625+ "Hover": { "type": "string" },
626+ "Disabled": { "type": "string" }
627+ }
628+}
629+|]
630+
631+-- ========================================================================
632+-- SingleMaybeField (single field data with optional field)
633+-- ========================================================================
634+
635+data SingleMaybeField = SingleMaybeField { singleMaybeField :: Maybe String }
636+ deriving (Show, Generic)
637+
638+instance ToJSON SingleMaybeField
639+instance ToSchema SingleMaybeField
640+
641+singleMaybeFieldSchemaJSON :: Value
642+singleMaybeFieldSchemaJSON = [aesonQQ|
643+{
644+ "type": "object",
645+ "properties":
646+ {
647+ "singleMaybeField": { "type": "string" }
648+ }
649+}
650+|]
651+
652+
653+-- ========================================================================
654+-- TimeOfDay
655+-- ========================================================================
656+data TimeOfDay
657+ = Int
658+ | Pico
659+ deriving (Generic)
660+instance ToSchema TimeOfDay
661+instance ToParamSchema TimeOfDay
662+
663+
664+timeOfDaySchemaJSON :: Value
665+timeOfDaySchemaJSON = [aesonQQ|
666+{
667+ "example": "12:33:15",
668+ "type": "string",
669+ "format": "hh:MM:ss"
670+}
671+|]
672+
673+timeOfDayParamSchemaJSON :: Value
674+timeOfDayParamSchemaJSON = [aesonQQ|
675+{
676+ "type": "string",
677+ "format": "hh:MM:ss"
678+}
679+|]
test/Data/Swagger/ParamSchemaSpec.hs+10−84
@@ -1,22 +1,29 @@
1{-# LANGUAGE DeriveGeneric #-}
1{-# LANGUAGE DeriveGeneric #-}
2+{-# LANGUAGE DataKinds #-}
2{-# LANGUAGE ScopedTypeVariables #-}
3{-# LANGUAGE ScopedTypeVariables #-}
3{-# LANGUAGE TemplateHaskell #-}
4{-# LANGUAGE TemplateHaskell #-}
4{-# LANGUAGE QuasiQuotes #-}
5{-# LANGUAGE QuasiQuotes #-}
6+{-# LANGUAGE OverloadedStrings #-}
5module Data.Swagger.ParamSchemaSpec where
7module Data.Swagger.ParamSchemaSpec where
6
8
7import Data.Aeson
9import Data.Aeson
8−import Data.Aeson.QQ
10+import Data.Aeson.QQ.Simple
9import Data.Char
11import Data.Char
10import Data.Proxy
12import Data.Proxy
11import GHC.Generics
13import GHC.Generics
12
14
13import Data.Swagger
15import Data.Swagger
16+import Data.Swagger.Internal (SwaggerKind(..))
14
17
18+import Data.Swagger.CommonTestTypes
15import SpecCommon
19import SpecCommon
16import Test.Hspec
20import Test.Hspec
21+import Data.Time.LocalTime
22+
23+import qualified Data.HashMap.Strict as HM
17
24
18checkToParamSchema :: ToParamSchema a => Proxy a -> Value -> Spec
25checkToParamSchema :: ToParamSchema a => Proxy a -> Value -> Spec
19−checkToParamSchema proxy js = (toParamSchema proxy :: ParamSchema Param) <=> js
26+checkToParamSchema proxy js = (toParamSchema proxy :: ParamSchema ('SwaggerKindNormal Param)) <=> js
20
27
21spec :: Spec
28spec :: Spec
22spec = do
29spec = do
@@ -27,88 +34,7 @@ spec = do
27 context "Unary records" $ do
34 context "Unary records" $ do
28 context "Email (unary record)" $ checkToParamSchema (Proxy :: Proxy Email) emailSchemaJSON
35 context "Email (unary record)" $ checkToParamSchema (Proxy :: Proxy Email) emailSchemaJSON
29 context "UserId (non-record newtype)" $ checkToParamSchema (Proxy :: Proxy UserId) userIdSchemaJSON
36 context "UserId (non-record newtype)" $ checkToParamSchema (Proxy :: Proxy UserId) userIdSchemaJSON
37+ context "TimeOfDay" $ checkToParamSchema (Proxy :: Proxy Data.Time.LocalTime.TimeOfDay) timeOfDayParamSchemaJSON
30
38
31main :: IO ()
39main :: IO ()
32main = hspec spec
40main = hspec spec
33−
34−-- ========================================================================
35−-- Unit type
36−-- ========================================================================
37−
38−data Unit = Unit deriving (Generic)
39−instance ToParamSchema Unit
40−
41−unitSchemaJSON :: Value
42−unitSchemaJSON = [aesonQQ|
43−{
44− "type": "string",
45− "enum": ["Unit"]
46−}
47−|]
48−
49−-- ========================================================================
50−-- Color (enum)
51−-- ========================================================================
52−data Color
53− = Red
54− | Green
55− | Blue
56− deriving (Generic)
57−instance ToParamSchema Color
58−
59−colorSchemaJSON :: Value
60−colorSchemaJSON = [aesonQQ|
61−{
62− "type": "string",
63− "enum": ["Red", "Green", "Blue"]
64−}
65−|]
66−
67−-- ========================================================================
68−-- Status (constructorTagModifier)
69−-- ========================================================================
70−
71−data Status = StatusOk | StatusError deriving (Generic)
72−
73−instance ToParamSchema Status where
74− toParamSchema = genericToParamSchema defaultSchemaOptions
75− { constructorTagModifier = map toLower . drop (length "Status") }
76−
77−statusSchemaJSON :: Value
78−statusSchemaJSON = [aesonQQ|
79−{
80− "type": "string",
81− "enum": ["ok", "error"]
82−}
83−|]
84−
85−-- ========================================================================
86−-- Email (newtype with unwrapUnaryRecords set to True)
87−-- ========================================================================
88−
89−newtype Email = Email { getEmail :: String }
90− deriving (Generic)
91−instance ToParamSchema Email
92−
93−emailSchemaJSON :: Value
94−emailSchemaJSON = [aesonQQ|
95−{
96− "type": "string"
97−}
98−|]
99−
100−-- ========================================================================
101−-- UserId (non-record newtype)
102−-- ========================================================================
103−
104−newtype UserId = UserId Integer
105− deriving (Generic)
106−instance ToParamSchema UserId
107−
108−userIdSchemaJSON :: Value
109−userIdSchemaJSON = [aesonQQ|
110−{
111− "type": "integer"
112−}
113−|]
114−
test/Data/Swagger/Schema/GeneratorSpec.hsnew file+168
@@ -0,0 +1,168 @@
1+{-# LANGUAGE OverloadedLists #-}
2+{-# LANGUAGE OverloadedStrings #-}
3+{-# LANGUAGE PackageImports #-}
4+module Data.Swagger.Schema.GeneratorSpec where
5+
6+import Prelude ()
7+import Prelude.Compat
8+
9+import Data.Swagger
10+import Data.Swagger.Schema.Generator
11+
12+import Control.Lens.Operators
13+import Data.Aeson
14+import Data.Hashable (Hashable)
15+import Data.HashMap.Strict (HashMap)
16+import qualified Data.HashMap.Strict as HashMap
17+import "unordered-containers" Data.HashSet (HashSet)
18+import qualified "unordered-containers" Data.HashSet as HashSet
19+import Data.Int
20+import Data.IntMap (IntMap)
21+import Data.List.NonEmpty.Compat (NonEmpty (..), nonEmpty)
22+import Data.Map (Map, fromList)
23+import Data.Monoid (mempty)
24+import Data.Proxy
25+import Data.Proxy
26+import Data.Set (Set)
27+import qualified Data.Text as T
28+import qualified Data.Text.Lazy as TL
29+import Data.Time
30+import Data.Version (Version)
31+import Data.Word
32+import GHC.Generics
33+
34+import Test.Hspec
35+import Test.Hspec.QuickCheck
36+import Test.QuickCheck
37+
38+shouldValidate :: (FromJSON a, ToSchema a) => Proxy a -> Property
39+shouldValidate = validateFromJSON
40+
41+
42+shouldNotValidate :: (FromJSON a, ToSchema a) => Proxy a -> Property
43+shouldNotValidate = expectFailure . shouldValidate
44+
45+
46+spec :: Spec
47+spec = do
48+ describe "FromJSON validation" $ do
49+ prop "Bool" $ shouldValidate (Proxy :: Proxy Bool)
50+ prop "Char" $ shouldValidate (Proxy :: Proxy Char)
51+ prop "Double" $ shouldValidate (Proxy :: Proxy Double)
52+ prop "Float" $ shouldValidate (Proxy :: Proxy Float)
53+ prop "Int" $ shouldValidate (Proxy :: Proxy Int)
54+ prop "Int8" $ shouldValidate (Proxy :: Proxy Int8)
55+ prop "Int16" $ shouldValidate (Proxy :: Proxy Int16)
56+ prop "Int32" $ shouldValidate (Proxy :: Proxy Int32)
57+ prop "Int64" $ shouldValidate (Proxy :: Proxy Int64)
58+ prop "Integer" $ shouldValidate (Proxy :: Proxy Integer)
59+ prop "Word" $ shouldValidate (Proxy :: Proxy Word)
60+ prop "Word8" $ shouldValidate (Proxy :: Proxy Word8)
61+ prop "Word16" $ shouldValidate (Proxy :: Proxy Word16)
62+ prop "Word32" $ shouldValidate (Proxy :: Proxy Word32)
63+ prop "Word64" $ shouldValidate (Proxy :: Proxy Word64)
64+ prop "String" $ shouldValidate (Proxy :: Proxy String)
65+ prop "()" $ shouldValidate (Proxy :: Proxy ())
66+-- prop "ZonedTime" $ shouldValidate (Proxy :: Proxy ZonedTime)
67+-- prop "UTCTime" $ shouldValidate (Proxy :: Proxy UTCTime)
68+ prop "T.Text" $ shouldValidate (Proxy :: Proxy T.Text)
69+ prop "TL.Text" $ shouldValidate (Proxy :: Proxy TL.Text)
70+ prop "[String]" $ shouldValidate (Proxy :: Proxy [String])
71+ -- prop "(Maybe [Int])" $ shouldValidate (Proxy :: Proxy (Maybe [Int]))
72+ prop "(IntMap String)" $ shouldValidate (Proxy :: Proxy (IntMap String))
73+ prop "(Set Bool)" $ shouldValidate (Proxy :: Proxy (Set Bool))
74+ prop "(NonEmpty Bool)" $ shouldValidate (Proxy :: Proxy (NonEmpty Bool))
75+ prop "(HashSet Bool)" $ shouldValidate (Proxy :: Proxy (HashSet Bool))
76+ prop "(Either Int String)" $ shouldValidate (Proxy :: Proxy (Either Int String))
77+ prop "(Int, String)" $ shouldValidate (Proxy :: Proxy (Int, String))
78+ prop "(Map String Int)" $ shouldValidate (Proxy :: Proxy (Map String Int))
79+ prop "(Map T.Text Int)" $ shouldValidate (Proxy :: Proxy (Map T.Text Int))
80+ prop "(Map TL.Text Bool)" $ shouldValidate (Proxy :: Proxy (Map TL.Text Bool))
81+ prop "(HashMap String Int)" $ shouldValidate (Proxy :: Proxy (HashMap String Int))
82+ prop "(HashMap T.Text Int)" $ shouldValidate (Proxy :: Proxy (HashMap T.Text Int))
83+ prop "(HashMap TL.Text Bool)" $ shouldValidate (Proxy :: Proxy (HashMap TL.Text Bool))
84+ prop "Object" $ shouldValidate (Proxy :: Proxy Object)
85+ prop "(Int, String, Double)" $ shouldValidate (Proxy :: Proxy (Int, String, Double))
86+ prop "(Int, String, Double, [Int])" $ shouldValidate (Proxy :: Proxy (Int, String, Double, [Int]))
87+ prop "(Int, String, Double, [Int], Int)" $ shouldValidate (Proxy :: Proxy (Int, String, Double, [Int], Int))
88+ describe "Invalid FromJSON validation" $ do
89+ prop "WrongType" $ shouldNotValidate (Proxy :: Proxy WrongType)
90+ prop "MissingRequired" $ shouldNotValidate (Proxy :: Proxy MissingRequired)
91+ prop "MissingProperty" $ shouldNotValidate (Proxy :: Proxy MissingProperty)
92+ prop "WrongPropType" $ shouldNotValidate (Proxy :: Proxy WrongPropType)
93+
94+-- =============================
95+-- Data types and bunk instances
96+-- =============================
97+
98+data WrongType = WrongType Bool
99+
100+instance FromJSON WrongType where
101+ parseJSON = withBool "WrongType" $ return . WrongType
102+
103+instance ToSchema WrongType where
104+ declareNamedSchema _ = return . NamedSchema (Just "WrongType") $
105+ mempty
106+ & type_ ?~ SwaggerObject
107+
108+
109+data MissingRequired = MissingRequired
110+ { propA :: String
111+ , propB :: Bool
112+ }
113+
114+instance FromJSON MissingRequired where
115+ parseJSON = withObject "MissingRequired" $ \o ->
116+ MissingRequired
117+ <$> o .: "propA"
118+ <*> o .: "propB"
119+
120+instance ToSchema MissingRequired where
121+ declareNamedSchema _ = do
122+ stringSchema <- declareSchemaRef (Proxy :: Proxy String)
123+ boolSchema <- declareSchemaRef (Proxy :: Proxy Bool)
124+ return . NamedSchema (Just "MissingRequired") $
125+ mempty
126+ & type_ ?~ SwaggerObject
127+ & properties .~ [("propA", stringSchema)
128+ ,("propB", boolSchema)
129+ ]
130+ & required .~ ["propA"]
131+
132+data MissingProperty = MissingProperty
133+ { propC :: String
134+ , propD :: Bool
135+ }
136+
137+instance FromJSON MissingProperty where
138+ parseJSON = withObject "MissingProperty" $ \o ->
139+ MissingProperty
140+ <$> o .: "propC"
141+ <*> o .: "propD"
142+
143+instance ToSchema MissingProperty where
144+ declareNamedSchema _ = do
145+ stringSchema <- declareSchemaRef (Proxy :: Proxy String)
146+ return . NamedSchema (Just "MissingProperty") $
147+ mempty
148+ & type_ ?~ SwaggerObject
149+ & properties .~ [("propC", stringSchema)]
150+ & required .~ ["propC"]
151+
152+data WrongPropType = WrongPropType
153+ { propE :: String
154+ }
155+
156+instance FromJSON WrongPropType where
157+ parseJSON = withObject "WrongPropType" $ \o ->
158+ WrongPropType
159+ <$> o .: "propE"
160+
161+instance ToSchema WrongPropType where
162+ declareNamedSchema _ = do
163+ boolSchema <- declareSchemaRef (Proxy :: Proxy Bool)
164+ return . NamedSchema (Just "WrongPropType") $
165+ mempty
166+ & type_ ?~ SwaggerObject
167+ & properties .~ [("propE", boolSchema)]
168+ & required .~ ["propE"]
test/Data/Swagger/Schema/ValidationSpec.hs+151−70
@@ -1,44 +1,50 @@
1−{-# LANGUAGE CPP #-}
1+{-# LANGUAGE CPP #-}
2−{-# LANGUAGE DeriveAnyClass #-}
3−{-# LANGUAGE DeriveGeneric #-}
2+{-# LANGUAGE DeriveGeneric #-}
4−{-# LANGUAGE PackageImports #-}
3+{-# LANGUAGE PackageImports #-}
4+{-# LANGUAGE RecordWildCards #-}
5+{-# LANGUAGE ScopedTypeVariables #-}
6+{-# OPTIONS_GHC -fno-warn-orphans #-}
5module Data.Swagger.Schema.ValidationSpec where
7module Data.Swagger.Schema.ValidationSpec where
6
8
7−import Control.Applicative
9+import Control.Applicative
10+import Control.Lens ((&), (.~), (?~))
8−import Data.Aeson
11+import Data.Aeson
9−import Data.Aeson.Types
12+import Data.Aeson.Types
10−import Data.Int
13+import Data.Hashable (Hashable)
11−import Data.IntMap (IntMap)
14+import Data.HashMap.Strict (HashMap)
12−import qualified Data.IntMap as IntMap
15+import qualified Data.HashMap.Strict as HashMap
13−import Data.IntSet (IntSet)
14−import Data.Hashable (Hashable)
15−import "unordered-containers" Data.HashSet (HashSet)
16+import "unordered-containers" Data.HashSet (HashSet)
16import qualified "unordered-containers" Data.HashSet as HashSet
17import qualified "unordered-containers" Data.HashSet as HashSet
17−import Data.HashMap.Strict (HashMap)
18+import Data.Int
18−import qualified Data.HashMap.Strict as HashMap
19+import Data.IntMap (IntMap)
20+import Data.List.NonEmpty.Compat (NonEmpty (..), nonEmpty)
19−import Data.Map (Map)
21+import Data.Map (Map, fromList)
20−import qualified Data.Map as Map
22+import Data.Monoid (mempty)
21−import Data.Proxy
23+import Data.Proxy
22−import Data.Time
24+import Data.Set (Set)
23−import qualified Data.Text as T
25+import qualified Data.Text as T
24−import qualified Data.Text.Lazy as TL
26+import qualified Data.Text.Lazy as TL
25−import Data.Set (Set)
27+import Data.Time
26−import qualified Data.Set as Set
28+import Data.Version (Version)
27−import Data.Word
29+import Data.Word
28−import GHC.Generics
30+import GHC.Generics
29−
31+
30−import Data.Swagger
32+import Data.Swagger
31−import Data.Swagger.Declare
33+import Data.Swagger.Declare
32−import Data.Swagger.Schema.Validation
34+
33−
34−import SpecCommon
35−import Test.Hspec
35+import Test.Hspec
36−import Test.Hspec.QuickCheck
36+import Test.Hspec.QuickCheck
37−import Test.QuickCheck
37+import Test.QuickCheck
38+import Test.QuickCheck.Instances ()
38
39
39shouldValidate :: (ToJSON a, ToSchema a) => Proxy a -> a -> Bool
40shouldValidate :: (ToJSON a, ToSchema a) => Proxy a -> a -> Bool
40shouldValidate _ x = validateToJSON x == []
41shouldValidate _ x = validateToJSON x == []
41
42
43+shouldNotValidate :: forall a. ToSchema a => (a -> Value) -> a -> Bool
44+shouldNotValidate f = not . null . validateJSON defs sch . f
45+ where
46+ (defs, sch) = runDeclare (declareSchema (Proxy :: Proxy a)) mempty
47+
42spec :: Spec
48spec :: Spec
43spec = do
49spec = do
44 describe "Validation" $ do
50 describe "Validation" $ do
@@ -67,6 +73,7 @@ spec = do
67 -- prop "(Maybe [Int])" $ shouldValidate (Proxy :: Proxy (Maybe [Int]))
73 -- prop "(Maybe [Int])" $ shouldValidate (Proxy :: Proxy (Maybe [Int]))
68 prop "(IntMap String)" $ shouldValidate (Proxy :: Proxy (IntMap String))
74 prop "(IntMap String)" $ shouldValidate (Proxy :: Proxy (IntMap String))
69 prop "(Set Bool)" $ shouldValidate (Proxy :: Proxy (Set Bool))
75 prop "(Set Bool)" $ shouldValidate (Proxy :: Proxy (Set Bool))
76+ prop "(NonEmpty Bool)" $ shouldValidate (Proxy :: Proxy (NonEmpty Bool))
70 prop "(HashSet Bool)" $ shouldValidate (Proxy :: Proxy (HashSet Bool))
77 prop "(HashSet Bool)" $ shouldValidate (Proxy :: Proxy (HashSet Bool))
71 prop "(Either Int String)" $ shouldValidate (Proxy :: Proxy (Either Int String))
78 prop "(Either Int String)" $ shouldValidate (Proxy :: Proxy (Either Int String))
72 prop "(Int, String)" $ shouldValidate (Proxy :: Proxy (Int, String))
79 prop "(Int, String)" $ shouldValidate (Proxy :: Proxy (Int, String))
@@ -76,6 +83,7 @@ spec = do
76 prop "(HashMap String Int)" $ shouldValidate (Proxy :: Proxy (HashMap String Int))
83 prop "(HashMap String Int)" $ shouldValidate (Proxy :: Proxy (HashMap String Int))
77 prop "(HashMap T.Text Int)" $ shouldValidate (Proxy :: Proxy (HashMap T.Text Int))
84 prop "(HashMap T.Text Int)" $ shouldValidate (Proxy :: Proxy (HashMap T.Text Int))
78 prop "(HashMap TL.Text Bool)" $ shouldValidate (Proxy :: Proxy (HashMap TL.Text Bool))
85 prop "(HashMap TL.Text Bool)" $ shouldValidate (Proxy :: Proxy (HashMap TL.Text Bool))
86+ prop "Object" $ shouldValidate (Proxy :: Proxy Object)
79 prop "(Int, String, Double)" $ shouldValidate (Proxy :: Proxy (Int, String, Double))
87 prop "(Int, String, Double)" $ shouldValidate (Proxy :: Proxy (Int, String, Double))
80 prop "(Int, String, Double, [Int])" $ shouldValidate (Proxy :: Proxy (Int, String, Double, [Int]))
88 prop "(Int, String, Double, [Int])" $ shouldValidate (Proxy :: Proxy (Int, String, Double, [Int]))
81 prop "(Int, String, Double, [Int], Int)" $ shouldValidate (Proxy :: Proxy (Int, String, Double, [Int], Int))
89 prop "(Int, String, Double, [Int], Int)" $ shouldValidate (Proxy :: Proxy (Int, String, Double, [Int], Int))
@@ -84,6 +92,16 @@ spec = do
84 prop "Paint" $ shouldValidate (Proxy :: Proxy Paint)
92 prop "Paint" $ shouldValidate (Proxy :: Proxy Paint)
85 prop "MyRoseTree" $ shouldValidate (Proxy :: Proxy MyRoseTree)
93 prop "MyRoseTree" $ shouldValidate (Proxy :: Proxy MyRoseTree)
86 prop "Light" $ shouldValidate (Proxy :: Proxy Light)
94 prop "Light" $ shouldValidate (Proxy :: Proxy Light)
95+ prop "ButtonImages" $ shouldValidate (Proxy :: Proxy ButtonImages)
96+ prop "Version" $ shouldValidate (Proxy :: Proxy Version)
97+ prop "FreeForm" $ shouldValidate (Proxy :: Proxy FreeForm)
98+
99+ describe "invalid cases" $ do
100+ prop "invalidPersonToJSON" $ shouldNotValidate invalidPersonToJSON
101+ prop "invalidColorToJSON" $ shouldNotValidate invalidColorToJSON
102+ prop "invalidPaintToJSON" $ shouldNotValidate invalidPaintToJSON
103+ prop "invalidLightToJSON" $ shouldNotValidate invalidLightToJSON
104+ prop "invalidButtonImagesToJSON" $ shouldNotValidate invalidButtonImagesToJSON
87
105
88main :: IO ()
106main :: IO ()
89main = hspec spec
107main = hspec spec
@@ -91,29 +109,57 @@ main = hspec spec
91-- ========================================================================
109-- ========================================================================
92-- Person (simple record with optional fields)
110-- Person (simple record with optional fields)
93-- ========================================================================
111-- ========================================================================
94−data Person = Person { name :: String , phone :: Integer , email :: Maybe String } deriving (Show, Generic, ToSchema, ToJSON)
112+data Person = Person
113+ { name :: String
114+ , phone :: Integer
115+ , email :: Maybe String
116+ } deriving (Show, Generic)
117+
118+instance ToJSON Person
119+instance ToSchema Person
95
120
96instance Arbitrary Person where
121instance Arbitrary Person where
97 arbitrary = Person <$> arbitrary <*> arbitrary <*> arbitrary
122 arbitrary = Person <$> arbitrary <*> arbitrary <*> arbitrary
98
123
124+invalidPersonToJSON :: Person -> Value
125+invalidPersonToJSON Person{..} = object
126+ [ T.pack "personName" .= toJSON name
127+ , T.pack "personPhone" .= toJSON phone
128+ , T.pack "personEmail" .= toJSON email
129+ ]
130+
99-- ========================================================================
131-- ========================================================================
100-- Color (enum)
132-- Color (enum)
101-- ========================================================================
133-- ========================================================================
102−data Color = Red | Green | Blue deriving (Show, Generic, ToSchema, ToJSON, Bounded, Enum)
134+data Color = Red | Green | Blue deriving (Show, Generic, Bounded, Enum)
135+
136+instance ToJSON Color
137+instance ToSchema Color
103
138
104instance Arbitrary Color where
139instance Arbitrary Color where
105 arbitrary = arbitraryBoundedEnum
140 arbitrary = arbitraryBoundedEnum
106
141
142+invalidColorToJSON :: Color -> Value
143+invalidColorToJSON Red = toJSON "red"
144+invalidColorToJSON Green = toJSON "green"
145+invalidColorToJSON Blue = toJSON "blue"
146+
107-- ========================================================================
147-- ========================================================================
108-- Paint (record with bounded enum property)
148-- Paint (record with bounded enum property)
109-- ========================================================================
149-- ========================================================================
110
150
111newtype Paint = Paint { color :: Color }
151newtype Paint = Paint { color :: Color }
112− deriving (Show, Generic, ToSchema, ToJSON)
152+ deriving (Show, Generic)
153+
154+instance ToJSON Paint
155+instance ToSchema Paint
113
156
114instance Arbitrary Paint where
157instance Arbitrary Paint where
115 arbitrary = Paint <$> arbitrary
158 arbitrary = Paint <$> arbitrary
116
159
160+invalidPaintToJSON :: Paint -> Value
161+invalidPaintToJSON = toJSON . color
162+
117-- ========================================================================
163-- ========================================================================
118-- MyRoseTree (custom datatypeNameModifier)
164-- MyRoseTree (custom datatypeNameModifier)
119-- ========================================================================
165-- ========================================================================
@@ -121,7 +167,9 @@ instance Arbitrary Paint where
121data MyRoseTree = MyRoseTree
167data MyRoseTree = MyRoseTree
122 { root :: String
168 { root :: String
123 , trees :: [MyRoseTree]
169 , trees :: [MyRoseTree]
124− } deriving (Show, Generic, ToJSON)
170+ } deriving (Show, Generic)
171+
172+instance ToJSON MyRoseTree
125
173
126instance ToSchema MyRoseTree where
174instance ToSchema MyRoseTree where
127 declareNamedSchema = genericDeclareNamedSchema defaultSchemaOptions
175 declareNamedSchema = genericDeclareNamedSchema defaultSchemaOptions
@@ -138,7 +186,10 @@ instance Arbitrary MyRoseTree where
138-- Light (sum type)
186-- Light (sum type)
139-- ========================================================================
187-- ========================================================================
140
188
141−data Light = NoLight | LightFreq Double | LightColor Color deriving (Show, Generic, ToSchema)
189+data Light = NoLight | LightFreq Double | LightColor Color deriving (Show, Generic)
190+
191+instance ToSchema Light where
192+ declareNamedSchema = genericDeclareNamedSchemaUnrestricted defaultSchemaOptions
142
193
143instance ToJSON Light where
194instance ToJSON Light where
144 toJSON = genericToJSON defaultOptions { sumEncoding = ObjectWithSingleField }
195 toJSON = genericToJSON defaultOptions { sumEncoding = ObjectWithSingleField }
@@ -150,48 +201,78 @@ instance Arbitrary Light where
150 , LightColor <$> arbitrary
201 , LightColor <$> arbitrary
151 ]
202 ]
152
203
153−-- Arbitrary instances for common types
204+invalidLightToJSON :: Light -> Value
205+invalidLightToJSON = genericToJSON defaultOptions
154
206
155−#if MIN_VERSION_QuickCheck(2,8,2)
207+-- ========================================================================
156−#else
208+-- ButtonImages (bounded enum key mapping)
157−instance (Ord k, Arbitrary k, Arbitrary v) => Arbitrary (Map k v) where
209+-- ========================================================================
158− arbitrary = Map.fromList <$> arbitrary
159
210
160−instance Arbitrary a => Arbitrary (IntMap a) where
211+data ButtonState = Neutral | Focus | Active | Hover | Disabled
161− arbitrary = IntMap.fromList <$> arbitrary
212+ deriving (Show, Eq, Ord, Bounded, Enum, Generic)
162
213
163−instance (Ord a, Arbitrary a) => Arbitrary (Set a) where
214+instance ToJSON ButtonState
164− arbitrary = Set.fromList <$> arbitrary
215+instance ToSchema ButtonState
165−#endif
216+instance ToJSONKey ButtonState where toJSONKey = toJSONKeyText (T.pack . show)
166
217
167−instance (Eq k, Hashable k, Arbitrary k, Arbitrary v) => Arbitrary (HashMap k v) where
218+instance Arbitrary ButtonState where
168− arbitrary = HashMap.fromList <$> arbitrary
219+ arbitrary = arbitraryBoundedEnum
169
220
170−instance (Eq a, Hashable a, Arbitrary a) => Arbitrary (HashSet a) where
221+type ImageUrl = T.Text
171− arbitrary = HashSet.fromList <$> arbitrary
172
222
173−instance Arbitrary T.Text where
223+newtype ButtonImages = ButtonImages { getButtonImages :: Map ButtonState ImageUrl }
174− arbitrary = T.pack <$> arbitrary
224+ deriving (Show, Generic)
175
225
176−instance Arbitrary TL.Text where
226+instance ToJSON ButtonImages where
177− arbitrary = TL.pack <$> arbitrary
227+ toJSON = toJSON . getButtonImages
178
228
179−instance Arbitrary Day where
229+instance ToSchema ButtonImages where
180− arbitrary = liftA3 fromGregorian (fmap ((+ 1) . abs) arbitrary) arbitrary arbitrary
230+ declareNamedSchema = genericDeclareNamedSchemaNewtype defaultSchemaOptions
231+ declareSchemaBoundedEnumKeyMapping
181
232
233+invalidButtonImagesToJSON :: ButtonImages -> Value
234+invalidButtonImagesToJSON = genericToJSON defaultOptions
235+
182−instance Arbitrary LocalTime where
236+instance Arbitrary ButtonImages where
183− arbitrary = LocalTime
184− <$> arbitrary
237+ arbitrary = ButtonImages <$> arbitrary
185− <*> liftA3 TimeOfDay (choose (0, 23)) (choose (0, 59)) (fromInteger <$> choose (0, 60))
238+
239+-- ========================================================================
240+-- FreeForm (wraps a raw JSON Value)
241+-- ========================================================================
242+
243+data FreeForm = FreeForm { jsonContent :: Map T.Text Value }
244+ deriving (Show, Generic)
245+
246+instance ToJSON FreeForm where
247+ toJSON = toJSON . jsonContent
248+
249+instance ToSchema FreeForm where
250+ declareNamedSchema _ = pure $ NamedSchema (Just $ T.pack "FreeForm") $ mempty
251+ & type_ ?~ SwaggerObject
252+ & additionalProperties ?~ AdditionalPropertiesAllowed True
253+
254+instance Arbitrary FreeForm where
255+ arbitrary = (FreeForm . fromList) <$> genObj
256+ where
257+ genObj = listOf $ do
258+ k <- arbitrary
259+ v <- oneof [ String <$> arbitrary, Number <$> arbitrary, Bool <$> arbitrary, pure Null ]
260+ pure (k, v)
186
261
187instance Eq ZonedTime where
262instance Eq ZonedTime where
188 ZonedTime t (TimeZone x _ _) == ZonedTime t' (TimeZone y _ _) = t == t' && x == y
263 ZonedTime t (TimeZone x _ _) == ZonedTime t' (TimeZone y _ _) = t == t' && x == y
189
264
190−instance Arbitrary ZonedTime where
265+-- ========================================================================
191− arbitrary = ZonedTime
266+-- Arbitrary instance for Data.Aeson.Value
192− <$> arbitrary
267+-- ========================================================================
193− <*> liftA3 TimeZone arbitrary arbitrary (vectorOf 3 (elements ['A'..'Z']))
194−
195−instance Arbitrary UTCTime where
196− arbitrary = UTCTime <$> arbitrary <*> fmap fromInteger (choose (0, 86400))
197
268
269+instance Arbitrary Value where
270+ -- Weights are almost random
271+ -- Uniform oneof tends not to build complex objects cause of recursive call.
272+ arbitrary = resize 4 $ frequency
273+ [ (3, Object <$> arbitrary)
274+ , (3, Array <$> arbitrary)
275+ , (3, String <$> arbitrary)
276+ , (3, Number <$> arbitrary)
277+ , (3, Bool <$> arbitrary)
278+ , (1, return Null) ]
test/Data/Swagger/SchemaSpec.hs+25−513
@@ -7,22 +7,23 @@ module Data.Swagger.SchemaSpec where
7import Prelude ()
7import Prelude ()
8import Prelude.Compat
8import Prelude.Compat
9
9
10−import Data.Aeson
10+import Control.Lens ((^.))
11−import Data.Aeson.QQ
12−import Data.Char
11+import Data.Aeson (Value)
13−import qualified Data.HashMap.Strict as HashMap
12+import qualified Data.HashMap.Strict.InsOrd as InsOrdHashMap
14import Data.Proxy
13import Data.Proxy
15import Data.Set (Set)
14import Data.Set (Set)
16−import qualified Data.Set as Set
17import qualified Data.Text as Text
15import qualified Data.Text as Text
18−import GHC.Generics
19
16
20import Data.Swagger
17import Data.Swagger
21import Data.Swagger.Declare
18import Data.Swagger.Declare
22
19
20+import Data.Swagger.CommonTestTypes
23import SpecCommon
21import SpecCommon
24import Test.Hspec
22import Test.Hspec
25
23
24+import qualified Data.HashMap.Strict as HM
25+import Data.Time.LocalTime
26+
26checkToSchema :: ToSchema a => Proxy a -> Value -> Spec
27checkToSchema :: ToSchema a => Proxy a -> Value -> Spec
27checkToSchema proxy js = toSchema proxy <=> js
28checkToSchema proxy js = toSchema proxy <=> js
28
29
@@ -34,10 +35,17 @@ checkSchemaName sname proxy =
34checkDefs :: ToSchema a => Proxy a -> [String] -> Spec
35checkDefs :: ToSchema a => Proxy a -> [String] -> Spec
35checkDefs proxy names =
36checkDefs proxy names =
36 it ("uses these definitions " ++ show names) $
37 it ("uses these definitions " ++ show names) $
37− Set.fromList (HashMap.keys defs) `shouldBe` Set.fromList (map Text.pack names)
38+ InsOrdHashMap.keys defs `shouldBe` map Text.pack names
38 where
39 where
39 defs = execDeclare (declareNamedSchema proxy) mempty
40 defs = execDeclare (declareNamedSchema proxy) mempty
40
41
42+checkProperties :: ToSchema a => Proxy a -> [String] -> Spec
43+checkProperties proxy names =
44+ it ("has these fields in order " ++ show names) $
45+ InsOrdHashMap.keys fields `shouldBe` map Text.pack names
46+ where
47+ fields = toSchema proxy ^. properties
48+
41checkInlinedSchema :: ToSchema a => Proxy a -> Value -> Spec
49checkInlinedSchema :: ToSchema a => Proxy a -> Value -> Spec
42checkInlinedSchema proxy js = toInlinedSchema proxy <=> js
50checkInlinedSchema proxy js = toInlinedSchema proxy <=> js
43
51
@@ -58,6 +66,9 @@ spec = do
58 context "Person" $ checkToSchema (Proxy :: Proxy Person) personSchemaJSON
66 context "Person" $ checkToSchema (Proxy :: Proxy Person) personSchemaJSON
59 context "ISPair" $ checkToSchema (Proxy :: Proxy ISPair) ispairSchemaJSON
67 context "ISPair" $ checkToSchema (Proxy :: Proxy ISPair) ispairSchemaJSON
60 context "Point (fieldLabelModifier)" $ checkToSchema (Proxy :: Proxy Point) pointSchemaJSON
68 context "Point (fieldLabelModifier)" $ checkToSchema (Proxy :: Proxy Point) pointSchemaJSON
69+ context "Point5 (many field record)" $ do
70+ checkToSchema (Proxy :: Proxy Point5) point5SchemaJSON
71+ checkProperties (Proxy :: Proxy Point5) point5Properties
61 context "Color (bounded enum)" $ checkToSchema (Proxy :: Proxy Color) colorSchemaJSON
72 context "Color (bounded enum)" $ checkToSchema (Proxy :: Proxy Color) colorSchemaJSON
62 context "Shade (paramSchemaToNamedSchema)" $ checkToSchema (Proxy :: Proxy Shade) shadeSchemaJSON
73 context "Shade (paramSchemaToNamedSchema)" $ checkToSchema (Proxy :: Proxy Shade) shadeSchemaJSON
63 context "Paint (record with bounded enum field)" $ checkToSchema (Proxy :: Proxy Paint) paintSchemaJSON
74 context "Paint (record with bounded enum field)" $ checkToSchema (Proxy :: Proxy Paint) paintSchemaJSON
@@ -66,8 +77,10 @@ spec = do
66 context "Email (unwrapUnaryRecords)" $ checkToSchema (Proxy :: Proxy Email) emailSchemaJSON
77 context "Email (unwrapUnaryRecords)" $ checkToSchema (Proxy :: Proxy Email) emailSchemaJSON
67 context "UserId (non-record newtype)" $ checkToSchema (Proxy :: Proxy UserId) userIdSchemaJSON
78 context "UserId (non-record newtype)" $ checkToSchema (Proxy :: Proxy UserId) userIdSchemaJSON
68 context "Player (unary record)" $ checkToSchema (Proxy :: Proxy Player) playerSchemaJSON
79 context "Player (unary record)" $ checkToSchema (Proxy :: Proxy Player) playerSchemaJSON
80+ context "SingleMaybeField (unary record with Maybe)" $ checkToSchema (Proxy :: Proxy SingleMaybeField) singleMaybeFieldSchemaJSON
69 context "Players (inlining schema)" $ checkToSchema (Proxy :: Proxy Players) playersSchemaJSON
81 context "Players (inlining schema)" $ checkToSchema (Proxy :: Proxy Players) playersSchemaJSON
70 context "MyRoseTree (datatypeNameModifier)" $ checkToSchema (Proxy :: Proxy MyRoseTree) myRoseTreeSchemaJSON
82 context "MyRoseTree (datatypeNameModifier)" $ checkToSchema (Proxy :: Proxy MyRoseTree) myRoseTreeSchemaJSON
83+ context "MyRoseTree' (datatypeNameModifier)" $ checkToSchema (Proxy :: Proxy MyRoseTree') myRoseTreeSchemaJSON'
71 context "Sum types" $ do
84 context "Sum types" $ do
72 context "Status (sum of unary constructors)" $ checkToSchema (Proxy :: Proxy Status) statusSchemaJSON
85 context "Status (sum of unary constructors)" $ checkToSchema (Proxy :: Proxy Status) statusSchemaJSON
73 context "Character (ref and record sum)" $ checkToSchema (Proxy :: Proxy Character) characterSchemaJSON
86 context "Character (ref and record sum)" $ checkToSchema (Proxy :: Proxy Character) characterSchemaJSON
@@ -83,6 +96,7 @@ spec = do
83 context "Light" $ checkDefs (Proxy :: Proxy Light) ["Color"]
96 context "Light" $ checkDefs (Proxy :: Proxy Light) ["Color"]
84 context "Character" $ checkDefs (Proxy :: Proxy Character) ["Player", "Point"]
97 context "Character" $ checkDefs (Proxy :: Proxy Character) ["Player", "Point"]
85 context "MyRoseTree" $ checkDefs (Proxy :: Proxy MyRoseTree) ["RoseTree"]
98 context "MyRoseTree" $ checkDefs (Proxy :: Proxy MyRoseTree) ["RoseTree"]
99+ context "MyRoseTree'" $ checkDefs (Proxy :: Proxy MyRoseTree') ["myrosetree'"]
86 context "[Set (Unit, Maybe Color)]" $ checkDefs (Proxy :: Proxy [Set (Unit, Maybe Color)]) ["Unit", "Color"]
100 context "[Set (Unit, Maybe Color)]" $ checkDefs (Proxy :: Proxy [Set (Unit, Maybe Color)]) ["Unit", "Color"]
87 context "ResourceId" $ checkDefs (Proxy :: Proxy ResourceId) []
101 context "ResourceId" $ checkDefs (Proxy :: Proxy ResourceId) []
88 describe "Inlining Schemas" $ do
102 describe "Inlining Schemas" $ do
@@ -91,512 +105,10 @@ spec = do
91 context "Character (inlining only Player)" $ checkInlinedSchemas ["Player"] (Proxy :: Proxy Character) characterInlinedPlayerSchemaJSON
105 context "Character (inlining only Player)" $ checkInlinedSchemas ["Player"] (Proxy :: Proxy Character) characterInlinedPlayerSchemaJSON
92 context "Light" $ checkInlinedSchema (Proxy :: Proxy Light) lightInlinedSchemaJSON
106 context "Light" $ checkInlinedSchema (Proxy :: Proxy Light) lightInlinedSchemaJSON
93 context "MyRoseTree (inlineNonRecursiveSchemas)" $ checkInlinedRecSchema (Proxy :: Proxy MyRoseTree) myRoseTreeSchemaJSON
107 context "MyRoseTree (inlineNonRecursiveSchemas)" $ checkInlinedRecSchema (Proxy :: Proxy MyRoseTree) myRoseTreeSchemaJSON
108+ context "MyRoseTree' (inlineNonRecursiveSchemas)" $ checkInlinedRecSchema (Proxy :: Proxy MyRoseTree') myRoseTreeSchemaJSON'
109+ describe "Bounded Enum key mapping" $ do
110+ context "ButtonImages" $ checkToSchema (Proxy :: Proxy ButtonImages) buttonImagesSchemaJSON
111+ context "TimeOfDay" $ checkToSchema (Proxy :: Proxy Data.Time.LocalTime.TimeOfDay) timeOfDaySchemaJSON
94
112
95main :: IO ()
113main :: IO ()
96main = hspec spec
114main = hspec spec
97−
98−-- ========================================================================
99−-- Person (simple record with optional fields)
100−-- ========================================================================
101−data Person = Person
102− { name :: String
103− , phone :: Integer
104− , email :: Maybe String
105− } deriving (Generic)
106−
107−instance ToSchema Person
108−
109−personSchemaJSON :: Value
110−personSchemaJSON = [aesonQQ|
111−{
112− "type": "object",
113− "properties":
114− {
115− "name": { "type": "string" },
116− "phone": { "type": "integer" },
117− "email": { "type": "string" }
118− },
119− "required": ["name", "phone"]
120−}
121−|]
122−
123−-- ========================================================================
124−-- ISPair (non-record product data type)
125−-- ========================================================================
126−data ISPair = ISPair Integer String
127− deriving (Generic)
128−
129−instance ToSchema ISPair
130−
131−ispairSchemaJSON :: Value
132−ispairSchemaJSON = [aesonQQ|
133−{
134− "type": "array",
135− "items":
136− [
137− { "type": "integer" },
138− { "type": "string" }
139− ]
140−}
141−|]
142−
143−-- ========================================================================
144−-- Point (record data type with custom fieldLabelModifier)
145−-- ========================================================================
146−data Point = Point
147− { pointX :: Double
148− , pointY :: Double
149− } deriving (Generic)
150−
151−instance ToSchema Point where
152− declareNamedSchema = genericDeclareNamedSchema defaultSchemaOptions
153− { fieldLabelModifier = map toLower . drop (length "point") }
154−
155−pointSchemaJSON :: Value
156−pointSchemaJSON = [aesonQQ|
157−{
158− "type": "object",
159− "properties":
160− {
161− "x": { "type": "number", "format": "double" },
162− "y": { "type": "number", "format": "double" }
163− },
164− "required": ["x", "y"]
165−}
166−|]
167−
168−
169−-- ========================================================================
170−-- Color (enum)
171−-- ========================================================================
172−data Color
173− = Red
174− | Green
175− | Blue
176− deriving (Generic)
177−instance ToSchema Color
178−
179−colorSchemaJSON :: Value
180−colorSchemaJSON = [aesonQQ|
181−{
182− "type": "string",
183− "enum": ["Red", "Green", "Blue"]
184−}
185−|]
186−
187−-- ========================================================================
188−-- Shade (paramSchemaToNamedSchema)
189−-- ========================================================================
190−
191−data Shade = Dim | Bright deriving (Generic)
192−instance ToParamSchema Shade
193−
194−instance ToSchema Shade where declareNamedSchema = pure . paramSchemaToNamedSchema defaultSchemaOptions
195−
196−shadeSchemaJSON :: Value
197−shadeSchemaJSON = [aesonQQ|
198−{
199− "type": "string",
200− "enum": ["Dim", "Bright"]
201−}
202−|]
203−
204−-- ========================================================================
205−-- Paint (record with bounded enum property)
206−-- ========================================================================
207−
208−newtype Paint = Paint { color :: Color }
209− deriving (Generic)
210−instance ToSchema Paint
211−
212−paintSchemaJSON :: Value
213−paintSchemaJSON = [aesonQQ|
214−{
215− "type": "object",
216− "properties":
217− {
218− "color":
219− {
220− "$ref": "#/definitions/Color"
221− }
222− },
223− "required": ["color"]
224−}
225−|]
226−
227−paintInlinedSchemaJSON :: Value
228−paintInlinedSchemaJSON = [aesonQQ|
229−{
230− "type": "object",
231− "properties":
232− {
233− "color":
234− {
235− "type": "string",
236− "enum": ["Red", "Green", "Blue"]
237− }
238− },
239− "required": ["color"]
240−}
241−|]
242−
243−-- ========================================================================
244−-- Email (newtype with unwrapUnaryRecords set to True)
245−-- ========================================================================
246−
247−newtype Email = Email { getEmail :: String }
248− deriving (Generic)
249−
250−instance ToSchema Email where
251− declareNamedSchema = genericDeclareNamedSchema defaultSchemaOptions
252− { unwrapUnaryRecords = True }
253−
254−emailSchemaJSON :: Value
255−emailSchemaJSON = [aesonQQ|
256−{
257− "type": "string"
258−}
259−|]
260−
261−-- ========================================================================
262−-- UserId (non-record newtype)
263−-- ========================================================================
264−
265−newtype UserId = UserId Integer
266− deriving (Eq, Ord, Generic)
267−instance ToSchema UserId
268−
269−userIdSchemaJSON :: Value
270−userIdSchemaJSON = [aesonQQ|
271−{
272− "type": "integer"
273−}
274−|]
275−
276−-- ========================================================================
277−-- UserGroup (set newtype)
278−-- ========================================================================
279−
280−newtype UserGroup = UserGroup (Set UserId)
281− deriving (Generic)
282−instance ToSchema UserGroup
283−
284−userGroupSchemaJSON :: Value
285−userGroupSchemaJSON = [aesonQQ|
286−{
287− "type": "array",
288− "items": { "$ref": "#/definitions/UserId" },
289− "uniqueItems": true
290−}
291−|]
292−
293−-- ========================================================================
294−-- Player (record newtype)
295−-- ========================================================================
296−
297−newtype Player = Player
298− { position :: Point
299− } deriving (Generic)
300−instance ToSchema Player
301−
302−playerSchemaJSON :: Value
303−playerSchemaJSON = [aesonQQ|
304−{
305− "type": "object",
306− "properties":
307− {
308− "position":
309− {
310− "$ref": "#/definitions/Point"
311− }
312− },
313− "required": ["position"]
314−}
315−|]
316−
317−-- ========================================================================
318−-- MyRoseTree (custom datatypeNameModifier)
319−-- ========================================================================
320−
321−data MyRoseTree = MyRoseTree
322− { root :: String
323− , trees :: [MyRoseTree]
324− } deriving (Generic)
325−
326−instance ToSchema MyRoseTree where
327− declareNamedSchema = genericDeclareNamedSchema defaultSchemaOptions
328− { datatypeNameModifier = drop (length "My") }
329−
330−myRoseTreeSchemaJSON :: Value
331−myRoseTreeSchemaJSON = [aesonQQ|
332−{
333− "type": "object",
334− "properties":
335− {
336− "root": { "type": "string" },
337− "trees":
338− {
339− "type": "array",
340− "items":
341− {
342− "$ref": "#/definitions/RoseTree"
343− }
344− }
345− },
346− "required": ["root", "trees"]
347−}
348−|]
349−
350−-- ========================================================================
351−-- Inlined (newtype for inlining schemas)
352−-- ========================================================================
353−
354−newtype Inlined a = Inlined { getInlined :: a }
355−
356−instance ToSchema a => ToSchema (Inlined a) where
357− declareNamedSchema _ = unname <$> declareNamedSchema (Proxy :: Proxy a)
358− where
359− unname (NamedSchema _ s) = NamedSchema Nothing s
360−
361−newtype Players = Players [Inlined Player]
362− deriving (Generic)
363−instance ToSchema Players
364−
365−playersSchemaJSON :: Value
366−playersSchemaJSON = [aesonQQ|
367−{
368− "type": "array",
369− "items":
370− {
371− "type": "object",
372− "properties":
373− {
374− "position":
375− {
376− "$ref": "#/definitions/Point"
377− }
378− },
379− "required": ["position"]
380− }
381−}
382−|]
383−
384−-- ========================================================================
385−-- Status (sum type with unary constructors)
386−-- ========================================================================
387−
388−data Status
389− = StatusOk String
390− | StatusError String
391− deriving (Generic)
392−
393−instance ToSchema Status where
394− declareNamedSchema = genericDeclareNamedSchema defaultSchemaOptions
395− { constructorTagModifier = map toLower . drop (length "Status") }
396−
397−statusSchemaJSON :: Value
398−statusSchemaJSON = [aesonQQ|
399−{
400− "type": "object",
401− "properties":
402− {
403− "ok": { "type": "string" },
404− "error": { "type": "string" }
405− },
406− "maxProperties": 1,
407− "minProperties": 1
408−}
409−|]
410−
411−-- ========================================================================
412−-- Unit type
413−-- ========================================================================
414−
415−data Unit = Unit deriving (Generic)
416−instance ToSchema Unit
417−
418−unitSchemaJSON :: Value
419−unitSchemaJSON = [aesonQQ|
420−{
421− "type": "string",
422− "enum": ["Unit"]
423−}
424−|]
425−
426−
427−-- ========================================================================
428−-- Character (sum type with ref and record in alternative)
429−-- ========================================================================
430−
431−data Character
432− = PC Player
433− | NPC { npcName :: String, npcPosition :: Point }
434− deriving (Generic)
435−instance ToSchema Character
436−
437−characterSchemaJSON :: Value
438−characterSchemaJSON = [aesonQQ|
439−{
440− "type": "object",
441− "properties":
442− {
443− "PC": { "$ref": "#/definitions/Player" },
444− "NPC":
445− {
446− "type": "object",
447− "properties":
448− {
449− "npcName": { "type": "string" },
450− "npcPosition": { "$ref": "#/definitions/Point" }
451− },
452− "required": ["npcName", "npcPosition"]
453− }
454− },
455− "maxProperties": 1,
456− "minProperties": 1
457−}
458−|]
459−
460−characterInlinedSchemaJSON :: Value
461−characterInlinedSchemaJSON = [aesonQQ|
462−{
463− "type": "object",
464− "properties":
465− {
466− "PC":
467− {
468− "type": "object",
469− "properties":
470− {
471− "position":
472− {
473− "type": "object",
474− "properties":
475− {
476− "x": { "type": "number", "format": "double" },
477− "y": { "type": "number", "format": "double" }
478− },
479− "required": ["x", "y"]
480− }
481− },
482− "required": ["position"]
483− },
484− "NPC":
485− {
486− "type": "object",
487− "properties":
488− {
489− "npcName": { "type": "string" },
490− "npcPosition":
491− {
492− "type": "object",
493− "properties":
494− {
495− "x": { "type": "number", "format": "double" },
496− "y": { "type": "number", "format": "double" }
497− },
498− "required": ["x", "y"]
499− }
500− },
501− "required": ["npcName", "npcPosition"]
502− }
503− },
504− "maxProperties": 1,
505− "minProperties": 1
506−}
507−|]
508−
509−characterInlinedPlayerSchemaJSON :: Value
510−characterInlinedPlayerSchemaJSON = [aesonQQ|
511−{
512− "type": "object",
513− "properties":
514− {
515− "PC":
516− {
517− "type": "object",
518− "properties":
519− {
520− "position":
521− {
522− "$ref": "#/definitions/Point"
523− }
524− },
525− "required": ["position"]
526− },
527− "NPC":
528− {
529− "type": "object",
530− "properties":
531− {
532− "npcName": { "type": "string" },
533− "npcPosition": { "$ref": "#/definitions/Point" }
534− },
535− "required": ["npcName", "npcPosition"]
536− }
537− },
538− "maxProperties": 1,
539− "minProperties": 1
540−}
541−|]
542−
543−-- ========================================================================
544−-- Light (sum type with unwrapUnaryRecords)
545−-- ========================================================================
546−
547−data Light
548− = NoLight
549− | LightFreq Double
550− | LightColor Color
551− | LightWaveLength { waveLength :: Double }
552− deriving (Generic)
553−
554−instance ToSchema Light where
555− declareNamedSchema = genericDeclareNamedSchema defaultSchemaOptions
556− { unwrapUnaryRecords = True }
557−
558−lightSchemaJSON :: Value
559−lightSchemaJSON = [aesonQQ|
560−{
561− "type": "object",
562− "properties":
563− {
564− "NoLight": { "type": "array", "items": [] },
565− "LightFreq": { "type": "number", "format": "double" },
566− "LightColor": { "$ref": "#/definitions/Color" },
567− "LightWaveLength": { "type": "number", "format": "double" }
568− },
569− "maxProperties": 1,
570− "minProperties": 1
571−}
572−|]
573−
574−lightInlinedSchemaJSON :: Value
575−lightInlinedSchemaJSON = [aesonQQ|
576−{
577− "type": "object",
578− "properties":
579− {
580− "NoLight": { "type": "array", "items": [] },
581− "LightFreq": { "type": "number", "format": "double" },
582− "LightColor":
583− {
584− "type": "string",
585− "enum": ["Red", "Green", "Blue"]
586− },
587− "LightWaveLength": { "type": "number", "format": "double" }
588− },
589− "maxProperties": 1,
590− "minProperties": 1
591−}
592−|]
593−
594−-- ========================================================================
595−-- ResourceId (series of newtypes)
596−-- ========================================================================
597−
598−newtype Id = Id String deriving (Generic)
599−instance ToSchema Id
600−
601−newtype ResourceId = ResourceId Id deriving (Generic)
602−instance ToSchema ResourceId
test/Data/SwaggerSpec.hs+426−330
@@ -10,8 +10,9 @@ import Prelude.Compat
10import Control.Lens
10import Control.Lens
11
11
12import Data.Aeson
12import Data.Aeson
13−import Data.Aeson.QQ
13+import Data.Aeson.QQ.Simple
14import Data.HashMap.Strict (HashMap)
14import Data.HashMap.Strict (HashMap)
15+import qualified Data.HashSet.InsOrd as InsOrdHS
15import Data.Text (Text)
16import Data.Text (Text)
16
17
17import Data.Swagger
18import Data.Swagger
@@ -20,6 +21,14 @@ import Test.Hspec hiding (example)
20
21
21spec :: Spec
22spec :: Spec
22spec = do
23spec = do
24+ describe "host" $ do
25+ it "can decode the host port" $ do
26+ let h = Just $ Host "localhost" (Just (fromInteger 8000))
27+ swagger :: Swagger
28+ swagger = swaggerExample
29+ & host .~ h
30+ parsed :: Swagger = either error id $ eitherDecode' $ encode swagger
31+ parsed ^. host `shouldBe` h
23 describe "License Object" $ licenseExample <=> licenseExampleJSON
32 describe "License Object" $ licenseExample <=> licenseExampleJSON
24 describe "Contact Object" $ contactExample <=> contactExampleJSON
33 describe "Contact Object" $ contactExample <=> contactExampleJSON
25 describe "Info Object" $ infoExample <=> infoExampleJSON
34 describe "Info Object" $ infoExample <=> infoExampleJSON
@@ -28,11 +37,14 @@ spec = do
28 context "Primitive Sample" $ schemaPrimitiveExample <=> schemaPrimitiveExampleJSON
37 context "Primitive Sample" $ schemaPrimitiveExample <=> schemaPrimitiveExampleJSON
29 context "Simple Model" $ schemaSimpleModelExample <=> schemaSimpleModelExampleJSON
38 context "Simple Model" $ schemaSimpleModelExample <=> schemaSimpleModelExampleJSON
30 context "Model with Map/Dictionary Properties" $ schemaModelDictExample <=> schemaModelDictExampleJSON
39 context "Model with Map/Dictionary Properties" $ schemaModelDictExample <=> schemaModelDictExampleJSON
40+ context "Model with Arbitrary Properties" $ schemaAdditionalExample <=> schemaAdditionalExampleJSON
31 context "Model with Example" $ schemaWithExampleExample <=> schemaWithExampleExampleJSON
41 context "Model with Example" $ schemaWithExampleExample <=> schemaWithExampleExampleJSON
32 describe "Definitions Object" $ definitionsExample <=> definitionsExampleJSON
42 describe "Definitions Object" $ definitionsExample <=> definitionsExampleJSON
33 describe "Parameters Definition Object" $ paramsDefinitionExample <=> paramsDefinitionExampleJSON
43 describe "Parameters Definition Object" $ paramsDefinitionExample <=> paramsDefinitionExampleJSON
34 describe "Responses Definition Object" $ responsesDefinitionExample <=> responsesDefinitionExampleJSON
44 describe "Responses Definition Object" $ responsesDefinitionExample <=> responsesDefinitionExampleJSON
35 describe "Security Definitions Object" $ securityDefinitionsExample <=> securityDefinitionsExampleJSON
45 describe "Security Definitions Object" $ securityDefinitionsExample <=> securityDefinitionsExampleJSON
46+ describe "OAuth2 Security Definitions with merged Scope" $ oAuth2SecurityDefinitionsExample <=> oAuth2SecurityDefinitionsExampleJSON
47+ describe "Composition Schema Example" $ compositionSchemaExample <=> compositionSchemaExampleJSON
36 describe "Swagger Object" $ do
48 describe "Swagger Object" $ do
37 context "Todo Example" $ swaggerExample <=> swaggerExampleJSON
49 context "Todo Example" $ swaggerExample <=> swaggerExampleJSON
38 context "PetStore Example" $
50 context "PetStore Example" $
@@ -98,7 +110,8 @@ contactExampleJSON = [aesonQQ|
98-- =======================================================================
110-- =======================================================================
99
111
100licenseExample :: License
112licenseExample :: License
113+licenseExample = "Apache 2.0"
101−licenseExample = License "Apache 2.0" (Just (URL "http://www.apache.org/licenses/LICENSE-2.0.html"))
114+ & url ?~ URL "http://www.apache.org/licenses/LICENSE-2.0.html"
102
115
103licenseExampleJSON :: Value
116licenseExampleJSON :: Value
104licenseExampleJSON = [aesonQQ|
117licenseExampleJSON = [aesonQQ|
@@ -115,7 +128,7 @@ licenseExampleJSON = [aesonQQ|
115
128
116operationExample :: Operation
129operationExample :: Operation
117operationExample = mempty
130operationExample = mempty
118− & tags .~ ["pet"]
131+ & tags .~ InsOrdHS.fromList ["pet"]
119 & summary ?~ "Updates a pet in the store with form data"
132 & summary ?~ "Updates a pet in the store with form data"
120 & description ?~ ""
133 & description ?~ ""
121 & operationId ?~ "updatePetWithForm"
134 & operationId ?~ "updatePetWithForm"
@@ -139,15 +152,14 @@ operationExample = mempty
139 & schema .~ ParamOther (stringSchema ParamFormData)
152 & schema .~ ParamOther (stringSchema ParamFormData)
140 ]
153 ]
141
154
142− & responses .~ (mempty & responses .~
143− [ (200, Inline (mempty & description .~ "Pet updated."))
155+ & at 200 ?~ "Pet updated."
144− , (405, Inline (mempty & description .~ "Invalid input")) ])
156+ & at 405 ?~ "Invalid input"
145 & security .~ [SecurityRequirement [("petstore_auth", ["write:pets", "read:pets"])]]
157 & security .~ [SecurityRequirement [("petstore_auth", ["write:pets", "read:pets"])]]
146 where
158 where
147 stringSchema :: ParamLocation -> ParamOtherSchema
159 stringSchema :: ParamLocation -> ParamOtherSchema
148 stringSchema loc = mempty
160 stringSchema loc = mempty
149 & in_ .~ loc
161 & in_ .~ loc
150− & type_ .~ SwaggerString
162+ & type_ ?~ SwaggerString
151
163
152operationExampleJSON :: Value
164operationExampleJSON :: Value
153operationExampleJSON = [aesonQQ|
165operationExampleJSON = [aesonQQ|
@@ -213,7 +225,7 @@ operationExampleJSON = [aesonQQ|
213
225
214schemaPrimitiveExample :: Schema
226schemaPrimitiveExample :: Schema
215schemaPrimitiveExample = mempty
227schemaPrimitiveExample = mempty
216− & type_ .~ SwaggerString
228+ & type_ ?~ SwaggerString
217 & format ?~ "email"
229 & format ?~ "email"
218
230
219schemaPrimitiveExampleJSON :: Value
231schemaPrimitiveExampleJSON :: Value
@@ -226,14 +238,14 @@ schemaPrimitiveExampleJSON = [aesonQQ|
226
238
227schemaSimpleModelExample :: Schema
239schemaSimpleModelExample :: Schema
228schemaSimpleModelExample = mempty
240schemaSimpleModelExample = mempty
229− & type_ .~ SwaggerObject
241+ & type_ ?~ SwaggerObject
230 & required .~ [ "name" ]
242 & required .~ [ "name" ]
231 & properties .~
243 & properties .~
232− [ ("name", Inline (mempty & type_ .~ SwaggerString))
244+ [ ("name", Inline (mempty & type_ ?~ SwaggerString))
233 , ("address", Ref (Reference "Address"))
245 , ("address", Ref (Reference "Address"))
234 , ("age", Inline $ mempty
246 , ("age", Inline $ mempty
235 & minimum_ ?~ 0
247 & minimum_ ?~ 0
236− & type_ .~ SwaggerInteger
248+ & type_ ?~ SwaggerInteger
237 & format ?~ "int32" ) ]
249 & format ?~ "int32" ) ]
238
250
239schemaSimpleModelExampleJSON :: Value
251schemaSimpleModelExampleJSON :: Value
@@ -261,8 +273,8 @@ schemaSimpleModelExampleJSON = [aesonQQ|
261
273
262schemaModelDictExample :: Schema
274schemaModelDictExample :: Schema
263schemaModelDictExample = mempty
275schemaModelDictExample = mempty
264− & type_ .~ SwaggerObject
276+ & type_ ?~ SwaggerObject
265− & additionalProperties ?~ (mempty & type_ .~ SwaggerString)
277+ & additionalProperties ?~ AdditionalPropertiesSchema (Inline (mempty & type_ ?~ SwaggerString))
266
278
267schemaModelDictExampleJSON :: Value
279schemaModelDictExampleJSON :: Value
268schemaModelDictExampleJSON = [aesonQQ|
280schemaModelDictExampleJSON = [aesonQQ|
@@ -274,15 +286,28 @@ schemaModelDictExampleJSON = [aesonQQ|
274}
286}
275|]
287|]
276
288
289+schemaAdditionalExample :: Schema
290+schemaAdditionalExample = mempty
291+ & type_ ?~ SwaggerObject
292+ & additionalProperties ?~ AdditionalPropertiesAllowed True
293+
294+schemaAdditionalExampleJSON :: Value
295+schemaAdditionalExampleJSON = [aesonQQ|
296+{
297+ "type": "object",
298+ "additionalProperties": true
299+}
300+|]
301+
277schemaWithExampleExample :: Schema
302schemaWithExampleExample :: Schema
278schemaWithExampleExample = mempty
303schemaWithExampleExample = mempty
279− & type_ .~ SwaggerObject
304+ & type_ ?~ SwaggerObject
280 & properties .~
305 & properties .~
281 [ ("id", Inline $ mempty
306 [ ("id", Inline $ mempty
282− & type_ .~ SwaggerInteger
307+ & type_ ?~ SwaggerInteger
283 & format ?~ "int64" )
308 & format ?~ "int64" )
284 , ("name", Inline $ mempty
309 , ("name", Inline $ mempty
285− & type_ .~ SwaggerString) ]
310+ & type_ ?~ SwaggerString) ]
286 & required .~ [ "name" ]
311 & required .~ [ "name" ]
287 & example ?~ [aesonQQ|
312 & example ?~ [aesonQQ|
288 {
313 {
@@ -321,19 +346,19 @@ schemaWithExampleExampleJSON = [aesonQQ|
321definitionsExample :: HashMap Text Schema
346definitionsExample :: HashMap Text Schema
322definitionsExample =
347definitionsExample =
323 [ ("Category", mempty
348 [ ("Category", mempty
324− & type_ .~ SwaggerObject
349+ & type_ ?~ SwaggerObject
325 & properties .~
350 & properties .~
326 [ ("id", Inline $ mempty
351 [ ("id", Inline $ mempty
327− & type_ .~ SwaggerInteger
352+ & type_ ?~ SwaggerInteger
328 & format ?~ "int64")
353 & format ?~ "int64")
329− , ("name", Inline (mempty & type_ .~ SwaggerString)) ] )
354+ , ("name", Inline (mempty & type_ ?~ SwaggerString)) ] )
330 , ("Tag", mempty
355 , ("Tag", mempty
331− & type_ .~ SwaggerObject
356+ & type_ ?~ SwaggerObject
332 & properties .~
357 & properties .~
333 [ ("id", Inline $ mempty
358 [ ("id", Inline $ mempty
334− & type_ .~ SwaggerInteger
359+ & type_ ?~ SwaggerInteger
335 & format ?~ "int64")
360 & format ?~ "int64")
336− , ("name", Inline (mempty & type_ .~ SwaggerString)) ] ) ]
361+ , ("name", Inline (mempty & type_ ?~ SwaggerString)) ] ) ]
337
362
338definitionsExampleJSON :: Value
363definitionsExampleJSON :: Value
339definitionsExampleJSON = [aesonQQ|
364definitionsExampleJSON = [aesonQQ|
@@ -377,7 +402,7 @@ paramsDefinitionExample =
377 & required ?~ True
402 & required ?~ True
378 & schema .~ ParamOther (mempty
403 & schema .~ ParamOther (mempty
379 & in_ .~ ParamQuery
404 & in_ .~ ParamQuery
380− & type_ .~ SwaggerInteger
405+ & type_ ?~ SwaggerInteger
381 & format ?~ "int32" ))
406 & format ?~ "int32" ))
382 , ("limitParam", mempty
407 , ("limitParam", mempty
383 & name .~ "limit"
408 & name .~ "limit"
@@ -385,7 +410,7 @@ paramsDefinitionExample =
385 & required ?~ True
410 & required ?~ True
386 & schema .~ ParamOther (mempty
411 & schema .~ ParamOther (mempty
387 & in_ .~ ParamQuery
412 & in_ .~ ParamQuery
388− & type_ .~ SwaggerInteger
413+ & type_ ?~ SwaggerInteger
389 & format ?~ "int32" )) ]
414 & format ?~ "int32" )) ]
390
415
391paramsDefinitionExampleJSON :: Value
416paramsDefinitionExampleJSON :: Value
@@ -435,8 +460,8 @@ responsesDefinitionExampleJSON = [aesonQQ|
435-- Responses Definition object
460-- Responses Definition object
436-- =======================================================================
461-- =======================================================================
437
462
438−securityDefinitionsExample :: HashMap Text SecurityScheme
463+securityDefinitionsExample :: SecurityDefinitions
439−securityDefinitionsExample =
464+securityDefinitionsExample = SecurityDefinitions
440 [ ("api_key", SecurityScheme
465 [ ("api_key", SecurityScheme
441 { _securitySchemeType = SecuritySchemeApiKey (ApiKeyParams "api_key" ApiKeyHeader)
466 { _securitySchemeType = SecuritySchemeApiKey (ApiKeyParams "api_key" ApiKeyHeader)
442 , _securitySchemeDescription = Nothing })
467 , _securitySchemeDescription = Nothing })
@@ -468,6 +493,46 @@ securityDefinitionsExampleJSON = [aesonQQ|
468}
493}
469|]
494|]
470
495
496+oAuth2SecurityDefinitionsReadExample :: SecurityDefinitions
497+oAuth2SecurityDefinitionsReadExample = SecurityDefinitions
498+ [ ("petstore_auth", SecurityScheme
499+ { _securitySchemeType = SecuritySchemeOAuth2 (OAuth2Params
500+ { _oauth2Flow = OAuth2Implicit "http://swagger.io/api/oauth/dialog"
501+ , _oauth2Scopes =
502+ [ ("read:pets", "read your pets") ] } )
503+ , _securitySchemeDescription = Nothing })
504+ ]
505+
506+oAuth2SecurityDefinitionsWriteExample :: SecurityDefinitions
507+oAuth2SecurityDefinitionsWriteExample = SecurityDefinitions
508+ [ ("petstore_auth", SecurityScheme
509+ { _securitySchemeType = SecuritySchemeOAuth2 (OAuth2Params
510+ { _oauth2Flow = OAuth2Implicit "http://swagger.io/api/oauth/dialog"
511+ , _oauth2Scopes =
512+ [ ("write:pets", "modify pets in your account") ] } )
513+ , _securitySchemeDescription = Nothing })
514+ ]
515+
516+oAuth2SecurityDefinitionsExample :: SecurityDefinitions
517+oAuth2SecurityDefinitionsExample =
518+ oAuth2SecurityDefinitionsWriteExample <>
519+ oAuth2SecurityDefinitionsReadExample
520+
521+oAuth2SecurityDefinitionsExampleJSON :: Value
522+oAuth2SecurityDefinitionsExampleJSON = [aesonQQ|
523+{
524+ "petstore_auth": {
525+ "type": "oauth2",
526+ "authorizationUrl": "http://swagger.io/api/oauth/dialog",
527+ "flow": "implicit",
528+ "scopes": {
529+ "write:pets": "modify pets in your account",
530+ "read:pets": "read your pets"
531+ }
532+ }
533+}
534+|]
535+
471-- =======================================================================
536-- =======================================================================
472-- Swagger object
537-- Swagger object
473-- =======================================================================
538-- =======================================================================
@@ -479,24 +544,25 @@ swaggerExample = mempty
479 & info .~ (mempty
544 & info .~ (mempty
480 & version .~ "1.0"
545 & version .~ "1.0"
481 & title .~ "Todo API"
546 & title .~ "Todo API"
482− & license ?~ License "MIT" (Just (URL "http://mit.com"))
547+ & license ?~ "MIT"
548+ & license._Just.url ?~ URL "http://mit.com"
483 & description ?~ "This is a an API that tests servant-swagger support for a Todo API")
549 & description ?~ "This is a an API that tests servant-swagger support for a Todo API")
484 & paths.at "/todo/{id}" ?~ (mempty & get ?~ ((mempty :: Operation)
550 & paths.at "/todo/{id}" ?~ (mempty & get ?~ ((mempty :: Operation)
485 & at 200 ?~ Inline (mempty
551 & at 200 ?~ Inline (mempty
486 & description .~ "OK"
552 & description .~ "OK"
487 & schema ?~ Inline (mempty
553 & schema ?~ Inline (mempty
488− & type_ .~ SwaggerObject
554+ & type_ ?~ SwaggerObject
489 & example ?~ [aesonQQ|
555 & example ?~ [aesonQQ|
490 {
556 {
491 "created": 100,
557 "created": 100,
492 "description": "get milk"
558 "description": "get milk"
493 } |]
559 } |]
494− & description ?~ "This is some real Todo right here"
560+ & description ?~ "This is some real Todo right here"
495 & properties .~
561 & properties .~
496 [ ("created", Inline $ mempty
562 [ ("created", Inline $ mempty
497− & type_ .~ SwaggerInteger
563+ & type_ ?~ SwaggerInteger
498 & format ?~ "int32")
564 & format ?~ "int32")
499− , ("description", Inline (mempty & type_ .~ SwaggerString))]))
565+ , ("description", Inline (mempty & type_ ?~ SwaggerString))]))
500 & produces ?~ MimeList [ "application/json" ]
566 & produces ?~ MimeList [ "application/json" ]
501 & parameters .~
567 & parameters .~
502 [ Inline $ mempty
568 [ Inline $ mempty
@@ -505,8 +571,8 @@ swaggerExample = mempty
505 & description ?~ "TodoId param"
571 & description ?~ "TodoId param"
506 & schema .~ ParamOther (mempty
572 & schema .~ ParamOther (mempty
507 & in_ .~ ParamPath
573 & in_ .~ ParamPath
508− & type_ .~ SwaggerString ) ]
574+ & type_ ?~ SwaggerString ) ]
509− & tags .~ [ "todo" ] ))
575+ & tags .~ InsOrdHS.fromList [ "todo" ] ))
510
576
511swaggerExampleJSON :: Value
577swaggerExampleJSON :: Value
512swaggerExampleJSON = [aesonQQ|
578swaggerExampleJSON = [aesonQQ|
@@ -573,130 +639,130 @@ swaggerExampleJSON = [aesonQQ|
573
639
574petstoreExampleJSON :: Value
640petstoreExampleJSON :: Value
575petstoreExampleJSON = [aesonQQ|
641petstoreExampleJSON = [aesonQQ|
576−{
642+{
577 "swagger":"2.0",
643 "swagger":"2.0",
578− "info":{
644+ "info":{
579 "description":"This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.",
645 "description":"This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.",
580 "version":"1.0.0",
646 "version":"1.0.0",
581 "title":"Swagger Petstore",
647 "title":"Swagger Petstore",
582 "termsOfService":"http://swagger.io/terms/",
648 "termsOfService":"http://swagger.io/terms/",
583− "contact":{
649+ "contact":{
584 "email":"apiteam@swagger.io"
650 "email":"apiteam@swagger.io"
585 },
651 },
586− "license":{
652+ "license":{
587 "name":"Apache 2.0",
653 "name":"Apache 2.0",
588 "url":"http://www.apache.org/licenses/LICENSE-2.0.html"
654 "url":"http://www.apache.org/licenses/LICENSE-2.0.html"
589 }
655 }
590 },
656 },
591 "host":"petstore.swagger.io",
657 "host":"petstore.swagger.io",
592 "basePath":"/v2",
658 "basePath":"/v2",
593− "tags":[
659+ "tags":[
594− {
660+ {
595 "name":"pet",
661 "name":"pet",
596 "description":"Everything about your Pets",
662 "description":"Everything about your Pets",
597− "externalDocs":{
663+ "externalDocs":{
598 "description":"Find out more",
664 "description":"Find out more",
599 "url":"http://swagger.io"
665 "url":"http://swagger.io"
600 }
666 }
601 },
667 },
602− {
668+ {
603 "name":"store",
669 "name":"store",
604 "description":"Access to Petstore orders"
670 "description":"Access to Petstore orders"
605 },
671 },
606− {
672+ {
607 "name":"user",
673 "name":"user",
608 "description":"Operations about user",
674 "description":"Operations about user",
609− "externalDocs":{
675+ "externalDocs":{
610 "description":"Find out more about our store",
676 "description":"Find out more about our store",
611 "url":"http://swagger.io"
677 "url":"http://swagger.io"
612 }
678 }
613 }
679 }
614 ],
680 ],
615− "schemes":[
681+ "schemes":[
616 "http"
682 "http"
617 ],
683 ],
618− "paths":{
684+ "paths":{
619− "/pet":{
685+ "/pet":{
620− "post":{
686+ "post":{
621− "tags":[
687+ "tags":[
622 "pet"
688 "pet"
623 ],
689 ],
624 "summary":"Add a new pet to the store",
690 "summary":"Add a new pet to the store",
625 "description":"",
691 "description":"",
626 "operationId":"addPet",
692 "operationId":"addPet",
627− "consumes":[
693+ "consumes":[
628 "application/json",
694 "application/json",
629 "application/xml"
695 "application/xml"
630 ],
696 ],
631− "produces":[
697+ "produces":[
632 "application/xml",
698 "application/xml",
633 "application/json"
699 "application/json"
634 ],
700 ],
635− "parameters":[
701+ "parameters":[
636− {
702+ {
637 "in":"body",
703 "in":"body",
638 "name":"body",
704 "name":"body",
639 "description":"Pet object that needs to be added to the store",
705 "description":"Pet object that needs to be added to the store",
640 "required":true,
706 "required":true,
641− "schema":{
707+ "schema":{
642 "$ref":"#/definitions/Pet"
708 "$ref":"#/definitions/Pet"
643 }
709 }
644 }
710 }
645 ],
711 ],
646− "responses":{
712+ "responses":{
647− "405":{
713+ "405":{
648 "description":"Invalid input"
714 "description":"Invalid input"
649 }
715 }
650 },
716 },
651− "security":[
717+ "security":[
652− {
718+ {
653− "petstore_auth":[
719+ "petstore_auth":[
654 "write:pets",
720 "write:pets",
655 "read:pets"
721 "read:pets"
656 ]
722 ]
657 }
723 }
658 ]
724 ]
659 },
725 },
660− "put":{
726+ "put":{
661− "tags":[
727+ "tags":[
662 "pet"
728 "pet"
663 ],
729 ],
664 "summary":"Update an existing pet",
730 "summary":"Update an existing pet",
665 "description":"",
731 "description":"",
666 "operationId":"updatePet",
732 "operationId":"updatePet",
667− "consumes":[
733+ "consumes":[
668 "application/json",
734 "application/json",
669 "application/xml"
735 "application/xml"
670 ],
736 ],
671− "produces":[
737+ "produces":[
672 "application/xml",
738 "application/xml",
673 "application/json"
739 "application/json"
674 ],
740 ],
675− "parameters":[
741+ "parameters":[
676− {
742+ {
677 "in":"body",
743 "in":"body",
678 "name":"body",
744 "name":"body",
679 "description":"Pet object that needs to be added to the store",
745 "description":"Pet object that needs to be added to the store",
680 "required":true,
746 "required":true,
681− "schema":{
747+ "schema":{
682 "$ref":"#/definitions/Pet"
748 "$ref":"#/definitions/Pet"
683 }
749 }
684 }
750 }
685 ],
751 ],
686− "responses":{
752+ "responses":{
687− "400":{
753+ "400":{
688 "description":"Invalid ID supplied"
754 "description":"Invalid ID supplied"
689 },
755 },
690− "404":{
756+ "404":{
691 "description":"Pet not found"
757 "description":"Pet not found"
692 },
758 },
693− "405":{
759+ "405":{
694 "description":"Validation exception"
760 "description":"Validation exception"
695 }
761 }
696 },
762 },
697− "security":[
763+ "security":[
698− {
764+ {
699− "petstore_auth":[
765+ "petstore_auth":[
700 "write:pets",
766 "write:pets",
701 "read:pets"
767 "read:pets"
702 ]
768 ]
@@ -704,28 +770,28 @@ petstoreExampleJSON = [aesonQQ|
704 ]
770 ]
705 }
771 }
706 },
772 },
707− "/pet/findByStatus":{
773+ "/pet/findByStatus":{
708− "get":{
774+ "get":{
709− "tags":[
775+ "tags":[
710 "pet"
776 "pet"
711 ],
777 ],
712 "summary":"Finds Pets by status",
778 "summary":"Finds Pets by status",
713 "description":"Multiple status values can be provided with comma seperated strings",
779 "description":"Multiple status values can be provided with comma seperated strings",
714 "operationId":"findPetsByStatus",
780 "operationId":"findPetsByStatus",
715− "produces":[
781+ "produces":[
716 "application/xml",
782 "application/xml",
717 "application/json"
783 "application/json"
718 ],
784 ],
719− "parameters":[
785+ "parameters":[
720− {
786+ {
721 "name":"status",
787 "name":"status",
722 "in":"query",
788 "in":"query",
723 "description":"Status values that need to be considered for filter",
789 "description":"Status values that need to be considered for filter",
724 "required":true,
790 "required":true,
725 "type":"array",
791 "type":"array",
726− "items":{
792+ "items":{
727 "type":"string",
793 "type":"string",
728− "enum":[
794+ "enum":[
729 "available",
795 "available",
730 "pending",
796 "pending",
731 "sold"
797 "sold"
@@ -735,23 +801,23 @@ petstoreExampleJSON = [aesonQQ|
735 "collectionFormat":"csv"
801 "collectionFormat":"csv"
736 }
802 }
737 ],
803 ],
738− "responses":{
804+ "responses":{
739− "200":{
805+ "200":{
740 "description":"successful operation",
806 "description":"successful operation",
741− "schema":{
807+ "schema":{
742 "type":"array",
808 "type":"array",
743− "items":{
809+ "items":{
744 "$ref":"#/definitions/Pet"
810 "$ref":"#/definitions/Pet"
745 }
811 }
746 }
812 }
747 },
813 },
748− "400":{
814+ "400":{
749 "description":"Invalid status value"
815 "description":"Invalid status value"
750 }
816 }
751 },
817 },
752− "security":[
818+ "security":[
753− {
819+ {
754− "petstore_auth":[
820+ "petstore_auth":[
755 "write:pets",
821 "write:pets",
756 "read:pets"
822 "read:pets"
757 ]
823 ]
@@ -759,48 +825,48 @@ petstoreExampleJSON = [aesonQQ|
759 ]
825 ]
760 }
826 }
761 },
827 },
762− "/pet/findByTags":{
828+ "/pet/findByTags":{
763− "get":{
829+ "get":{
764− "tags":[
830+ "tags":[
765 "pet"
831 "pet"
766 ],
832 ],
767 "summary":"Finds Pets by tags",
833 "summary":"Finds Pets by tags",
768 "description":"Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.",
834 "description":"Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.",
769 "operationId":"findPetsByTags",
835 "operationId":"findPetsByTags",
770− "produces":[
836+ "produces":[
771 "application/xml",
837 "application/xml",
772 "application/json"
838 "application/json"
773 ],
839 ],
774− "parameters":[
840+ "parameters":[
775− {
841+ {
776 "name":"tags",
842 "name":"tags",
777 "in":"query",
843 "in":"query",
778 "description":"Tags to filter by",
844 "description":"Tags to filter by",
779 "required":true,
845 "required":true,
780 "type":"array",
846 "type":"array",
781− "items":{
847+ "items":{
782 "type":"string"
848 "type":"string"
783 },
849 },
784 "collectionFormat":"csv"
850 "collectionFormat":"csv"
785 }
851 }
786 ],
852 ],
787− "responses":{
853+ "responses":{
788− "200":{
854+ "200":{
789 "description":"successful operation",
855 "description":"successful operation",
790− "schema":{
856+ "schema":{
791 "type":"array",
857 "type":"array",
792− "items":{
858+ "items":{
793 "$ref":"#/definitions/Pet"
859 "$ref":"#/definitions/Pet"
794 }
860 }
795 }
861 }
796 },
862 },
797− "400":{
863+ "400":{
798 "description":"Invalid tag value"
864 "description":"Invalid tag value"
799 }
865 }
800 },
866 },
801− "security":[
867+ "security":[
802− {
868+ {
803− "petstore_auth":[
869+ "petstore_auth":[
804 "write:pets",
870 "write:pets",
805 "read:pets"
871 "read:pets"
806 ]
872 ]
@@ -808,20 +874,20 @@ petstoreExampleJSON = [aesonQQ|
808 ]
874 ]
809 }
875 }
810 },
876 },
811− "/pet/{petId}":{
877+ "/pet/{petId}":{
812− "get":{
878+ "get":{
813− "tags":[
879+ "tags":[
814 "pet"
880 "pet"
815 ],
881 ],
816 "summary":"Find pet by ID",
882 "summary":"Find pet by ID",
817 "description":"Returns a single pet",
883 "description":"Returns a single pet",
818 "operationId":"getPetById",
884 "operationId":"getPetById",
819− "produces":[
885+ "produces":[
820 "application/xml",
886 "application/xml",
821 "application/json"
887 "application/json"
822 ],
888 ],
823− "parameters":[
889+ "parameters":[
824− {
890+ {
825 "name":"petId",
891 "name":"petId",
826 "in":"path",
892 "in":"path",
827 "description":"ID of pet to return",
893 "description":"ID of pet to return",
@@ -830,42 +896,42 @@ petstoreExampleJSON = [aesonQQ|
830 "format":"int64"
896 "format":"int64"
831 }
897 }
832 ],
898 ],
833− "responses":{
899+ "responses":{
834− "200":{
900+ "200":{
835 "description":"successful operation",
901 "description":"successful operation",
836− "schema":{
902+ "schema":{
837 "$ref":"#/definitions/Pet"
903 "$ref":"#/definitions/Pet"
838 }
904 }
839 },
905 },
840− "400":{
906+ "400":{
841 "description":"Invalid ID supplied"
907 "description":"Invalid ID supplied"
842 },
908 },
843− "404":{
909+ "404":{
844 "description":"Pet not found"
910 "description":"Pet not found"
845 }
911 }
846 },
912 },
847− "security":[
913+ "security":[
848− {
914+ {
849 "api_key": []
915 "api_key": []
850 }
916 }
851 ]
917 ]
852 },
918 },
853− "post":{
919+ "post":{
854− "tags":[
920+ "tags":[
855 "pet"
921 "pet"
856 ],
922 ],
857 "summary":"Updates a pet in the store with form data",
923 "summary":"Updates a pet in the store with form data",
858 "description":"",
924 "description":"",
859 "operationId":"updatePetWithForm",
925 "operationId":"updatePetWithForm",
860− "consumes":[
926+ "consumes":[
861 "application/x-www-form-urlencoded"
927 "application/x-www-form-urlencoded"
862 ],
928 ],
863− "produces":[
929+ "produces":[
864 "application/xml",
930 "application/xml",
865 "application/json"
931 "application/json"
866 ],
932 ],
867− "parameters":[
933+ "parameters":[
868− {
934+ {
869 "name":"petId",
935 "name":"petId",
870 "in":"path",
936 "in":"path",
871 "description":"ID of pet that needs to be updated",
937 "description":"ID of pet that needs to be updated",
@@ -873,14 +939,14 @@ petstoreExampleJSON = [aesonQQ|
873 "type":"integer",
939 "type":"integer",
874 "format":"int64"
940 "format":"int64"
875 },
941 },
876− {
942+ {
877 "name":"name",
943 "name":"name",
878 "in":"formData",
944 "in":"formData",
879 "description":"Updated name of the pet",
945 "description":"Updated name of the pet",
880 "required":false,
946 "required":false,
881 "type":"string"
947 "type":"string"
882 },
948 },
883− {
949+ {
884 "name":"status",
950 "name":"status",
885 "in":"formData",
951 "in":"formData",
886 "description":"Updated status of the pet",
952 "description":"Updated status of the pet",
@@ -888,39 +954,39 @@ petstoreExampleJSON = [aesonQQ|
888 "type":"string"
954 "type":"string"
889 }
955 }
890 ],
956 ],
891− "responses":{
957+ "responses":{
892− "405":{
958+ "405":{
893 "description":"Invalid input"
959 "description":"Invalid input"
894 }
960 }
895 },
961 },
896− "security":[
962+ "security":[
897− {
963+ {
898− "petstore_auth":[
964+ "petstore_auth":[
899 "write:pets",
965 "write:pets",
900 "read:pets"
966 "read:pets"
901 ]
967 ]
902 }
968 }
903 ]
969 ]
904 },
970 },
905− "delete":{
971+ "delete":{
906− "tags":[
972+ "tags":[
907 "pet"
973 "pet"
908 ],
974 ],
909 "summary":"Deletes a pet",
975 "summary":"Deletes a pet",
910 "description":"",
976 "description":"",
911 "operationId":"deletePet",
977 "operationId":"deletePet",
912− "produces":[
978+ "produces":[
913 "application/xml",
979 "application/xml",
914 "application/json"
980 "application/json"
915 ],
981 ],
916− "parameters":[
982+ "parameters":[
917− {
983+ {
918 "name":"api_key",
984 "name":"api_key",
919 "in":"header",
985 "in":"header",
920 "required":false,
986 "required":false,
921 "type":"string"
987 "type":"string"
922 },
988 },
923− {
989+ {
924 "name":"petId",
990 "name":"petId",
925 "in":"path",
991 "in":"path",
926 "description":"Pet id to delete",
992 "description":"Pet id to delete",
@@ -929,14 +995,14 @@ petstoreExampleJSON = [aesonQQ|
929 "format":"int64"
995 "format":"int64"
930 }
996 }
931 ],
997 ],
932− "responses":{
998+ "responses":{
933− "400":{
999+ "400":{
934 "description":"Invalid pet value"
1000 "description":"Invalid pet value"
935 }
1001 }
936 },
1002 },
937− "security":[
1003+ "security":[
938− {
1004+ {
939− "petstore_auth":[
1005+ "petstore_auth":[
940 "write:pets",
1006 "write:pets",
941 "read:pets"
1007 "read:pets"
942 ]
1008 ]
@@ -944,22 +1010,22 @@ petstoreExampleJSON = [aesonQQ|
944 ]
1010 ]
945 }
1011 }
946 },
1012 },
947− "/pet/{petId}/uploadImage":{
1013+ "/pet/{petId}/uploadImage":{
948− "post":{
1014+ "post":{
949− "tags":[
1015+ "tags":[
950 "pet"
1016 "pet"
951 ],
1017 ],
952 "summary":"uploads an image",
1018 "summary":"uploads an image",
953 "description":"",
1019 "description":"",
954 "operationId":"uploadFile",
1020 "operationId":"uploadFile",
955− "consumes":[
1021+ "consumes":[
956 "multipart/form-data"
1022 "multipart/form-data"
957 ],
1023 ],
958− "produces":[
1024+ "produces":[
959 "application/json"
1025 "application/json"
960 ],
1026 ],
961− "parameters":[
1027+ "parameters":[
962− {
1028+ {
963 "name":"petId",
1029 "name":"petId",
964 "in":"path",
1030 "in":"path",
965 "description":"ID of pet to update",
1031 "description":"ID of pet to update",
@@ -967,14 +1033,14 @@ petstoreExampleJSON = [aesonQQ|
967 "type":"integer",
1033 "type":"integer",
968 "format":"int64"
1034 "format":"int64"
969 },
1035 },
970− {
1036+ {
971 "name":"additionalMetadata",
1037 "name":"additionalMetadata",
972 "in":"formData",
1038 "in":"formData",
973 "description":"Additional data to pass to server",
1039 "description":"Additional data to pass to server",
974 "required":false,
1040 "required":false,
975 "type":"string"
1041 "type":"string"
976 },
1042 },
977− {
1043+ {
978 "name":"file",
1044 "name":"file",
979 "in":"formData",
1045 "in":"formData",
980 "description":"file to upload",
1046 "description":"file to upload",
@@ -982,17 +1048,17 @@ petstoreExampleJSON = [aesonQQ|
982 "type":"file"
1048 "type":"file"
983 }
1049 }
984 ],
1050 ],
985− "responses":{
1051+ "responses":{
986− "200":{
1052+ "200":{
987 "description":"successful operation",
1053 "description":"successful operation",
988− "schema":{
1054+ "schema":{
989 "$ref":"#/definitions/ApiResponse"
1055 "$ref":"#/definitions/ApiResponse"
990 }
1056 }
991 }
1057 }
992 },
1058 },
993− "security":[
1059+ "security":[
994− {
1060+ {
995− "petstore_auth":[
1061+ "petstore_auth":[
996 "write:pets",
1062 "write:pets",
997 "read:pets"
1063 "read:pets"
998 ]
1064 ]
@@ -1000,87 +1066,87 @@ petstoreExampleJSON = [aesonQQ|
1000 ]
1066 ]
1001 }
1067 }
1002 },
1068 },
1003− "/store/inventory":{
1069+ "/store/inventory":{
1004− "get":{
1070+ "get":{
1005− "tags":[
1071+ "tags":[
1006 "store"
1072 "store"
1007 ],
1073 ],
1008 "summary":"Returns pet inventories by status",
1074 "summary":"Returns pet inventories by status",
1009 "description":"Returns a map of status codes to quantities",
1075 "description":"Returns a map of status codes to quantities",
1010 "operationId":"getInventory",
1076 "operationId":"getInventory",
1011− "produces":[
1077+ "produces":[
1012 "application/json"
1078 "application/json"
1013 ],
1079 ],
1014 "parameters": [],
1080 "parameters": [],
1015− "responses":{
1081+ "responses":{
1016− "200":{
1082+ "200":{
1017 "description":"successful operation",
1083 "description":"successful operation",
1018− "schema":{
1084+ "schema":{
1019 "type":"object",
1085 "type":"object",
1020− "additionalProperties":{
1086+ "additionalProperties":{
1021 "type":"integer",
1087 "type":"integer",
1022 "format":"int32"
1088 "format":"int32"
1023 }
1089 }
1024 }
1090 }
1025 }
1091 }
1026 },
1092 },
1027− "security":[
1093+ "security":[
1028− {
1094+ {
1029 "api_key": []
1095 "api_key": []
1030 }
1096 }
1031 ]
1097 ]
1032 }
1098 }
1033 },
1099 },
1034− "/store/order":{
1100+ "/store/order":{
1035− "post":{
1101+ "post":{
1036− "tags":[
1102+ "tags":[
1037 "store"
1103 "store"
1038 ],
1104 ],
1039 "summary":"Place an order for a pet",
1105 "summary":"Place an order for a pet",
1040 "description":"",
1106 "description":"",
1041 "operationId":"placeOrder",
1107 "operationId":"placeOrder",
1042− "produces":[
1108+ "produces":[
1043 "application/xml",
1109 "application/xml",
1044 "application/json"
1110 "application/json"
1045 ],
1111 ],
1046− "parameters":[
1112+ "parameters":[
1047− {
1113+ {
1048 "in":"body",
1114 "in":"body",
1049 "name":"body",
1115 "name":"body",
1050 "description":"order placed for purchasing the pet",
1116 "description":"order placed for purchasing the pet",
1051 "required":true,
1117 "required":true,
1052− "schema":{
1118+ "schema":{
1053 "$ref":"#/definitions/Order"
1119 "$ref":"#/definitions/Order"
1054 }
1120 }
1055 }
1121 }
1056 ],
1122 ],
1057− "responses":{
1123+ "responses":{
1058− "200":{
1124+ "200":{
1059 "description":"successful operation",
1125 "description":"successful operation",
1060− "schema":{
1126+ "schema":{
1061 "$ref":"#/definitions/Order"
1127 "$ref":"#/definitions/Order"
1062 }
1128 }
1063 },
1129 },
1064− "400":{
1130+ "400":{
1065 "description":"Invalid Order"
1131 "description":"Invalid Order"
1066 }
1132 }
1067 }
1133 }
1068 }
1134 }
1069 },
1135 },
1070− "/store/order/{orderId}":{
1136+ "/store/order/{orderId}":{
1071− "get":{
1137+ "get":{
1072− "tags":[
1138+ "tags":[
1073 "store"
1139 "store"
1074 ],
1140 ],
1075 "summary":"Find purchase order by ID",
1141 "summary":"Find purchase order by ID",
1076 "description":"For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions",
1142 "description":"For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions",
1077 "operationId":"getOrderById",
1143 "operationId":"getOrderById",
1078− "produces":[
1144+ "produces":[
1079 "application/xml",
1145 "application/xml",
1080 "application/json"
1146 "application/json"
1081 ],
1147 ],
1082− "parameters":[
1148+ "parameters":[
1083− {
1149+ {
1084 "name":"orderId",
1150 "name":"orderId",
1085 "in":"path",
1151 "in":"path",
1086 "description":"ID of pet that needs to be fetched",
1152 "description":"ID of pet that needs to be fetched",
@@ -1091,34 +1157,34 @@ petstoreExampleJSON = [aesonQQ|
1091 "format":"int64"
1157 "format":"int64"
1092 }
1158 }
1093 ],
1159 ],
1094− "responses":{
1160+ "responses":{
1095− "200":{
1161+ "200":{
1096 "description":"successful operation",
1162 "description":"successful operation",
1097− "schema":{
1163+ "schema":{
1098 "$ref":"#/definitions/Order"
1164 "$ref":"#/definitions/Order"
1099 }
1165 }
1100 },
1166 },
1101− "400":{
1167+ "400":{
1102 "description":"Invalid ID supplied"
1168 "description":"Invalid ID supplied"
1103 },
1169 },
1104− "404":{
1170+ "404":{
1105 "description":"Order not found"
1171 "description":"Order not found"
1106 }
1172 }
1107 }
1173 }
1108 },
1174 },
1109− "delete":{
1175+ "delete":{
1110− "tags":[
1176+ "tags":[
1111 "store"
1177 "store"
1112 ],
1178 ],
1113 "summary":"Delete purchase order by ID",
1179 "summary":"Delete purchase order by ID",
1114 "description":"For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors",
1180 "description":"For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors",
1115 "operationId":"deleteOrder",
1181 "operationId":"deleteOrder",
1116− "produces":[
1182+ "produces":[
1117 "application/xml",
1183 "application/xml",
1118 "application/json"
1184 "application/json"
1119 ],
1185 ],
1120− "parameters":[
1186+ "parameters":[
1121− {
1187+ {
1122 "name":"orderId",
1188 "name":"orderId",
1123 "in":"path",
1189 "in":"path",
1124 "description":"ID of the order that needs to be deleted",
1190 "description":"ID of the order that needs to be deleted",
@@ -1127,133 +1193,133 @@ petstoreExampleJSON = [aesonQQ|
1127 "minimum":1.0
1193 "minimum":1.0
1128 }
1194 }
1129 ],
1195 ],
1130− "responses":{
1196+ "responses":{
1131− "400":{
1197+ "400":{
1132 "description":"Invalid ID supplied"
1198 "description":"Invalid ID supplied"
1133 },
1199 },
1134− "404":{
1200+ "404":{
1135 "description":"Order not found"
1201 "description":"Order not found"
1136 }
1202 }
1137 }
1203 }
1138 }
1204 }
1139 },
1205 },
1140− "/user":{
1206+ "/user":{
1141− "post":{
1207+ "post":{
1142− "tags":[
1208+ "tags":[
1143 "user"
1209 "user"
1144 ],
1210 ],
1145 "summary":"Create user",
1211 "summary":"Create user",
1146 "description":"This can only be done by the logged in user.",
1212 "description":"This can only be done by the logged in user.",
1147 "operationId":"createUser",
1213 "operationId":"createUser",
1148− "produces":[
1214+ "produces":[
1149 "application/xml",
1215 "application/xml",
1150 "application/json"
1216 "application/json"
1151 ],
1217 ],
1152− "parameters":[
1218+ "parameters":[
1153− {
1219+ {
1154 "in":"body",
1220 "in":"body",
1155 "name":"body",
1221 "name":"body",
1156 "description":"Created user object",
1222 "description":"Created user object",
1157 "required":true,
1223 "required":true,
1158− "schema":{
1224+ "schema":{
1159 "$ref":"#/definitions/User"
1225 "$ref":"#/definitions/User"
1160 }
1226 }
1161 }
1227 }
1162 ],
1228 ],
1163− "responses":{
1229+ "responses":{
1164− "default":{
1230+ "default":{
1165 "description":"successful operation"
1231 "description":"successful operation"
1166 }
1232 }
1167 }
1233 }
1168 }
1234 }
1169 },
1235 },
1170− "/user/createWithArray":{
1236+ "/user/createWithArray":{
1171− "post":{
1237+ "post":{
1172− "tags":[
1238+ "tags":[
1173 "user"
1239 "user"
1174 ],
1240 ],
1175 "summary":"Creates list of users with given input array",
1241 "summary":"Creates list of users with given input array",
1176 "description":"",
1242 "description":"",
1177 "operationId":"createUsersWithArrayInput",
1243 "operationId":"createUsersWithArrayInput",
1178− "produces":[
1244+ "produces":[
1179 "application/xml",
1245 "application/xml",
1180 "application/json"
1246 "application/json"
1181 ],
1247 ],
1182− "parameters":[
1248+ "parameters":[
1183− {
1249+ {
1184 "in":"body",
1250 "in":"body",
1185 "name":"body",
1251 "name":"body",
1186 "description":"List of user object",
1252 "description":"List of user object",
1187 "required":true,
1253 "required":true,
1188− "schema":{
1254+ "schema":{
1189 "type":"array",
1255 "type":"array",
1190− "items":{
1256+ "items":{
1191 "$ref":"#/definitions/User"
1257 "$ref":"#/definitions/User"
1192 }
1258 }
1193 }
1259 }
1194 }
1260 }
1195 ],
1261 ],
1196− "responses":{
1262+ "responses":{
1197− "default":{
1263+ "default":{
1198 "description":"successful operation"
1264 "description":"successful operation"
1199 }
1265 }
1200 }
1266 }
1201 }
1267 }
1202 },
1268 },
1203− "/user/createWithList":{
1269+ "/user/createWithList":{
1204− "post":{
1270+ "post":{
1205− "tags":[
1271+ "tags":[
1206 "user"
1272 "user"
1207 ],
1273 ],
1208 "summary":"Creates list of users with given input array",
1274 "summary":"Creates list of users with given input array",
1209 "description":"",
1275 "description":"",
1210 "operationId":"createUsersWithListInput",
1276 "operationId":"createUsersWithListInput",
1211− "produces":[
1277+ "produces":[
1212 "application/xml",
1278 "application/xml",
1213 "application/json"
1279 "application/json"
1214 ],
1280 ],
1215− "parameters":[
1281+ "parameters":[
1216− {
1282+ {
1217 "in":"body",
1283 "in":"body",
1218 "name":"body",
1284 "name":"body",
1219 "description":"List of user object",
1285 "description":"List of user object",
1220 "required":true,
1286 "required":true,
1221− "schema":{
1287+ "schema":{
1222 "type":"array",
1288 "type":"array",
1223− "items":{
1289+ "items":{
1224 "$ref":"#/definitions/User"
1290 "$ref":"#/definitions/User"
1225 }
1291 }
1226 }
1292 }
1227 }
1293 }
1228 ],
1294 ],
1229− "responses":{
1295+ "responses":{
1230− "default":{
1296+ "default":{
1231 "description":"successful operation"
1297 "description":"successful operation"
1232 }
1298 }
1233 }
1299 }
1234 }
1300 }
1235 },
1301 },
1236− "/user/login":{
1302+ "/user/login":{
1237− "get":{
1303+ "get":{
1238− "tags":[
1304+ "tags":[
1239 "user"
1305 "user"
1240 ],
1306 ],
1241 "summary":"Logs user into the system",
1307 "summary":"Logs user into the system",
1242 "description":"",
1308 "description":"",
1243 "operationId":"loginUser",
1309 "operationId":"loginUser",
1244− "produces":[
1310+ "produces":[
1245 "application/xml",
1311 "application/xml",
1246 "application/json"
1312 "application/json"
1247 ],
1313 ],
1248− "parameters":[
1314+ "parameters":[
1249− {
1315+ {
1250 "name":"username",
1316 "name":"username",
1251 "in":"query",
1317 "in":"query",
1252 "description":"The user name for login",
1318 "description":"The user name for login",
1253 "required":true,
1319 "required":true,
1254 "type":"string"
1320 "type":"string"
1255 },
1321 },
1256− {
1322+ {
1257 "name":"password",
1323 "name":"password",
1258 "in":"query",
1324 "in":"query",
1259 "description":"The password for login in clear text",
1325 "description":"The password for login in clear text",
@@ -1261,65 +1327,65 @@ petstoreExampleJSON = [aesonQQ|
1261 "type":"string"
1327 "type":"string"
1262 }
1328 }
1263 ],
1329 ],
1264− "responses":{
1330+ "responses":{
1265− "200":{
1331+ "200":{
1266 "description":"successful operation",
1332 "description":"successful operation",
1267− "schema":{
1333+ "schema":{
1268 "type":"string"
1334 "type":"string"
1269 },
1335 },
1270− "headers":{
1336+ "headers":{
1271− "X-Rate-Limit":{
1337+ "X-Rate-Limit":{
1272 "type":"integer",
1338 "type":"integer",
1273 "format":"int32",
1339 "format":"int32",
1274 "description":"calls per hour allowed by the user"
1340 "description":"calls per hour allowed by the user"
1275 },
1341 },
1276− "X-Expires-After":{
1342+ "X-Expires-After":{
1277 "type":"string",
1343 "type":"string",
1278 "format":"date-time",
1344 "format":"date-time",
1279 "description":"date in UTC when toekn expires"
1345 "description":"date in UTC when toekn expires"
1280 }
1346 }
1281 }
1347 }
1282 },
1348 },
1283− "400":{
1349+ "400":{
1284 "description":"Invalid username/password supplied"
1350 "description":"Invalid username/password supplied"
1285 }
1351 }
1286 }
1352 }
1287 }
1353 }
1288 },
1354 },
1289− "/user/logout":{
1355+ "/user/logout":{
1290− "get":{
1356+ "get":{
1291− "tags":[
1357+ "tags":[
1292 "user"
1358 "user"
1293 ],
1359 ],
1294 "summary":"Logs out current logged in user session",
1360 "summary":"Logs out current logged in user session",
1295 "description":"",
1361 "description":"",
1296 "operationId":"logoutUser",
1362 "operationId":"logoutUser",
1297− "produces":[
1363+ "produces":[
1298 "application/xml",
1364 "application/xml",
1299 "application/json"
1365 "application/json"
1300 ],
1366 ],
1301 "parameters": [],
1367 "parameters": [],
1302− "responses":{
1368+ "responses":{
1303− "default":{
1369+ "default":{
1304 "description":"successful operation"
1370 "description":"successful operation"
1305 }
1371 }
1306 }
1372 }
1307 }
1373 }
1308 },
1374 },
1309− "/user/{username}":{
1375+ "/user/{username}":{
1310− "get":{
1376+ "get":{
1311− "tags":[
1377+ "tags":[
1312 "user"
1378 "user"
1313 ],
1379 ],
1314 "summary":"Get user by user name",
1380 "summary":"Get user by user name",
1315 "description":"",
1381 "description":"",
1316 "operationId":"getUserByName",
1382 "operationId":"getUserByName",
1317− "produces":[
1383+ "produces":[
1318 "application/xml",
1384 "application/xml",
1319 "application/json"
1385 "application/json"
1320 ],
1386 ],
1321− "parameters":[
1387+ "parameters":[
1322− {
1388+ {
1323 "name":"username",
1389 "name":"username",
1324 "in":"path",
1390 "in":"path",
1325 "description":"The name that needs to be fetched. Use user1 for testing. ",
1391 "description":"The name that needs to be fetched. Use user1 for testing. ",
@@ -1327,72 +1393,72 @@ petstoreExampleJSON = [aesonQQ|
1327 "type":"string"
1393 "type":"string"
1328 }
1394 }
1329 ],
1395 ],
1330− "responses":{
1396+ "responses":{
1331− "200":{
1397+ "200":{
1332 "description":"successful operation",
1398 "description":"successful operation",
1333− "schema":{
1399+ "schema":{
1334 "$ref":"#/definitions/User"
1400 "$ref":"#/definitions/User"
1335 }
1401 }
1336 },
1402 },
1337− "400":{
1403+ "400":{
1338 "description":"Invalid username supplied"
1404 "description":"Invalid username supplied"
1339 },
1405 },
1340− "404":{
1406+ "404":{
1341 "description":"User not found"
1407 "description":"User not found"
1342 }
1408 }
1343 }
1409 }
1344 },
1410 },
1345− "put":{
1411+ "put":{
1346− "tags":[
1412+ "tags":[
1347 "user"
1413 "user"
1348 ],
1414 ],
1349 "summary":"Updated user",
1415 "summary":"Updated user",
1350 "description":"This can only be done by the logged in user.",
1416 "description":"This can only be done by the logged in user.",
1351 "operationId":"updateUser",
1417 "operationId":"updateUser",
1352− "produces":[
1418+ "produces":[
1353 "application/xml",
1419 "application/xml",
1354 "application/json"
1420 "application/json"
1355 ],
1421 ],
1356− "parameters":[
1422+ "parameters":[
1357− {
1423+ {
1358 "name":"username",
1424 "name":"username",
1359 "in":"path",
1425 "in":"path",
1360 "description":"name that need to be deleted",
1426 "description":"name that need to be deleted",
1361 "required":true,
1427 "required":true,
1362 "type":"string"
1428 "type":"string"
1363 },
1429 },
1364− {
1430+ {
1365 "in":"body",
1431 "in":"body",
1366 "name":"body",
1432 "name":"body",
1367 "description":"Updated user object",
1433 "description":"Updated user object",
1368 "required":true,
1434 "required":true,
1369− "schema":{
1435+ "schema":{
1370 "$ref":"#/definitions/User"
1436 "$ref":"#/definitions/User"
1371 }
1437 }
1372 }
1438 }
1373 ],
1439 ],
1374− "responses":{
1440+ "responses":{
1375− "400":{
1441+ "400":{
1376 "description":"Invalid user supplied"
1442 "description":"Invalid user supplied"
1377 },
1443 },
1378− "404":{
1444+ "404":{
1379 "description":"User not found"
1445 "description":"User not found"
1380 }
1446 }
1381 }
1447 }
1382 },
1448 },
1383− "delete":{
1449+ "delete":{
1384− "tags":[
1450+ "tags":[
1385 "user"
1451 "user"
1386 ],
1452 ],
1387 "summary":"Delete user",
1453 "summary":"Delete user",
1388 "description":"This can only be done by the logged in user.",
1454 "description":"This can only be done by the logged in user.",
1389 "operationId":"deleteUser",
1455 "operationId":"deleteUser",
1390− "produces":[
1456+ "produces":[
1391 "application/xml",
1457 "application/xml",
1392 "application/json"
1458 "application/json"
1393 ],
1459 ],
1394− "parameters":[
1460+ "parameters":[
1395− {
1461+ {
1396 "name":"username",
1462 "name":"username",
1397 "in":"path",
1463 "in":"path",
1398 "description":"The name that needs to be deleted",
1464 "description":"The name that needs to be deleted",
@@ -1400,207 +1466,237 @@ petstoreExampleJSON = [aesonQQ|
1400 "type":"string"
1466 "type":"string"
1401 }
1467 }
1402 ],
1468 ],
1403− "responses":{
1469+ "responses":{
1404− "400":{
1470+ "400":{
1405 "description":"Invalid username supplied"
1471 "description":"Invalid username supplied"
1406 },
1472 },
1407− "404":{
1473+ "404":{
1408 "description":"User not found"
1474 "description":"User not found"
1409 }
1475 }
1410 }
1476 }
1411 }
1477 }
1412 }
1478 }
1413 },
1479 },
1414− "securityDefinitions":{
1480+ "securityDefinitions":{
1415− "petstore_auth":{
1481+ "petstore_auth":{
1416 "type":"oauth2",
1482 "type":"oauth2",
1417 "authorizationUrl":"http://petstore.swagger.io/api/oauth/dialog",
1483 "authorizationUrl":"http://petstore.swagger.io/api/oauth/dialog",
1418 "flow":"implicit",
1484 "flow":"implicit",
1419− "scopes":{
1485+ "scopes":{
1420 "write:pets":"modify pets in your account",
1486 "write:pets":"modify pets in your account",
1421 "read:pets":"read your pets"
1487 "read:pets":"read your pets"
1422 }
1488 }
1423 },
1489 },
1424− "api_key":{
1490+ "api_key":{
1425 "type":"apiKey",
1491 "type":"apiKey",
1426 "name":"api_key",
1492 "name":"api_key",
1427 "in":"header"
1493 "in":"header"
1428 }
1494 }
1429 },
1495 },
1430− "definitions":{
1496+ "definitions":{
1431− "Order":{
1497+ "Order":{
1432 "type":"object",
1498 "type":"object",
1433− "properties":{
1499+ "properties":{
1434− "id":{
1500+ "id":{
1435 "type":"integer",
1501 "type":"integer",
1436 "format":"int64"
1502 "format":"int64"
1437 },
1503 },
1438− "petId":{
1504+ "petId":{
1439 "type":"integer",
1505 "type":"integer",
1440 "format":"int64"
1506 "format":"int64"
1441 },
1507 },
1442− "quantity":{
1508+ "quantity":{
1443 "type":"integer",
1509 "type":"integer",
1444 "format":"int32"
1510 "format":"int32"
1445 },
1511 },
1446− "shipDate":{
1512+ "shipDate":{
1447 "type":"string",
1513 "type":"string",
1448 "format":"date-time"
1514 "format":"date-time"
1449 },
1515 },
1450− "status":{
1516+ "status":{
1451 "type":"string",
1517 "type":"string",
1452 "description":"Order Status",
1518 "description":"Order Status",
1453− "enum":[
1519+ "enum":[
1454 "placed",
1520 "placed",
1455 "approved",
1521 "approved",
1456 "delivered"
1522 "delivered"
1457 ]
1523 ]
1458 },
1524 },
1459− "complete":{
1525+ "complete":{
1460 "type":"boolean",
1526 "type":"boolean",
1461 "default":false
1527 "default":false
1462 }
1528 }
1463 },
1529 },
1464− "xml":{
1530+ "xml":{
1465 "name":"Order"
1531 "name":"Order"
1466 }
1532 }
1467 },
1533 },
1468− "Category":{
1534+ "Category":{
1469 "type":"object",
1535 "type":"object",
1470− "properties":{
1536+ "properties":{
1471− "id":{
1537+ "id":{
1472 "type":"integer",
1538 "type":"integer",
1473 "format":"int64"
1539 "format":"int64"
1474 },
1540 },
1475− "name":{
1541+ "name":{
1476 "type":"string"
1542 "type":"string"
1477 }
1543 }
1478 },
1544 },
1479− "xml":{
1545+ "xml":{
1480 "name":"Category"
1546 "name":"Category"
1481 }
1547 }
1482 },
1548 },
1483− "User":{
1549+ "User":{
1484 "type":"object",
1550 "type":"object",
1485− "properties":{
1551+ "properties":{
1486− "id":{
1552+ "id":{
1487 "type":"integer",
1553 "type":"integer",
1488 "format":"int64"
1554 "format":"int64"
1489 },
1555 },
1490− "username":{
1556+ "username":{
1491 "type":"string"
1557 "type":"string"
1492 },
1558 },
1493− "firstName":{
1559+ "firstName":{
1494 "type":"string"
1560 "type":"string"
1495 },
1561 },
1496− "lastName":{
1562+ "lastName":{
1497 "type":"string"
1563 "type":"string"
1498 },
1564 },
1499− "email":{
1565+ "email":{
1500 "type":"string"
1566 "type":"string"
1501 },
1567 },
1502− "password":{
1568+ "password":{
1503 "type":"string"
1569 "type":"string"
1504 },
1570 },
1505− "phone":{
1571+ "phone":{
1506 "type":"string"
1572 "type":"string"
1507 },
1573 },
1508− "userStatus":{
1574+ "userStatus":{
1509 "type":"integer",
1575 "type":"integer",
1510 "format":"int32",
1576 "format":"int32",
1511 "description":"User Status"
1577 "description":"User Status"
1512 }
1578 }
1513 },
1579 },
1514− "xml":{
1580+ "xml":{
1515 "name":"User"
1581 "name":"User"
1516 }
1582 }
1517 },
1583 },
1518− "Tag":{
1584+ "Tag":{
1519 "type":"object",
1585 "type":"object",
1520− "properties":{
1586+ "properties":{
1521− "id":{
1587+ "id":{
1522 "type":"integer",
1588 "type":"integer",
1523 "format":"int64"
1589 "format":"int64"
1524 },
1590 },
1525− "name":{
1591+ "name":{
1526 "type":"string"
1592 "type":"string"
1527 }
1593 }
1528 },
1594 },
1529− "xml":{
1595+ "xml":{
1530 "name":"Tag"
1596 "name":"Tag"
1531 }
1597 }
1532 },
1598 },
1533− "Pet":{
1599+ "Pet":{
1534 "type":"object",
1600 "type":"object",
1535− "required":[
1601+ "required":[
1536 "name",
1602 "name",
1537 "photoUrls"
1603 "photoUrls"
1538 ],
1604 ],
1539− "properties":{
1605+ "properties":{
1540− "id":{
1606+ "id":{
1541 "type":"integer",
1607 "type":"integer",
1542 "format":"int64"
1608 "format":"int64"
1543 },
1609 },
1544− "category":{
1610+ "category":{
1545 "$ref":"#/definitions/Category"
1611 "$ref":"#/definitions/Category"
1546 },
1612 },
1547− "name":{
1613+ "name":{
1548 "type":"string",
1614 "type":"string",
1549 "example":"doggie"
1615 "example":"doggie"
1550 },
1616 },
1551− "photoUrls":{
1617+ "photoUrls":{
1552 "type":"array",
1618 "type":"array",
1553− "xml":{
1619+ "xml":{
1554 "name":"photoUrl",
1620 "name":"photoUrl",
1555 "wrapped":true
1621 "wrapped":true
1556 },
1622 },
1557− "items":{
1623+ "items":{
1558 "type":"string"
1624 "type":"string"
1559 }
1625 }
1560 },
1626 },
1561− "tags":{
1627+ "tags":{
1562 "type":"array",
1628 "type":"array",
1563− "xml":{
1629+ "xml":{
1564 "name":"tag",
1630 "name":"tag",
1565 "wrapped":true
1631 "wrapped":true
1566 },
1632 },
1567− "items":{
1633+ "items":{
1568 "$ref":"#/definitions/Tag"
1634 "$ref":"#/definitions/Tag"
1569 }
1635 }
1570 },
1636 },
1571− "status":{
1637+ "status":{
1572 "type":"string",
1638 "type":"string",
1573 "description":"pet status in the store",
1639 "description":"pet status in the store",
1574− "enum":[
1640+ "enum":[
1575 "available",
1641 "available",
1576 "pending",
1642 "pending",
1577 "sold"
1643 "sold"
1578 ]
1644 ]
1579 }
1645 }
1580 },
1646 },
1581− "xml":{
1647+ "xml":{
1582 "name":"Pet"
1648 "name":"Pet"
1583 }
1649 }
1584 },
1650 },
1585− "ApiResponse":{
1651+ "ApiResponse":{
1586 "type":"object",
1652 "type":"object",
1587− "properties":{
1653+ "properties":{
1588− "code":{
1654+ "code":{
1589 "type":"integer",
1655 "type":"integer",
1590 "format":"int32"
1656 "format":"int32"
1591 },
1657 },
1592− "type":{
1658+ "type":{
1593 "type":"string"
1659 "type":"string"
1594 },
1660 },
1595− "message":{
1661+ "message":{
1596 "type":"string"
1662 "type":"string"
1597 }
1663 }
1598 }
1664 }
1599 }
1665 }
1600 },
1666 },
1601− "externalDocs":{
1667+ "externalDocs":{
1602 "description":"Find out more about Swagger",
1668 "description":"Find out more about Swagger",
1603 "url":"http://swagger.io"
1669 "url":"http://swagger.io"
1604 }
1670 }
1605}
1671}
1606|]
1672|]
1673+
1674+compositionSchemaExample :: Schema
1675+compositionSchemaExample = mempty
1676+ & type_ ?~ SwaggerObject
1677+ & Data.Swagger.allOf ?~ [
1678+ Ref (Reference "Other")
1679+ , Inline (mempty
1680+ & type_ ?~ SwaggerObject
1681+ & properties .~
1682+ [ ("greet", Inline $ mempty
1683+ & type_ ?~ SwaggerString) ])
1684+ ]
1685+
1686+compositionSchemaExampleJSON :: Value
1687+compositionSchemaExampleJSON = [aesonQQ|
1688+{
1689+ "type": "object",
1690+ "allOf": [
1691+ {
1692+ "$ref": "#/definitions/Other"
1693+ },
1694+ {
1695+ "type": "object",
1696+ "properties": {
1697+ "greet": { "type": "string" }
1698+ }
1699+ }
1700+ ]
1701+}
1702+|]
test/DocTest.hsdeleted−8
@@ -1,8 +0,0 @@
1−module Main (main) where
2−
3−import System.FilePath.Glob (glob)
4−import Test.DocTest (doctest)
5−
6−main :: IO ()
7−main = glob "src/**/*.hs" >>= doctest'
8− where doctest' files = doctest $ "-Iinclude/" : "-D__DOCTEST__" : files
test/SpecCommon.hs+7−2
@@ -1,6 +1,7 @@
1module SpecCommon where
1module SpecCommon where
2
2
3import Data.Aeson
3import Data.Aeson
4+import Data.ByteString.Builder (toLazyByteString)
4import qualified Data.Foldable as F
5import qualified Data.Foldable as F
5import qualified Data.HashMap.Strict as HashMap
6import qualified Data.HashMap.Strict as HashMap
6import qualified Data.Vector as Vector
7import qualified Data.Vector as Vector
@@ -21,5 +22,9 @@ x <=> js = do
21 toJSON x `shouldBe` js
22 toJSON x `shouldBe` js
22 it "decodes correctly" $ do
23 it "decodes correctly" $ do
23 fromJSON js `shouldBe` Success x
24 fromJSON js `shouldBe` Success x
24−
25+ it "roundtrips: eitherDecode . encode" $ do
25−
26+ eitherDecode (encode x) `shouldBe` Right x
27+ it "roundtrips with toJSON" $ do
28+ eitherDecode (encode $ toJSON x) `shouldBe` Right x
29+ it "roundtrips with toEncoding" $ do
30+ eitherDecode (toLazyByteString $ fromEncoding $ toEncoding x) `shouldBe` Right x
test/doctests.hsnew file+12
@@ -0,0 +1,12 @@
1+module Main where
2+
3+import Build_doctests (flags, pkgs, module_sources)
4+import Data.Foldable (traverse_)
5+import Test.DocTest
6+
7+main :: IO ()
8+main = do
9+ traverse_ putStrLn args
10+ doctest args
11+ where
12+ args = flags ++ pkgs ++ module_sources