git.iko.soy/typeable/swagger2
on ddab0db help sign in
.ghcideleted−2
since splitsnapshots
unifiedsplit
@@ -1,2 +0,0 @@
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,6 +1,4 @@
1dist
1dist
2−dist-newstyle
3−.ghc.environment.*
4cabal-dev
2cabal-dev
5*.o
3*.o
6*.hi
4*.hi
.travis.yml+34−155
@@ -1,162 +1,41 @@
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−#
9language: c
1language: c
10−dist: xenial
2+
11−git:
3+# explicitly request container-based infrastructure
12− # whether to recursively clone submodules
13− submodules: false
4+sudo: false
14−branches:
5+
15− only:
16− - master
17−cache:
18− directories:
19− - $HOME/.cabal/packages
20− - $HOME/.cabal/store
21−before_cache:
22− - rm -fv $CABALHOME/packages/hackage.haskell.org/build-reports.log
23− # remove files that are regenerated by 'cabal update'
24− - rm -fv $CABALHOME/packages/hackage.haskell.org/00-index.*
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
30matrix:
6matrix:
31 include:
7 include:
32− - compiler: ghc-8.8.1
8+ - env: CABALVER=1.18 GHCVER=7.8.4 HAPPYVER=1.19.4
33− addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-8.8.1","cabal-install-3.0"]}}
9+ addons: {apt: {packages: [cabal-install-1.18,ghc-7.8.4,happy-1.19.4], sources: [hvr-ghc]}}
34− - compiler: ghc-8.6.5
10+ - env: CABALVER=1.22 GHCVER=7.10.1 HAPPYVER=1.19.5
35− addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-8.6.5","cabal-install-3.0"]}}
11+ addons: {apt: {packages: [cabal-install-1.22,ghc-7.10.1,happy-1.19.5],sources: [hvr-ghc]}}
36− - compiler: ghc-8.4.4
12+ - env: CABALVER=head GHCVER=head HAPPYVER=head
37− addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-8.4.4","cabal-install-3.0"]}}
13+ addons: {apt: {packages: [cabal-install-head,ghc-head,happy-head], sources: [hvr-ghc]}}
38− - compiler: ghc-8.2.2
14+
39− addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-8.2.2","cabal-install-3.0"]}}
15+ allow_failures:
40− - compiler: ghc-8.0.2
16+ - env: CABALVER=1.18 GHCVER=7.8.4 HAPPYVER=1.19.4
41− addons: {"apt":{"sources":["hvr-ghc"],"packages":["ghc-8.0.2","cabal-install-3.0"]}}
17+ - env: CABALVER=head GHCVER=head HAPPYVER=head
18+
42before_install:
19before_install:
43− - HC=$(echo "/opt/$CC/bin/ghc" | sed 's/-/\//')
20+ - export PATH=/opt/ghc/$GHCVER/bin:/opt/cabal/$CABALVER/bin:$PATH:/opt/happy/$HAPPYVER/bin
44− - WITHCOMPILER="-w $HC"
21+
45− - HADDOCK=$(echo "/opt/$CC/bin/haddock" | sed 's/-/\//')
46− - HCPKG="$HC-pkg"
47− - unset CC
48− - CABAL=/opt/ghc/bin/cabal
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
74install:
22install:
75− - ${CABAL} --version
23+ - cabal --version
76− - echo "$(${HC} --version) [$(${HC} --print-project-git-commit-id 2> /dev/null || echo '?')]"
24+ - echo "$(ghc --version) [$(ghc --print-project-git-commit-id 2> /dev/null || echo '?')]"
77− - TEST=--enable-tests
78− - BENCH=--enable-benchmarks
79− - HEADHACKAGE=false
80− - rm -f $CABALHOME/config
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
110− - travis_retry ${CABAL} v2-update -v
25+ - travis_retry cabal update
111− # Generate cabal.project
26+ - cabal install --only-dependencies --enable-tests --enable-benchmarks
112− - rm -rf cabal.project cabal.project.local cabal.project.freeze
27+
113− - touch cabal.project
28+# Here starts the actual work to be performed for the package under test; any command which exits with a non-zero exit code causes the build to fail.
114− - |
115− echo "packages: ." >> cabal.project
116− - |
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"
118− - cat cabal.project || true
119− - cat cabal.project.local || true
120− - if [ -f "./configure.ac" ]; then (cd "." && autoreconf -i); fi
121− - ${CABAL} v2-freeze $WITHCOMPILER ${TEST} ${BENCH} | color_cabal_output
122− - "cat cabal.project.freeze | sed -E 's/^(constraints: *| *)//' | sed 's/any.//'"
123− - rm cabal.project.freeze
124− - ${CABAL} v2-build $WITHCOMPILER ${TEST} ${BENCH} --dep -j2 all | color_cabal_output
125− - ${CABAL} v2-build $WITHCOMPILER --disable-tests --disable-benchmarks --dep -j2 all | color_cabal_output
126script:
29script:
127− - DISTDIR=$(mktemp -d /tmp/dist-test.XXXX)
30+ - if [ -f configure.ac ]; then autoreconf -i; fi
128− # Packaging...
31+ - cabal configure --enable-tests --enable-benchmarks -v2 # -v2 provides useful information for debugging
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...
146− # this builds all libraries and executables (without tests/benchmarks)
32+ - cabal build --ghc-options="-O0" # this builds all libraries and executables (including tests/benchmarks)
147− - ${CABAL} v2-build $WITHCOMPILER --disable-tests --disable-benchmarks all | color_cabal_output
33+ - cabal test
148− # Building with tests and benchmarks...
34+ - cabal check
149− # build & run tests, build benchmarks
35+ - cabal sdist # tests that a source-distribution can be generated
150− - ${CABAL} v2-build $WITHCOMPILER ${TEST} ${BENCH} all | color_cabal_output
151− # Testing...
152− - ${CABAL} v2-test $WITHCOMPILER ${TEST} ${BENCH} all | color_cabal_output
153− # cabal check...
154− - (cd ${PKGDIR_swagger2} && ${CABAL} -vnormal check)
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
160
36
161−# REGENDATA ("0.5.20191020",["--branches","master","--haddock-jobs=>=8.4","--output",".travis.yml","swagger2.cabal"])
37+# Check that the resulting source distribution can be built & installed.
162−# EOF
38+# If there are no other `.tar.gz` files in `dist`, this can be even simpler:
39+# `cabal install --force-reinstalls dist/*-*.tar.gz`
40+ - SRC_TGZ=$(cabal info . | awk '{print $2;exit}').tar.gz &&
41+ (cd dist && cabal install --force-reinstalls "$SRC_TGZ")
CHANGELOG.md+9−235
@@ -1,229 +1,3 @@
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−
186−1.2.1
187−---
188−
189−* Minor changes:
190− * Change `_SwaggerItemsPrimitive` type from a `Prism'` to a more restrictive `Review`-like `Optic'`.
191−
192−* Fixes:
193− * Fix build for GHC 8.0-rc1.
194−
195−1.2
196−---
197−* Minor changes (see [#36](https://github.com/GetShopTV/swagger2/pull/36)):
198− * Change default `ToSchema` instance for unit data types (i.e. types with one nullable constructor like `data Unit = Unit`):
199− now these types are treated like sum types with only one alternative;
200− * Add generic `ToParamSchema` instance for unit data types;
201− * Add `items: []` to schema for `()` (making it a valid schema).
202−
203−* Fixes:
204− * Do not omit `items: []` from `Schema` JSON;
205− * Do not generate unused definitions for nested `newtype`s (see [#38](https://github.com/GetShopTV/swagger2/pull/38)).
206−
207−1.1.1
208−---
209−* Fixes:
210− * `CollectionFormat Param` -> `CollectionFormat ParamOtherSchema`;
211− this change was necessary after putting `CollectionFormat` to `SwaggerItems`.
212−
213−1.1
214−---
215−* Major changes:
216− * Put `CollectionFormat` in one place (see [`3cc860d`](https://github.com/GetShopTV/swagger2/commit/3cc860dd3f002ab984f4d0e4ce1d1799f985832e)).
217−
218−* Minor changes:
219− * Use Swagger formats for `Int32`, `Int64`, `Float`, `Double`, `Day` and `ZonedTime` (see [#32](https://github.com/GetShopTV/swagger2/pull/32));
220− * Export `HeaderName`, `TagName`, `HttpStatusCode` type synonyms;
221− * Add `ToParamSchema` instances for `[a]`, `Set a` and `HashSet a`;
222− * Add `Monoid` instances for `Header` and `Example`.
223−
224−* Fixes:
225− * Use overwrite strategy for `HashMap` `SwaggerMonoid` instances by default.
226−
2271.0
11.0
228---
2---
229* Major changes:
3* Major changes:
@@ -240,7 +14,7 @@ Dependencies and CI:
240 * Add `declareSchema`, `declareSchemaRef`;
14 * Add `declareSchema`, `declareSchemaRef`;
241 * Replace `genericTo*` helpers with `genericDeclare*` helpers;
15 * Replace `genericTo*` helpers with `genericDeclare*` helpers;
242 * Add `paramSchemaTo[Named]Schema` helpers to facilitate code reuse for primitive schemas;
16 * Add `paramSchemaTo[Named]Schema` helpers to facilitate code reuse for primitive schemas;
243− * Add helpers for inlining `Schema` references dynamically (see [#23](https://github.com/GetShopTV/swagger2/pull/23));
17+ * Add helpers for inlining `Schema` references dynamically (see [#23](https://github.com/GetShopTV/swagger2/pull/23)).
244 * Add `ToParamSchema` class (see [#17](https://github.com/GetShopTV/swagger2/pull/17)) with
18 * Add `ToParamSchema` class (see [#17](https://github.com/GetShopTV/swagger2/pull/17)) with
245 * generic default implementation and
19 * generic default implementation and
246 * instances for some base types compliant with `http-api-data` instances;
20 * instances for some base types compliant with `http-api-data` instances;
@@ -265,8 +39,8 @@ Dependencies and CI:
265 * Remove `minLength` property from schemas for `time` types;
39 * Remove `minLength` property from schemas for `time` types;
266 * Move `SchemaOptions` to `Data.Swagger.SchemaOptions`;
40 * Move `SchemaOptions` to `Data.Swagger.SchemaOptions`;
267 * Remove `useReferences` from `SchemaOptions` (see [#23](https://github.com/GetShopTV/swagger2/pull/23));
41 * Remove `useReferences` from `SchemaOptions` (see [#23](https://github.com/GetShopTV/swagger2/pull/23));
268− * Place all internal submodules under `Data.Swagger.Internal`;
42+ * Place all internal submodules under `Data.Swagger.Internal`.
269− * Better documentation (see [#26](https://github.com/GetShopTV/swagger2/pull/26)).
43+ * Better documentation (see [#26](https://github.com/GetShopTV/swagger2/pull/26));
270
44
2710.4.1
450.4.1
272---
46---
@@ -285,7 +59,7 @@ Dependencies and CI:
285 * Fix `HasSchemaCommon` instance for `Schema`;
59 * Fix `HasSchemaCommon` instance for `Schema`;
286 * Change `minimum`, `maximum` and `multipleOf` properties to be any number,
60 * Change `minimum`, `maximum` and `multipleOf` properties to be any number,
287 not necessarily an integer;
61 not necessarily an integer;
288− * Fix all warnings.
62+ * Fix all warnings
289
63
2900.3
640.3
291---
65---
@@ -297,9 +71,9 @@ Dependencies and CI:
297
71
2980.2
720.2
299---
73---
300−* Add `Data.Swagger.Lens`;
74+* Add `Data.Swagger.Lens`
301−* Support references;
75+* Support references
302* Fixes:
76* Fixes:
303− * Fix `FromJSON SwaggerHost` instance;
77+ * Fix `FromJSON SwaggerHost` instance
304− * Add missing `Maybe`s for field types;
78+ * Add missing `Maybe`s for field types
305− * Decode petstore `swagger.json` successfully.
79+ * Decode petstore swagger.json successfully
LICENSE+1−1
@@ -1,4 +1,4 @@
1−Copyright (c) 2015-2017, GetShopTV
1+Copyright (c) 2015, 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+1−5
@@ -1,11 +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−
5[![Hackage](https://img.shields.io/hackage/v/swagger2.svg)](http://hackage.haskell.org/package/swagger2)
3[![Hackage](https://img.shields.io/hackage/v/swagger2.svg)](http://hackage.haskell.org/package/swagger2)
6[![Build Status](https://travis-ci.org/GetShopTV/swagger2.svg?branch=master)](https://travis-ci.org/GetShopTV/swagger2)
4[![Build Status](https://travis-ci.org/GetShopTV/swagger2.svg?branch=master)](https://travis-ci.org/GetShopTV/swagger2)
7−[![Stackage LTS](http://stackage.org/package/swagger2/badge/lts)](http://stackage.org/lts/package/swagger2)
8−[![Stackage Nightly](http://stackage.org/package/swagger2/badge/nightly)](http://stackage.org/nightly/package/swagger2)
9
5
10Swagger 2.0 data model.
6Swagger 2.0 data model.
11
7
@@ -13,7 +9,7 @@ The original Swagger 2.0 specification is available at http://swagger.io/specifi
13
9
14## Usage
10## Usage
15
11
16−This library is intended to be used for decoding and encoding Swagger 2.0 API specifications as well as manipulating them.
12+This library is inteded to be used for decoding and encoding Swagger 2.0 API specifications as well as manipulating them.
17
13
18Please refer to [haddock documentation](http://hackage.haskell.org/package/swagger2).
14Please refer to [haddock documentation](http://hackage.haskell.org/package/swagger2).
19
15
Setup.hs−31
@@ -1,33 +1,2 @@
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−
28import Distribution.Simple
1import Distribution.Simple
29−
30−main :: IO ()
31main = defaultMain
2main = defaultMain
32−
33−#endif
cabal.projectdeleted−2
@@ -1,2 +0,0 @@
1−packages: .
2−tests: true
examples/hackage.hs+24−40
@@ -13,28 +13,13 @@ 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
17
16
18type Username = Text
17type Username = Text
19
18
20data UserSummary = UserSummary
19data UserSummary = UserSummary
21 { summaryUsername :: Username
20 { summaryUsername :: Username
22 , summaryUserid :: Int
21 , summaryUserid :: Int
23− } deriving (Generic)
22+ } deriving (Generic, ToSchema)
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−
38
23
39type Group = Text
24type Group = Text
40
25
@@ -52,33 +37,32 @@ hackageSwagger = spec & definitions .~ defs
52 where
37 where
53 (defs, spec) = runDeclare declareHackageSwagger mempty
38 (defs, spec) = runDeclare declareHackageSwagger mempty
54
39
55−declareHackageSwagger :: Declare (Definitions Schema) Swagger
40+declareHackageSwagger :: Declare Definitions Swagger
56declareHackageSwagger = do
41declareHackageSwagger = do
57− -- param schemas
58 let usernameParamSchema = toParamSchema (Proxy :: Proxy Username)
42 let usernameParamSchema = toParamSchema (Proxy :: Proxy Username)
59−
43+ userSummarySchemaRef <- declareSchemaRef (Proxy :: Proxy UserSummary)
60− -- responses
44+ userDetailedSchemaRef <- declareSchemaRef (Proxy :: Proxy UserDetailed)
61− userSummaryResponse <- declareResponse (Proxy :: Proxy UserSummary)
45+ packagesSchemaRef <- declareSchemaRef (Proxy :: Proxy [Package])
62− userDetailedResponse <- declareResponse (Proxy :: Proxy UserDetailed)
63− packagesResponse <- declareResponse (Proxy :: Proxy [Package])
64−
65 return $ mempty
46 return $ mempty
66− & paths .~
47+ & paths.pathsMap .~
67− [ ("/users", mempty & get ?~ (mempty
48+ [ ("/users", mempty & pathItemGet ?~ (mempty
68− & produces ?~ MimeList ["application/json"]
49+ & operationProduces ?~ MimeList ["application/json"]
69− & at 200 ?~ Inline userSummaryResponse))
50+ & operationResponses .~ (mempty
51+ & responsesResponses . at 200 ?~ Inline (mempty & responseSchema ?~ userSummarySchemaRef))))
70− , ("/user/{username}", mempty & get ?~ (mempty
52+ , ("/user/{username}", mempty & pathItemGet ?~ (mempty
71− & produces ?~ MimeList ["application/json"]
53+ & operationProduces ?~ MimeList ["application/json"]
72− & parameters .~ [ Inline $ mempty
54+ & operationParameters .~ [ Inline $ mempty
73− & name .~ "username"
55+ & paramName .~ "username"
74− & required ?~ True
56+ & paramRequired ?~ True
75− & schema .~ ParamOther (mempty
57+ & paramSchema .~ ParamOther (mempty
76− & in_ .~ ParamPath
58+ & paramOtherSchemaIn .~ ParamPath
77− & paramSchema .~ usernameParamSchema) ]
59+ & paramOtherSchemaParamSchema .~ usernameParamSchema) ]
78− & at 200 ?~ Inline userDetailedResponse))
60+ & operationResponses .~ (mempty
61+ & responsesResponses . at 200 ?~ Inline (mempty & responseSchema ?~ userDetailedSchemaRef))))
79− , ("/packages", mempty & get ?~ (mempty
62+ , ("/packages", mempty & pathItemGet ?~ (mempty
80− & produces ?~ MimeList ["application/json"]
63+ & operationProduces ?~ MimeList ["application/json"]
81− & at 200 ?~ Inline packagesResponse))
64+ & operationResponses .~ (mempty
65+ & responsesResponses . at 200 ?~ Inline (mempty & responseSchema ?~ packagesSchemaRef))))
82 ]
66 ]
83
67
84main :: IO ()
68main :: IO ()
hackage-docs.shdeleted−78
@@ -1,78 +0,0 @@
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"
include/overlapping-compat.hdeleted−8
@@ -1,8 +0,0 @@
1−#if __GLASGOW_HASKELL__ >= 710
2−#define OVERLAPPABLE_ {-# OVERLAPPABLE #-}
3−#define OVERLAPPING_ {-# OVERLAPPING #-}
4−#else
5−{-# LANGUAGE OverlappingInstances #-}
6−#define OVERLAPPABLE_
7−#define OVERLAPPING_
8−#endif
src/Data/Swagger.hs+23−159
@@ -1,9 +1,4 @@
1−{-# LANGUAGE CPP #-}
2-- |
1-- |
3−-- Module: Data.Swagger
4−-- Maintainer: Nickolay Kudasov <nickolay@getshoptv.com>
5−-- Stability: experimental
6−--
7-- Swagger™ is a project used to describe and document RESTful APIs.
2-- Swagger™ is a project used to describe and document RESTful APIs.
8--
3--
9-- The Swagger specification defines a set of files required to describe such an API.
4-- The Swagger specification defines a set of files required to describe such an API.
@@ -23,19 +18,10 @@ module Data.Swagger (
23 -- ** Schema specification
18 -- ** Schema specification
24 -- $schema
19 -- $schema
25
20
26− -- ** Manipulation
27− -- $manipulation
28−
29− -- ** Validation
30− -- $validation
31−
32 -- * Re-exports
21 -- * Re-exports
33 module Data.Swagger.Lens,
22 module Data.Swagger.Lens,
34− module Data.Swagger.Optics,
35− module Data.Swagger.Operation,
36 module Data.Swagger.ParamSchema,
23 module Data.Swagger.ParamSchema,
37 module Data.Swagger.Schema,
24 module Data.Swagger.Schema,
38− module Data.Swagger.Schema.Validation,
39
25
40 -- * Swagger specification
26 -- * Swagger specification
41 Swagger(..),
27 Swagger(..),
@@ -47,18 +33,17 @@ module Data.Swagger (
47 Contact(..),
33 Contact(..),
48 License(..),
34 License(..),
49
35
50− -- ** PathItem
36+ -- ** Paths
37+ Paths(..),
51 PathItem(..),
38 PathItem(..),
52
39
53 -- ** Operations
40 -- ** Operations
54− Operation(..),
55 Tag(..),
41 Tag(..),
56− TagName,
42+ Operation(..),
57
43
58 -- ** Types and formats
44 -- ** Types and formats
59 SwaggerType(..),
45 SwaggerType(..),
60 Format,
46 Format,
61− Definitions,
62 CollectionFormat(..),
47 CollectionFormat(..),
63
48
64 -- ** Parameters
49 -- ** Parameters
@@ -67,29 +52,24 @@ module Data.Swagger (
67 ParamOtherSchema(..),
52 ParamOtherSchema(..),
68 ParamLocation(..),
53 ParamLocation(..),
69 ParamName,
54 ParamName,
55+ Items(..),
70 Header(..),
56 Header(..),
71− HeaderName,
72 Example(..),
57 Example(..),
73
58
74 -- ** Schemas
59 -- ** Schemas
75 ParamSchema(..),
60 ParamSchema(..),
76 Schema(..),
61 Schema(..),
77− NamedSchema(..),
78 SwaggerItems(..),
62 SwaggerItems(..),
79 Xml(..),
63 Xml(..),
80− Pattern,
81− AdditionalProperties(..),
82
64
83 -- ** Responses
65 -- ** Responses
84 Responses(..),
66 Responses(..),
85 Response(..),
67 Response(..),
86− HttpStatusCode,
87
68
88 -- ** Security
69 -- ** Security
89 SecurityScheme(..),
70 SecurityScheme(..),
90 SecuritySchemeType(..),
71 SecuritySchemeType(..),
91 SecurityRequirement(..),
72 SecurityRequirement(..),
92− SecurityDefinitions(..),
93
73
94 -- *** API key
74 -- *** API key
95 ApiKeyParams(..),
75 ApiKeyParams(..),
@@ -114,11 +94,8 @@ module Data.Swagger (
114) where
94) where
115
95
116import Data.Swagger.Lens
96import Data.Swagger.Lens
117−import Data.Swagger.Optics ()
118−import Data.Swagger.Operation
119import Data.Swagger.ParamSchema
97import Data.Swagger.ParamSchema
120import Data.Swagger.Schema
98import Data.Swagger.Schema
121−import Data.Swagger.Schema.Validation
122
99
123import Data.Swagger.Internal
100import Data.Swagger.Internal
124
101
@@ -178,81 +155,35 @@ import Data.Swagger.Internal
178
155
179-- $lens
156-- $lens
180--
157--
181−-- Note: if you're working with the <https://hackage.haskell.org/package/optics optics> library, take a look at "Data.Swagger.Optics".
182−--
183-- Since @'Swagger'@ has a fairly complex structure, lenses and prisms are used
158-- Since @'Swagger'@ has a fairly complex structure, lenses and prisms are used
184−-- to work comfortably with it. In combination with @'Monoid'@ instances, lenses
159+-- to modify this structure. In combination with @'Monoid'@ instances, lenses
185−-- make it fairly simple to construct/modify any part of the specification:
160+-- also make it fairly simple to construct/modify any part of the specification:
186--
161--
187-- >>> :{
162-- >>> :{
188−-- encode $ (mempty :: Swagger)
163+-- encode $ mempty & pathsMap .~
189−-- & definitions .~ [ ("User", mempty & type_ ?~ SwaggerString) ]
190−-- & paths .~
191−-- [ ("/user", mempty & get ?~ (mempty
164+-- [ ("/user", mempty & pathItemGet ?~ (mempty
192−-- & produces ?~ MimeList ["application/json"]
165+-- & operationProduces ?~ MimeList ["application/json"]
193−-- & at 200 ?~ ("OK" & _Inline.schema ?~ Ref (Reference "User"))
166+-- & operationResponses .~ (mempty
194−-- & at 404 ?~ "User info not found")) ]
167+-- & responsesResponses . at 200 ?~ Inline (mempty & responseSchema ?~ Ref (Reference "#/definitions/User")))))]
195-- :}
168-- :}
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\"}}}"
169+-- "{\"/user\":{\"get\":{\"responses\":{\"200\":{\"schema\":{\"$ref\":\"#/definitions/#/definitions/User\"},\"description\":\"\"}},\"produces\":[\"application/json\"]}}}"
197--
170--
198−-- In the snippet above we declare an API with a single path @/user@. This path provides method @GET@
171+-- Since @'ParamSchema'@ is basically the /base schema specification/, a special
199−-- which produces @application/json@ output. It should respond with code @200@ and body specified
172+-- @'HasParamSchema'@ class has been introduced to generalize @'ParamSchema'@ lenses
200−-- by schema @User@ which is defined in @'definitions'@ property of swagger specification.
173+-- and allow them to be used by any type that has a @'ParamSchema'@:
201−-- Alternatively it may respond with code @404@ meaning that user info is not found.
202--
174--
203−-- For convenience, @swagger2@ uses /classy field lenses/. It means that
204−-- field accessor names can be overloaded for different types. One such
205−-- common field is @'description'@. Many components of a Swagger specification
206−-- can have descriptions, and you can use the same name for them:
207−--
208−-- >>> encode $ (mempty :: Response) & description .~ "No content"
209−-- "{\"description\":\"No content\"}"
210-- >>> :{
175-- >>> :{
211−-- encode $ (mempty :: Schema)
176+-- encode $ mempty
212−-- & type_ ?~ SwaggerBoolean
177+-- & schemaTitle ?~ "Email"
213−-- & description ?~ "To be or not to be"
178+-- & schemaType .~ SwaggerString
179+-- & schemaFormat ?~ "email"
214-- :}
180-- :}
215−-- "{\"description\":\"To be or not to be\",\"type\":\"boolean\"}"
181+-- "{\"format\":\"email\",\"title\":\"Email\",\"type\":\"string\"}"
216−--
217−-- @'ParamSchema'@ is basically the /base schema specification/ and many types contain it (see @'HasParamSchema'@).
218−-- So for convenience, all @'ParamSchema'@ fields are transitively made fields of the type that has it.
219−-- For example, you can use @'type_'@ to access @'SwaggerType'@ of @'Header'@ schema without having to use @'paramSchema'@:
220−--
221−-- >>> encode $ (mempty :: Header) & type_ ?~ SwaggerNumber
222−-- "{\"type\":\"number\"}"
223−--
224−-- Additionally, to simplify working with @'Response'@, both @'Operation'@ and @'Responses'@
225−-- have direct access to it via @'at' code@. Example:
226−--
227−-- >>> :{
228−-- encode $ (mempty :: Operation)
229−-- & at 404 ?~ "Not found"
230−-- :}
231−-- "{\"responses\":{\"404\":{\"description\":\"Not found\"}}}"
232−--
233−-- You might've noticed that @'type_'@ has an extra underscore in its name
234−-- compared to, say, @'description'@ field accessor.
235−-- This is because @type@ is a keyword in Haskell.
236−-- A few other field accessors are modified in this way:
237−--
238−-- - @'in_'@, @'type_'@, @'default_'@ (as keywords);
239−-- - @'maximum_'@, @'minimum_'@, @'head_'@ (as conflicting with @Prelude@);
240−-- - @'enum_'@ (as conflicting with @Control.Lens@).
241
182
242-- $schema
183-- $schema
243--
184--
244−-- @'ParamSchema'@ and @'Schema'@ are the two core types for data model specification.
245−--
246−-- @'ParamSchema' t@ specifies all the common properties, available for every data schema.
247−-- The @t@ parameter imposes some restrictions on @type@ and @items@ properties (see @'SwaggerType'@ and @'SwaggerItems'@).
248−--
249−-- @'Schema'@ is used for request and response bodies and allows specifying objects
250−-- with properties in addition to what @'ParamSchema'@ provides.
251−--
252−-- In most cases you will have a Haskell data type for which you would like to
253−-- define a corresponding schema. To facilitate this use case
254−-- @swagger2@ provides two classes for schema encoding.
185+-- This library provides two classes for schema encoding.
255−-- Both these classes provide means to encode /types/ as Swagger /schemas/.
186+-- Both these classes provide means to encode _types_ as Swagger _schemas_.
256--
187--
257-- @'ToParamSchema'@ is intended to be used for primitive API endpoint parameters,
188-- @'ToParamSchema'@ is intended to be used for primitive API endpoint parameters,
258-- such as query parameters, headers and URL path pieces.
189-- such as query parameters, headers and URL path pieces.
@@ -278,73 +209,6 @@ import Data.Swagger.Internal
278-- >>> encode (Person "David" 28)
209-- >>> encode (Person "David" 28)
279-- "{\"age\":28,\"name\":\"David\"}"
210-- "{\"age\":28,\"name\":\"David\"}"
280-- >>> encode $ toSchema (Proxy :: Proxy Person)
211-- >>> encode $ toSchema (Proxy :: Proxy Person)
281−-- "{\"required\":[\"name\",\"age\"],\"properties\":{\"name\":{\"type\":\"string\"},\"age\":{\"type\":\"integer\"}},\"type\":\"object\"}"
212+-- "{\"required\":[\"name\",\"age\"],\"type\":\"object\",\"properties\":{\"age\":{\"type\":\"integer\"},\"name\":{\"type\":\"string\"}}}"
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
336--
213--
337
214
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+10−91
@@ -2,33 +2,12 @@
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.
12module Data.Swagger.Declare where
5module Data.Swagger.Declare where
13
6
14−import Prelude ()
15−import Prelude.Compat
16−
17import Control.Monad
7import Control.Monad
18−import Control.Monad.Cont (ContT)
19−import Control.Monad.List (ListT)
20−import Control.Monad.Reader (ReaderT)
21import Control.Monad.Trans
8import 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
31import Data.Functor.Identity
9import Data.Functor.Identity
10+import Data.Monoid
32
11
33-- | A declare monad transformer parametrized by:
12-- | A declare monad transformer parametrized by:
34--
13--
@@ -45,22 +24,22 @@ import Data.Functor.Identity
45newtype DeclareT d m a = DeclareT { runDeclareT :: d -> m (d, a) }
24newtype DeclareT d m a = DeclareT { runDeclareT :: d -> m (d, a) }
46 deriving (Functor)
25 deriving (Functor)
47
26
48−instance (Applicative m, Monad m, Monoid d) => Applicative (DeclareT d m) where
27+instance (Monad m, Monoid d) => Applicative (DeclareT d m) where
49 pure x = DeclareT (\_ -> pure (mempty, x))
28 pure x = DeclareT (\_ -> pure (mempty, x))
50 DeclareT df <*> DeclareT dx = DeclareT $ \d -> do
29 DeclareT df <*> DeclareT dx = DeclareT $ \d -> do
51 ~(d', f) <- df d
30 ~(d', f) <- df d
52− ~(d'', x) <- dx (mappend d d')
31+ ~(d'', x) <- dx (d <> d')
53− return (mappend d' d'', f x)
32+ return (d' <> d'', f x)
54
33
55−instance (Applicative m, Monad m, Monoid d) => Monad (DeclareT d m) where
34+instance (Monad m, Monoid d) => Monad (DeclareT d m) where
56 return x = DeclareT (\_ -> pure (mempty, x))
35 return x = DeclareT (\_ -> pure (mempty, x))
57 DeclareT dx >>= f = DeclareT $ \d -> do
36 DeclareT dx >>= f = DeclareT $ \d -> do
58 ~(d', x) <- dx d
37 ~(d', x) <- dx d
59− ~(d'', y) <- runDeclareT (f x) (mappend d d')
38+ ~(d'', y) <- runDeclareT (f x) (d <> d')
60− return (mappend d' d'', y)
39+ return (d' <> d'', y)
61
40
62instance Monoid d => MonadTrans (DeclareT d) where
41instance Monoid d => MonadTrans (DeclareT d) where
63− lift m = DeclareT (\_ -> (,) mempty `liftM` m)
42+ lift m = DeclareT (\_ -> (,) mempty <$> m)
64
43
65-- |
44-- |
66-- Definitions of @declare@ and @look@ must satisfy the following laws:
45-- Definitions of @declare@ and @look@ must satisfy the following laws:
@@ -79,23 +58,16 @@ instance Monoid d => MonadTrans (DeclareT d) where
79-- [/@look@ as left identity/]
58-- [/@look@ as left identity/]
80-- @'look' >> m == m@
59-- @'look' >> m == m@
81-- for every @m@
60-- for every @m@
82−class (Applicative m, Monad m) => MonadDeclare d m | m -> d where
61+class Monad m => MonadDeclare d m | m -> d where
83 -- | @'declare' x@ is an action that produces the output @x@.
62 -- | @'declare' x@ is an action that produces the output @x@.
84 declare :: d -> m ()
63 declare :: d -> m ()
85 -- | @'look'@ is an action that returns all the output so far.
64 -- | @'look'@ is an action that returns all the output so far.
86 look :: m d
65 look :: m d
87
66
88−instance (Applicative m, Monad m, Monoid d) => MonadDeclare d (DeclareT d m) where
67+instance (Monad m, Monoid d) => MonadDeclare d (DeclareT d m) where
89 declare d = DeclareT (\_ -> return (d, ()))
68 declare d = DeclareT (\_ -> return (d, ()))
90 look = DeclareT (\d -> return (mempty, d))
69 look = DeclareT (\d -> return (mempty, d))
91
70
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−
99-- | Retrieve a function of all the output so far.
71-- | Retrieve a function of all the output so far.
100looks :: MonadDeclare d m => (d -> a) -> m a
72looks :: MonadDeclare d m => (d -> a) -> m a
101looks f = f <$> look
73looks f = f <$> look
@@ -144,56 +116,3 @@ execDeclare m = runIdentity . execDeclareT m
144undeclare :: Monoid d => Declare d a -> a
116undeclare :: Monoid d => Declare d a -> a
145undeclare = runIdentity . undeclareT
117undeclare = runIdentity . undeclareT
146
118
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+227−473
@@ -1,7 +1,4 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE DataKinds #-}
3{-# LANGUAGE DeriveDataTypeable #-}
1{-# LANGUAGE DeriveDataTypeable #-}
4−{-# LANGUAGE DeriveFunctor #-}
5{-# LANGUAGE DeriveGeneric #-}
2{-# LANGUAGE DeriveGeneric #-}
6{-# LANGUAGE DeriveTraversable #-}
3{-# LANGUAGE DeriveTraversable #-}
7{-# LANGUAGE FlexibleContexts #-}
4{-# LANGUAGE FlexibleContexts #-}
@@ -12,128 +9,89 @@
12{-# LANGUAGE RecordWildCards #-}
9{-# LANGUAGE RecordWildCards #-}
13{-# LANGUAGE ScopedTypeVariables #-}
10{-# LANGUAGE ScopedTypeVariables #-}
14{-# LANGUAGE StandaloneDeriving #-}
11{-# LANGUAGE StandaloneDeriving #-}
15−{-# LANGUAGE TemplateHaskell #-}
16−{-# LANGUAGE TypeFamilies #-}
17{-# LANGUAGE UndecidableInstances #-}
12{-# LANGUAGE UndecidableInstances #-}
18−#if __GLASGOW_HASKELL__ <710
19−{-# LANGUAGE PolyKinds #-}
20−#endif
21−#include "overlapping-compat.h"
22module Data.Swagger.Internal where
13module Data.Swagger.Internal where
23
14
24−import Prelude ()
25−import Prelude.Compat
26−
27−import Control.Lens ((&), (.~), (?~))
28import Control.Applicative
15import Control.Applicative
16+import Control.Monad
29import Data.Aeson
17import Data.Aeson
30import qualified Data.Aeson.Types as JSON
18import qualified Data.Aeson.Types as JSON
31import Data.Data (Data(..), Typeable, mkConstr, mkDataType, Fixity(..), Constr, DataType, constrIndex)
19import Data.Data (Data(..), Typeable, mkConstr, mkDataType, Fixity(..), Constr, DataType, constrIndex)
32−import Data.Hashable (Hashable)
20+import Data.HashMap.Strict (HashMap)
33import qualified Data.HashMap.Strict as HashMap
21import qualified Data.HashMap.Strict as HashMap
34−import Data.HashSet.InsOrd (InsOrdHashSet)
35import Data.Map (Map)
22import Data.Map (Map)
36import qualified Data.Map as Map
23import qualified Data.Map as Map
37−import Data.Monoid (Monoid (..))
24+import Data.Monoid
38−import Data.Semigroup.Compat (Semigroup (..))
39import Data.Scientific (Scientific)
25import Data.Scientific (Scientific)
40−import Data.String (IsString(..))
26+import Data.String (fromString)
41import Data.Text (Text)
27import Data.Text (Text)
42import qualified Data.Text as Text
28import qualified Data.Text as Text
43import GHC.Generics (Generic)
29import GHC.Generics (Generic)
44−import Network.Socket (HostName, PortNumber)
30+import Network (HostName, PortNumber)
45import Network.HTTP.Media (MediaType)
31import Network.HTTP.Media (MediaType)
46import Text.Read (readMaybe)
32import Text.Read (readMaybe)
47
33
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)
60import Data.Swagger.Internal.Utils
34import Data.Swagger.Internal.Utils
61
35
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−
73−-- | A list of definitions that can be used in references.
74−type Definitions = InsOrdHashMap Text
75−
76-- | This is the root document object for the API specification.
36-- | This is the root document object for the API specification.
77data Swagger = Swagger
37data Swagger = Swagger
78 { -- | Provides metadata about the API.
38 { -- | Provides metadata about the API.
79 -- The metadata can be used by the clients if needed.
39 -- The metadata can be used by the clients if needed.
80− _swaggerInfo :: Info
40+ _info :: Info
81
41
82 -- | The host (name or ip) serving the API. It MAY include a port.
42 -- | The host (name or ip) serving the API. It MAY include a port.
83 -- If the host is not included, the host serving the documentation is to be used (including the port).
43 -- If the host is not included, the host serving the documentation is to be used (including the port).
84− , _swaggerHost :: Maybe Host
44+ , _host :: Maybe Host
85
45
86 -- | The base path on which the API is served, which is relative to the host.
46 -- | The base path on which the API is served, which is relative to the host.
87 -- If it is not included, the API is served directly under the host.
47 -- If it is not included, the API is served directly under the host.
88 -- The value MUST start with a leading slash (/).
48 -- The value MUST start with a leading slash (/).
89− , _swaggerBasePath :: Maybe FilePath
49+ , _basePath :: Maybe FilePath
90
50
91 -- | The transfer protocol of the API.
51 -- | The transfer protocol of the API.
92 -- If the schemes is not included, the default scheme to be used is the one used to access the Swagger definition itself.
52 -- If the schemes is not included, the default scheme to be used is the one used to access the Swagger definition itself.
93− , _swaggerSchemes :: Maybe [Scheme]
53+ , _schemes :: Maybe [Scheme]
94
54
95 -- | A list of MIME types the APIs can consume.
55 -- | A list of MIME types the APIs can consume.
96 -- This is global to all APIs but can be overridden on specific API calls.
56 -- This is global to all APIs but can be overridden on specific API calls.
97− , _swaggerConsumes :: MimeList
57+ , _consumes :: MimeList
98
58
99 -- | A list of MIME types the APIs can produce.
59 -- | A list of MIME types the APIs can produce.
100− -- This is global to all APIs but can be overridden on specific API calls.
60+ -- This is global to all APIs but can be overridden on specific API calls.
101− , _swaggerProduces :: MimeList
61+ , _produces :: MimeList
102
62
103 -- | The available paths and operations for the API.
63 -- | The available paths and operations for the API.
104− -- Holds the relative paths to the individual endpoints.
64+ , _paths :: Paths
105− -- The path is appended to the @'basePath'@ in order to construct the full URL.
106− , _swaggerPaths :: InsOrdHashMap FilePath PathItem
107
65
108 -- | An object to hold data types produced and consumed by operations.
66 -- | An object to hold data types produced and consumed by operations.
109− , _swaggerDefinitions :: Definitions Schema
67+ , _definitions :: HashMap Text Schema
110
68
111 -- | An object to hold parameters that can be used across operations.
69 -- | An object to hold parameters that can be used across operations.
112 -- This property does not define global parameters for all operations.
70 -- This property does not define global parameters for all operations.
113− , _swaggerParameters :: Definitions Param
71+ , _parameters :: HashMap Text Param
114
72
115 -- | An object to hold responses that can be used across operations.
73 -- | An object to hold responses that can be used across operations.
116 -- This property does not define global responses for all operations.
74 -- This property does not define global responses for all operations.
117− , _swaggerResponses :: Definitions Response
75+ , _responses :: HashMap Text Response
118
76
119 -- | Security scheme definitions that can be used across the specification.
77 -- | Security scheme definitions that can be used across the specification.
120− , _swaggerSecurityDefinitions :: SecurityDefinitions
78+ , _securityDefinitions :: HashMap Text SecurityScheme
121
79
122 -- | A declaration of which security schemes are applied for the API as a whole.
80 -- | A declaration of which security schemes are applied for the API as a whole.
123 -- The list of values describes alternative security schemes that can be used
81 -- The list of values describes alternative security schemes that can be used
124 -- (that is, there is a logical OR between the security requirements).
82 -- (that is, there is a logical OR between the security requirements).
125 -- Individual operations can override this definition.
83 -- Individual operations can override this definition.
126− , _swaggerSecurity :: [SecurityRequirement]
84+ , _security :: [SecurityRequirement]
127
85
128 -- | A list of tags used by the specification with additional metadata.
86 -- | A list of tags used by the specification with additional metadata.
129 -- The order of the tags can be used to reflect on their order by the parsing tools.
87 -- The order of the tags can be used to reflect on their order by the parsing tools.
130 -- Not all tags that are used by the Operation Object must be declared.
88 -- Not all tags that are used by the Operation Object must be declared.
131 -- The tags that are not declared may be organized randomly or based on the tools' logic.
89 -- The tags that are not declared may be organized randomly or based on the tools' logic.
132 -- Each tag name in the list MUST be unique.
90 -- Each tag name in the list MUST be unique.
133− , _swaggerTags :: InsOrdHashSet Tag
91+ , _tags :: [Tag]
134
92
135 -- | Additional external documentation.
93 -- | Additional external documentation.
136− , _swaggerExternalDocs :: Maybe ExternalDocs
94+ , _externalDocs :: Maybe ExternalDocs
137 } deriving (Eq, Show, Generic, Data, Typeable)
95 } deriving (Eq, Show, Generic, Data, Typeable)
138
96
139-- | The object provides metadata about the API.
97-- | The object provides metadata about the API.
@@ -182,18 +140,12 @@ data License = License
182 , _licenseUrl :: Maybe URL
140 , _licenseUrl :: Maybe URL
183 } deriving (Eq, Show, Generic, Data, Typeable)
141 } deriving (Eq, Show, Generic, Data, Typeable)
184
142
185−instance IsString License where
186− fromString s = License (fromString s) Nothing
187−
188-- | The host (name or ip) serving the API. It MAY include a port.
143-- | The host (name or ip) serving the API. It MAY include a port.
189data Host = Host
144data Host = Host
190 { _hostName :: HostName -- ^ Host name.
145 { _hostName :: HostName -- ^ Host name.
191 , _hostPort :: Maybe PortNumber -- ^ Optional port.
146 , _hostPort :: Maybe PortNumber -- ^ Optional port.
192 } deriving (Eq, Show, Generic, Typeable)
147 } deriving (Eq, Show, Generic, Typeable)
193
148
194−instance IsString Host where
195− fromString s = Host s Nothing
196−
197hostConstr :: Constr
149hostConstr :: Constr
198hostConstr = mkConstr hostDataType "Host" [] Prefix
150hostConstr = mkConstr hostDataType "Host" [] Prefix
199
151
@@ -215,6 +167,13 @@ data Scheme
215 | Wss
167 | Wss
216 deriving (Eq, Show, Generic, Data, Typeable)
168 deriving (Eq, Show, Generic, Data, Typeable)
217
169
170+-- | The available paths and operations for the API.
171+data Paths = Paths
172+ { -- | Holds the relative paths to the individual endpoints.
173+ -- The path is appended to the @'basePath'@ in order to construct the full URL.
174+ _pathsMap :: HashMap FilePath PathItem
175+ } deriving (Eq, Show, Generic, Data, Typeable)
176+
218-- | Describes the operations available on a single path.
177-- | Describes the operations available on a single path.
219-- A @'PathItem'@ may be empty, due to ACL constraints.
178-- A @'PathItem'@ may be empty, due to ACL constraints.
220-- The path itself is still exposed to the documentation viewer
179-- The path itself is still exposed to the documentation viewer
@@ -252,7 +211,7 @@ data PathItem = PathItem
252data Operation = Operation
211data Operation = Operation
253 { -- | A list of tags for API documentation control.
212 { -- | A list of tags for API documentation control.
254 -- Tags can be used for logical grouping of operations by resources or any other qualifier.
213 -- Tags can be used for logical grouping of operations by resources or any other qualifier.
255− _operationTags :: InsOrdHashSet TagName
214+ _operationTags :: [Text]
256
215
257 -- | A short summary of what the operation does.
216 -- | A short summary of what the operation does.
258 -- For maximum readability in the swagger-ui, this field SHOULD be less than 120 characters.
217 -- For maximum readability in the swagger-ui, this field SHOULD be less than 120 characters.
@@ -309,7 +268,7 @@ data Operation = Operation
309 } deriving (Eq, Show, Generic, Data, Typeable)
268 } deriving (Eq, Show, Generic, Data, Typeable)
310
269
311newtype MimeList = MimeList { getMimeList :: [MediaType] }
270newtype MimeList = MimeList { getMimeList :: [MediaType] }
312− deriving (Eq, Show, Semigroup, Monoid, Typeable)
271+ deriving (Eq, Show, Monoid, Typeable)
313
272
314mimeListConstr :: Constr
273mimeListConstr :: Constr
315mimeListConstr = mkConstr mimeListDataType "MimeList" ["getMimeList"] Prefix
274mimeListConstr = mkConstr mimeListDataType "MimeList" ["getMimeList"] Prefix
@@ -360,92 +319,36 @@ data ParamOtherSchema = ParamOtherSchema
360 -- Default value is @False@.
319 -- Default value is @False@.
361 , _paramOtherSchemaAllowEmptyValue :: Maybe Bool
320 , _paramOtherSchemaAllowEmptyValue :: Maybe Bool
362
321
322+ -- | Determines the format of the array if @'ParamArray'@ is used.
323+ -- Default value is csv.
324+ , _paramOtherSchemaCollectionFormat :: Maybe (CollectionFormat Param)
325+
363− , _paramOtherSchemaParamSchema :: ParamSchema 'SwaggerKindParamOtherSchema
326+ , _paramOtherSchemaParamSchema :: ParamSchema ParamOtherSchema
364− } deriving (Eq, Show, Generic, Typeable, Data)
327+ } deriving (Eq, Show, Generic, Data, Typeable)
365−
328+
366−-- | Items for @'SwaggerArray'@ schemas.
367−--
368−-- @'SwaggerItemsPrimitive'@ should be used only for query params, headers and path pieces.
369−-- The @'CollectionFormat' t@ parameter specifies how elements of an array should be displayed.
370−-- Note that @fmt@ in @'SwaggerItemsPrimitive' fmt schema@ specifies format for elements of type @schema@.
371−-- This is different from the original Swagger's <http://swagger.io/specification/#itemsObject Items Object>.
372−--
373−-- @'SwaggerItemsObject'@ should be used to specify homogenous array @'Schema'@s.
374−--
375−-- @'SwaggerItemsArray'@ should be used to specify tuple @'Schema'@s.
376data SwaggerItems t where
329data SwaggerItems t where
377− SwaggerItemsPrimitive :: Maybe (CollectionFormat k) -> ParamSchema k-> SwaggerItems k
330+ SwaggerItemsPrimitive :: Items -> SwaggerItems t
378− SwaggerItemsObject :: Referenced Schema -> SwaggerItems 'SwaggerKindSchema
331+ SwaggerItemsObject :: Referenced Schema -> SwaggerItems Schema
379− SwaggerItemsArray :: [Referenced Schema] -> SwaggerItems 'SwaggerKindSchema
332+ SwaggerItemsArray :: [Referenced Schema] -> SwaggerItems Schema
380− deriving (Typeable)
381
333
382deriving instance Eq (SwaggerItems t)
334deriving instance Eq (SwaggerItems t)
383deriving instance Show (SwaggerItems t)
335deriving instance Show (SwaggerItems t)
384−--deriving instance Typeable (SwaggerItems t)
336+deriving instance Typeable (SwaggerItems t)
385
337
386swaggerItemsPrimitiveConstr :: Constr
338swaggerItemsPrimitiveConstr :: Constr
387swaggerItemsPrimitiveConstr = mkConstr swaggerItemsDataType "SwaggerItemsPrimitive" [] Prefix
339swaggerItemsPrimitiveConstr = mkConstr swaggerItemsDataType "SwaggerItemsPrimitive" [] Prefix
388
340
389−swaggerItemsObjectConstr :: Constr
390−swaggerItemsObjectConstr = mkConstr swaggerItemsDataType "SwaggerItemsObject" [] Prefix
391−
392−swaggerItemsArrayConstr :: Constr
393−swaggerItemsArrayConstr = mkConstr swaggerItemsDataType "SwaggerItemsArray" [] Prefix
394−
395swaggerItemsDataType :: DataType
341swaggerItemsDataType :: DataType
396swaggerItemsDataType = mkDataType "Data.Swagger.SwaggerItems" [swaggerItemsPrimitiveConstr]
342swaggerItemsDataType = mkDataType "Data.Swagger.SwaggerItems" [swaggerItemsPrimitiveConstr]
397
343
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−
401−instance Data t => Data (SwaggerItems ('SwaggerKindNormal t)) where
344+instance {-# OVERLAPPABLE #-} Typeable t => Data (SwaggerItems t) where
402− -- TODO: define gfoldl
403 gunfold k z c = case constrIndex c of
345 gunfold k z c = case constrIndex c of
404− 1 -> k (k (z SwaggerItemsPrimitive))
346+ 1 -> k (z SwaggerItemsPrimitive)
405 _ -> error $ "Data.Data.gunfold: Constructor " ++ show c ++ " is not of type (SwaggerItems t)."
347 _ -> error $ "Data.Data.gunfold: Constructor " ++ show c ++ " is not of type (SwaggerItems t)."
406 toConstr _ = swaggerItemsPrimitiveConstr
348 toConstr _ = swaggerItemsPrimitiveConstr
407 dataTypeOf _ = swaggerItemsDataType
349 dataTypeOf _ = swaggerItemsDataType
408
350
409−-- SwaggerItems SwaggerKindParamOtherSchema can be constructed using SwaggerItemsPrimitive only
410−instance Data (SwaggerItems 'SwaggerKindParamOtherSchema) where
351+deriving instance Data (SwaggerItems Schema)
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
449
352
450data SwaggerType t where
353data SwaggerType t where
451 SwaggerString :: SwaggerType t
354 SwaggerString :: SwaggerType t
@@ -453,44 +356,44 @@ data SwaggerType t where
453 SwaggerInteger :: SwaggerType t
356 SwaggerInteger :: SwaggerType t
454 SwaggerBoolean :: SwaggerType t
357 SwaggerBoolean :: SwaggerType t
455 SwaggerArray :: SwaggerType t
358 SwaggerArray :: SwaggerType t
456− SwaggerFile :: SwaggerType 'SwaggerKindParamOtherSchema
359+ SwaggerFile :: SwaggerType ParamOtherSchema
457− SwaggerNull :: SwaggerType 'SwaggerKindSchema
360+ SwaggerNull :: SwaggerType Schema
458− SwaggerObject :: SwaggerType 'SwaggerKindSchema
361+ SwaggerObject :: SwaggerType Schema
459− deriving (Typeable)
460
362
461deriving instance Eq (SwaggerType t)
363deriving instance Eq (SwaggerType t)
462deriving instance Show (SwaggerType t)
364deriving instance Show (SwaggerType t)
365+deriving instance Typeable (SwaggerType t)
463
366
464swaggerTypeConstr :: Data (SwaggerType t) => SwaggerType t -> Constr
367swaggerTypeConstr :: Data (SwaggerType t) => SwaggerType t -> Constr
465swaggerTypeConstr t = mkConstr (dataTypeOf t) (show t) [] Prefix
368swaggerTypeConstr t = mkConstr (dataTypeOf t) (show t) [] Prefix
466
369
467−swaggerTypeDataType :: {- Data (SwaggerType t) => -} SwaggerType t -> DataType
370+swaggerTypeDataType :: Data (SwaggerType t) => SwaggerType t -> DataType
468swaggerTypeDataType _ = mkDataType "Data.Swagger.SwaggerType" swaggerTypeConstrs
371swaggerTypeDataType _ = mkDataType "Data.Swagger.SwaggerType" swaggerTypeConstrs
469
372
470−swaggerCommonTypes :: [SwaggerType k]
373+swaggerCommonTypes :: [SwaggerType t]
471swaggerCommonTypes = [SwaggerString, SwaggerNumber, SwaggerInteger, SwaggerBoolean, SwaggerArray]
374swaggerCommonTypes = [SwaggerString, SwaggerNumber, SwaggerInteger, SwaggerBoolean, SwaggerArray]
472
375
473−swaggerParamTypes :: [SwaggerType 'SwaggerKindParamOtherSchema]
376+swaggerParamTypes :: [SwaggerType ParamOtherSchema]
474swaggerParamTypes = swaggerCommonTypes ++ [SwaggerFile]
377swaggerParamTypes = swaggerCommonTypes ++ [SwaggerFile]
475
378
476−swaggerSchemaTypes :: [SwaggerType 'SwaggerKindSchema]
379+swaggerSchemaTypes :: [SwaggerType Schema]
477swaggerSchemaTypes = swaggerCommonTypes ++ [error "SwaggerFile is invalid SwaggerType Schema", SwaggerNull, SwaggerObject]
380swaggerSchemaTypes = swaggerCommonTypes ++ [error "SwaggerFile is invalid SwaggerType Schema", SwaggerNull, SwaggerObject]
478
381
479swaggerTypeConstrs :: [Constr]
382swaggerTypeConstrs :: [Constr]
480−swaggerTypeConstrs = map swaggerTypeConstr (swaggerCommonTypes :: [SwaggerType 'SwaggerKindSchema])
383+swaggerTypeConstrs = map swaggerTypeConstr (swaggerCommonTypes :: [SwaggerType Schema])
481 ++ [swaggerTypeConstr SwaggerFile, swaggerTypeConstr SwaggerNull, swaggerTypeConstr SwaggerObject]
384 ++ [swaggerTypeConstr SwaggerFile, swaggerTypeConstr SwaggerNull, swaggerTypeConstr SwaggerObject]
482
385
483−instance Typeable t => Data (SwaggerType ('SwaggerKindNormal t)) where
386+instance {-# OVERLAPPABLE #-} Typeable t => Data (SwaggerType t) where
484 gunfold = gunfoldEnum "SwaggerType" swaggerCommonTypes
387 gunfold = gunfoldEnum "SwaggerType" swaggerCommonTypes
485 toConstr = swaggerTypeConstr
388 toConstr = swaggerTypeConstr
486 dataTypeOf = swaggerTypeDataType
389 dataTypeOf = swaggerTypeDataType
487
390
488−instance Data (SwaggerType 'SwaggerKindParamOtherSchema) where
391+instance {-# OVERLAPPING #-} Data (SwaggerType ParamOtherSchema) where
489 gunfold = gunfoldEnum "SwaggerType ParamOtherSchema" swaggerParamTypes
392 gunfold = gunfoldEnum "SwaggerType ParamOtherSchema" swaggerParamTypes
490 toConstr = swaggerTypeConstr
393 toConstr = swaggerTypeConstr
491 dataTypeOf = swaggerTypeDataType
394 dataTypeOf = swaggerTypeDataType
492
395
493−instance Data (SwaggerType 'SwaggerKindSchema) where
396+instance {-# OVERLAPPING #-} Data (SwaggerType Schema) where
494 gunfold = gunfoldEnum "SwaggerType Schema" swaggerSchemaTypes
397 gunfold = gunfoldEnum "SwaggerType Schema" swaggerSchemaTypes
495 toConstr = swaggerTypeConstr
398 toConstr = swaggerTypeConstr
496 dataTypeOf = swaggerTypeDataType
399 dataTypeOf = swaggerTypeDataType
@@ -530,11 +433,11 @@ data CollectionFormat t where
530 -- Corresponds to multiple parameter instances
433 -- Corresponds to multiple parameter instances
531 -- instead of multiple values for a single instance @foo=bar&foo=baz@.
434 -- instead of multiple values for a single instance @foo=bar&foo=baz@.
532 -- This is valid only for parameters in @'ParamQuery'@ or @'ParamFormData'@.
435 -- This is valid only for parameters in @'ParamQuery'@ or @'ParamFormData'@.
533− CollectionMulti :: CollectionFormat 'SwaggerKindParamOtherSchema
436+ CollectionMulti :: CollectionFormat Param
534− deriving (Typeable)
535
437
536deriving instance Eq (CollectionFormat t)
438deriving instance Eq (CollectionFormat t)
537deriving instance Show (CollectionFormat t)
439deriving instance Show (CollectionFormat t)
440+deriving instance Typeable (CollectionFormat t)
538
441
539collectionFormatConstr :: CollectionFormat t -> Constr
442collectionFormatConstr :: CollectionFormat t -> Constr
540collectionFormatConstr cf = mkConstr collectionFormatDataType (show cf) [] Prefix
443collectionFormatConstr cf = mkConstr collectionFormatDataType (show cf) [] Prefix
@@ -546,12 +449,12 @@ collectionFormatDataType = mkDataType "Data.Swagger.CollectionFormat" $
546collectionCommonFormats :: [CollectionFormat t]
449collectionCommonFormats :: [CollectionFormat t]
547collectionCommonFormats = [ CollectionCSV, CollectionSSV, CollectionTSV, CollectionPipes ]
450collectionCommonFormats = [ CollectionCSV, CollectionSSV, CollectionTSV, CollectionPipes ]
548
451
549−instance Data t => Data (CollectionFormat ('SwaggerKindNormal t)) where
452+instance {-# OVERLAPPABLE #-} Data t => Data (CollectionFormat t) where
550 gunfold = gunfoldEnum "CollectionFormat" collectionCommonFormats
453 gunfold = gunfoldEnum "CollectionFormat" collectionCommonFormats
551 toConstr = collectionFormatConstr
454 toConstr = collectionFormatConstr
552 dataTypeOf _ = collectionFormatDataType
455 dataTypeOf _ = collectionFormatDataType
553
456
554−deriving instance Data (CollectionFormat 'SwaggerKindParamOtherSchema)
457+deriving instance {-# OVERLAPPING #-} Data (CollectionFormat Param)
555
458
556type ParamName = Text
459type ParamName = Text
557
460
@@ -560,9 +463,9 @@ data Schema = Schema
560 , _schemaDescription :: Maybe Text
463 , _schemaDescription :: Maybe Text
561 , _schemaRequired :: [ParamName]
464 , _schemaRequired :: [ParamName]
562
465
563− , _schemaAllOf :: Maybe [Referenced Schema]
466+ , _schemaAllOf :: Maybe [Schema]
564− , _schemaProperties :: InsOrdHashMap Text (Referenced Schema)
467+ , _schemaProperties :: HashMap Text (Referenced Schema)
565− , _schemaAdditionalProperties :: Maybe AdditionalProperties
468+ , _schemaAdditionalProperties :: Maybe Schema
566
469
567 , _schemaDiscriminator :: Maybe Text
470 , _schemaDiscriminator :: Maybe Text
568 , _schemaReadOnly :: Maybe Bool
471 , _schemaReadOnly :: Maybe Bool
@@ -573,20 +476,10 @@ data Schema = Schema
573 , _schemaMaxProperties :: Maybe Integer
476 , _schemaMaxProperties :: Maybe Integer
574 , _schemaMinProperties :: Maybe Integer
477 , _schemaMinProperties :: Maybe Integer
575
478
576− , _schemaParamSchema :: ParamSchema 'SwaggerKindSchema
479+ , _schemaParamSchema :: ParamSchema Schema
577− } deriving (Eq, Show, Generic, Data, Typeable)
578−
579−-- | A @'Schema'@ with an optional name.
580−-- This name can be used in references.
581−data NamedSchema = NamedSchema
582− { _namedSchemaName :: Maybe Text
583− , _namedSchemaSchema :: Schema
584 } deriving (Eq, Show, Generic, Data, Typeable)
480 } deriving (Eq, Show, Generic, Data, Typeable)
585
481
586−-- | Regex pattern for @string@ type.
587−type Pattern = Text
588−
589−data ParamSchema (t :: SwaggerKind *) = ParamSchema
482+data ParamSchema t = ParamSchema
590 { -- | Declares the value of the parameter that the server will use if none is provided,
483 { -- | Declares the value of the parameter that the server will use if none is provided,
591 -- for example a @"count"@ to control the number of results per page might default to @100@
484 -- for example a @"count"@ to control the number of results per page might default to @100@
592 -- if not supplied by the client in the request.
485 -- if not supplied by the client in the request.
@@ -594,7 +487,7 @@ data ParamSchema (t :: SwaggerKind *) = ParamSchema
594 -- Unlike JSON Schema this value MUST conform to the defined type for this parameter.
487 -- Unlike JSON Schema this value MUST conform to the defined type for this parameter.
595 _paramSchemaDefault :: Maybe Value
488 _paramSchemaDefault :: Maybe Value
596
489
597− , _paramSchemaType :: Maybe (SwaggerType t)
490+ , _paramSchemaType :: SwaggerType t
598 , _paramSchemaFormat :: Maybe Format
491 , _paramSchemaFormat :: Maybe Format
599 , _paramSchemaItems :: Maybe (SwaggerItems t)
492 , _paramSchemaItems :: Maybe (SwaggerItems t)
600 , _paramSchemaMaximum :: Maybe Scientific
493 , _paramSchemaMaximum :: Maybe Scientific
@@ -603,7 +496,7 @@ data ParamSchema (t :: SwaggerKind *) = ParamSchema
603 , _paramSchemaExclusiveMinimum :: Maybe Bool
496 , _paramSchemaExclusiveMinimum :: Maybe Bool
604 , _paramSchemaMaxLength :: Maybe Integer
497 , _paramSchemaMaxLength :: Maybe Integer
605 , _paramSchemaMinLength :: Maybe Integer
498 , _paramSchemaMinLength :: Maybe Integer
606− , _paramSchemaPattern :: Maybe Pattern
499+ , _paramSchemaPattern :: Maybe Text
607 , _paramSchemaMaxItems :: Maybe Integer
500 , _paramSchemaMaxItems :: Maybe Integer
608 , _paramSchemaMinItems :: Maybe Integer
501 , _paramSchemaMinItems :: Maybe Integer
609 , _paramSchemaUniqueItems :: Maybe Bool
502 , _paramSchemaUniqueItems :: Maybe Bool
@@ -611,11 +504,11 @@ data ParamSchema (t :: SwaggerKind *) = ParamSchema
611 , _paramSchemaMultipleOf :: Maybe Scientific
504 , _paramSchemaMultipleOf :: Maybe Scientific
612 } deriving (Eq, Show, Generic, Typeable)
505 } deriving (Eq, Show, Generic, Typeable)
613
506
614−deriving instance (Typeable k, Data (Maybe (SwaggerType k)), Data (SwaggerItems k)) => Data (ParamSchema k)
507+deriving instance (Data t, Data (SwaggerType t), Data (SwaggerItems t)) => Data (ParamSchema t)
615
508
616data Xml = Xml
509data Xml = Xml
617 { -- | Replaces the name of the element/attribute used for the described schema property.
510 { -- | Replaces the name of the element/attribute used for the described schema property.
618− -- When defined within the @'SwaggerItems'@ (items), it will affect the name of the individual XML elements within the list.
511+ -- When defined within the @'Items'@ (items), it will affect the name of the individual XML elements within the list.
619 -- When defined alongside type being array (outside the items),
512 -- When defined alongside type being array (outside the items),
620 -- it will affect the wrapping element and only if wrapped is true.
513 -- it will affect the wrapping element and only if wrapped is true.
621 -- If wrapped is false, it will be ignored.
514 -- If wrapped is false, it will be ignored.
@@ -641,6 +534,14 @@ data Xml = Xml
641 , _xmlWrapped :: Maybe Bool
534 , _xmlWrapped :: Maybe Bool
642 } deriving (Eq, Show, Generic, Data, Typeable)
535 } deriving (Eq, Show, Generic, Data, Typeable)
643
536
537+data Items = Items
538+ { -- | Determines the format of the array if type array is used.
539+ -- Default value is @'ItemsCollectionCSV'@.
540+ _itemsCollectionFormat :: Maybe (CollectionFormat Items)
541+
542+ , _itemsParamSchema :: ParamSchema Items
543+ } deriving (Eq, Show, Generic, Data, Typeable)
544+
644-- | A container for the expected responses of an operation.
545-- | A container for the expected responses of an operation.
645-- The container maps a HTTP response code to the expected response.
546-- The container maps a HTTP response code to the expected response.
646-- It is not expected from the documentation to necessarily cover all possible HTTP response codes,
547-- It is not expected from the documentation to necessarily cover all possible HTTP response codes,
@@ -653,7 +554,7 @@ data Responses = Responses
653
554
654 -- | Any HTTP status code can be used as the property name (one property per HTTP status code).
555 -- | Any HTTP status code can be used as the property name (one property per HTTP status code).
655 -- Describes the expected response for those HTTP status codes.
556 -- Describes the expected response for those HTTP status codes.
656− , _responsesResponses :: InsOrdHashMap HttpStatusCode (Referenced Response)
557+ , _responsesResponses :: HashMap HttpStatusCode (Referenced Response)
657 } deriving (Eq, Show, Generic, Data, Typeable)
558 } deriving (Eq, Show, Generic, Data, Typeable)
658
559
659type HttpStatusCode = Int
560type HttpStatusCode = Int
@@ -672,22 +573,23 @@ data Response = Response
672 , _responseSchema :: Maybe (Referenced Schema)
573 , _responseSchema :: Maybe (Referenced Schema)
673
574
674 -- | A list of headers that are sent with the response.
575 -- | A list of headers that are sent with the response.
675− , _responseHeaders :: InsOrdHashMap HeaderName Header
576+ , _responseHeaders :: HashMap HeaderName Header
676
577
677 -- | An example of the response message.
578 -- | An example of the response message.
678 , _responseExamples :: Maybe Example
579 , _responseExamples :: Maybe Example
679 } deriving (Eq, Show, Generic, Data, Typeable)
580 } deriving (Eq, Show, Generic, Data, Typeable)
680
581
681−instance IsString Response where
682− fromString s = Response (fromString s) Nothing mempty Nothing
683−
684type HeaderName = Text
582type HeaderName = Text
685
583
686data Header = Header
584data Header = Header
687 { -- | A short description of the header.
585 { -- | A short description of the header.
688 _headerDescription :: Maybe Text
586 _headerDescription :: Maybe Text
689
587
588+ -- | Determines the format of the array if type array is used.
589+ -- Default value is @'ItemsCollectionCSV'@.
590+ , _headerCollectionFormat :: Maybe (CollectionFormat Items)
591+
690− , _headerParamSchema :: ParamSchema ('SwaggerKindNormal Header)
592+ , _headerParamSchema :: ParamSchema Header
691 } deriving (Eq, Show, Generic, Data, Typeable)
593 } deriving (Eq, Show, Generic, Data, Typeable)
692
594
693data Example = Example { getExample :: Map MediaType Value }
595data Example = Example { getExample :: Map MediaType Value }
@@ -738,7 +640,7 @@ data OAuth2Params = OAuth2Params
738 _oauth2Flow :: OAuth2Flow
640 _oauth2Flow :: OAuth2Flow
739
641
740 -- | The available scopes for the OAuth2 security scheme.
642 -- | The available scopes for the OAuth2 security scheme.
741− , _oauth2Scopes :: InsOrdHashMap Text Text
643+ , _oauth2Scopes :: HashMap Text Text
742 } deriving (Eq, Show, Generic, Data, Typeable)
644 } deriving (Eq, Show, Generic, Data, Typeable)
743
645
744data SecuritySchemeType
646data SecuritySchemeType
@@ -755,37 +657,18 @@ data SecurityScheme = SecurityScheme
755 , _securitySchemeDescription :: Maybe Text
657 , _securitySchemeDescription :: Maybe Text
756 } deriving (Eq, Show, Generic, Data, Typeable)
658 } deriving (Eq, Show, Generic, Data, Typeable)
757
659
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−
774-- | Lists the required security schemes to execute this operation.
660-- | Lists the required security schemes to execute this operation.
775-- The object can have multiple security schemes declared in it which are all required
661-- The object can have multiple security schemes declared in it which are all required
776-- (that is, there is a logical AND between the schemes).
662-- (that is, there is a logical AND between the schemes).
777newtype SecurityRequirement = SecurityRequirement
663newtype SecurityRequirement = SecurityRequirement
778− { getSecurityRequirement :: InsOrdHashMap Text [Text]
664+ { getSecurityRequirement :: HashMap Text [Text]
779− } deriving (Eq, Read, Show, Semigroup, Monoid, ToJSON, FromJSON, Data, Typeable)
665+ } deriving (Eq, Read, Show, Monoid, ToJSON, FromJSON, Data, Typeable)
780−
781−-- | Tag name.
782−type TagName = Text
783
666
784-- | Allows adding meta data to a single tag that is used by @Operation@.
667-- | Allows adding meta data to a single tag that is used by @Operation@.
785-- It is not mandatory to have a @Tag@ per tag used there.
668-- It is not mandatory to have a @Tag@ per tag used there.
786data Tag = Tag
669data Tag = Tag
787 { -- | The name of the tag.
670 { -- | The name of the tag.
788− _tagName :: TagName
671+ _tagName :: Text
789
672
790 -- | A short description for the tag.
673 -- | A short description for the tag.
791 -- GFM syntax can be used for rich text representation.
674 -- GFM syntax can be used for rich text representation.
@@ -793,12 +676,7 @@ data Tag = Tag
793
676
794 -- | Additional external documentation for this tag.
677 -- | Additional external documentation for this tag.
795 , _tagExternalDocs :: Maybe ExternalDocs
678 , _tagExternalDocs :: Maybe ExternalDocs
796− } deriving (Eq, Ord, Show, Generic, Data, Typeable)
679+ } deriving (Eq, Show, Generic, Data, Typeable)
797−
798−instance Hashable Tag
799−
800−instance IsString Tag where
801− fromString s = Tag (fromString s) Nothing Nothing
802
680
803-- | Allows referencing an external resource for extended documentation.
681-- | Allows referencing an external resource for extended documentation.
804data ExternalDocs = ExternalDocs
682data ExternalDocs = ExternalDocs
@@ -808,9 +686,7 @@ data ExternalDocs = ExternalDocs
808
686
809 -- | The URL for the target documentation.
687 -- | The URL for the target documentation.
810 , _externalDocsUrl :: URL
688 , _externalDocsUrl :: URL
811− } deriving (Eq, Ord, Show, Generic, Data, Typeable)
689+ } deriving (Eq, Show, Generic, Data, Typeable)
812−
813−instance Hashable ExternalDocs
814
690
815-- | A simple object to allow referencing other definitions in the specification.
691-- | A simple object to allow referencing other definitions in the specification.
816-- It can be used to reference parameters and responses that are defined at the top level for reuse.
692-- It can be used to reference parameters and responses that are defined at the top level for reuse.
@@ -820,122 +696,68 @@ newtype Reference = Reference { getReference :: Text }
820data Referenced a
696data Referenced a
821 = Ref Reference
697 = Ref Reference
822 | Inline a
698 | Inline a
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)
829−
830−data AdditionalProperties
831− = AdditionalPropertiesAllowed Bool
832− | AdditionalPropertiesSchema (Referenced Schema)
833 deriving (Eq, Show, Data, Typeable)
699 deriving (Eq, Show, Data, Typeable)
834
700
701+newtype URL = URL { getUrl :: Text } deriving (Eq, Show, ToJSON, FromJSON, Data, Typeable)
702+
835-- =======================================================================
703-- =======================================================================
836-- Monoid instances
704-- Monoid instances
837-- =======================================================================
705-- =======================================================================
838
706
839−instance Semigroup Swagger where
840− (<>) = genericMappend
841instance Monoid Swagger where
707instance Monoid Swagger where
842 mempty = genericMempty
708 mempty = genericMempty
843− mappend = (<>)
709+ mappend = genericMappend
844
710
845−instance Semigroup Info where
846− (<>) = genericMappend
847instance Monoid Info where
711instance Monoid Info where
848 mempty = genericMempty
712 mempty = genericMempty
849− mappend = (<>)
713+ mappend = genericMappend
850
714
851−instance Semigroup Contact where
852− (<>) = genericMappend
853−instance Monoid Contact where
715+instance Monoid Paths where
854 mempty = genericMempty
716 mempty = genericMempty
855− mappend = (<>)
717+ mappend = genericMappend
856
718
857−instance Semigroup PathItem where
858− (<>) = genericMappend
859instance Monoid PathItem where
719instance Monoid PathItem where
860 mempty = genericMempty
720 mempty = genericMempty
861− mappend = (<>)
721+ mappend = genericMappend
862
722
863−instance Semigroup Schema where
864− (<>) = genericMappend
865instance Monoid Schema where
723instance Monoid Schema where
866 mempty = genericMempty
724 mempty = genericMempty
867− mappend = (<>)
725+ mappend = genericMappend
868
726
869−instance Semigroup (ParamSchema t) where
870− (<>) = genericMappend
871instance Monoid (ParamSchema t) where
727instance Monoid (ParamSchema t) where
872 mempty = genericMempty
728 mempty = genericMempty
873− mappend = (<>)
729+ mappend = genericMappend
874
730
875−instance Semigroup Param where
876− (<>) = genericMappend
877instance Monoid Param where
731instance Monoid Param where
878 mempty = genericMempty
732 mempty = genericMempty
879− mappend = (<>)
733+ mappend = genericMappend
880
734
881−instance Semigroup ParamOtherSchema where
882− (<>) = genericMappend
883instance Monoid ParamOtherSchema where
735instance Monoid ParamOtherSchema where
884 mempty = genericMempty
736 mempty = genericMempty
885− mappend = (<>)
737+ mappend = genericMappend
886
738
887−instance Semigroup Header where
888− (<>) = genericMappend
889−instance Monoid Header where
890− mempty = genericMempty
891− mappend = (<>)
892−
893−instance Semigroup Responses where
894− (<>) = genericMappend
895instance Monoid Responses where
739instance Monoid Responses where
896 mempty = genericMempty
740 mempty = genericMempty
897− mappend = (<>)
741+ mappend = genericMappend
898
742
899−instance Semigroup Response where
900− (<>) = genericMappend
901instance Monoid Response where
743instance Monoid Response where
902 mempty = genericMempty
744 mempty = genericMempty
903− mappend = (<>)
745+ mappend = genericMappend
904
746
905−instance Semigroup ExternalDocs where
906− (<>) = genericMappend
907instance Monoid ExternalDocs where
747instance Monoid ExternalDocs where
908 mempty = genericMempty
748 mempty = genericMempty
909− mappend = (<>)
749+ mappend = genericMappend
910
750
911−instance Semigroup Operation where
912− (<>) = genericMappend
913instance Monoid Operation where
751instance Monoid Operation where
914 mempty = genericMempty
752 mempty = genericMempty
915− mappend = (<>)
916−
917−instance Semigroup Example where
918− (<>) = genericMappend
753+ mappend = genericMappend
919−instance Monoid Example where
920− mempty = genericMempty
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 = (<>)
933
754
934-- =======================================================================
755-- =======================================================================
935-- SwaggerMonoid helper instances
756-- SwaggerMonoid helper instances
936-- =======================================================================
757-- =======================================================================
937
758
938instance SwaggerMonoid Info
759instance SwaggerMonoid Info
760+instance SwaggerMonoid Paths
939instance SwaggerMonoid PathItem
761instance SwaggerMonoid PathItem
940instance SwaggerMonoid Schema
762instance SwaggerMonoid Schema
941instance SwaggerMonoid (ParamSchema t)
763instance SwaggerMonoid (ParamSchema t)
@@ -945,8 +767,6 @@ instance SwaggerMonoid Responses
945instance SwaggerMonoid Response
767instance SwaggerMonoid Response
946instance SwaggerMonoid ExternalDocs
768instance SwaggerMonoid ExternalDocs
947instance SwaggerMonoid Operation
769instance SwaggerMonoid Operation
948−instance SwaggerMonoid SecurityDefinitions
949−instance (Eq a, Hashable a) => SwaggerMonoid (InsOrdHashSet a)
950
770
951instance SwaggerMonoid MimeList
771instance SwaggerMonoid MimeList
952deriving instance SwaggerMonoid URL
772deriving instance SwaggerMonoid URL
@@ -959,15 +779,43 @@ instance SwaggerMonoid ParamLocation where
959 swaggerMempty = ParamQuery
779 swaggerMempty = ParamQuery
960 swaggerMappend _ y = y
780 swaggerMappend _ y = y
961
781
962−instance OVERLAPPING_ SwaggerMonoid (InsOrdHashMap FilePath PathItem) where
782+instance SwaggerMonoid (HashMap Text Schema) where
963− swaggerMempty = InsOrdHashMap.empty
783+ swaggerMempty = HashMap.empty
964− swaggerMappend = InsOrdHashMap.unionWith mappend
784+ swaggerMappend = HashMap.unionWith mappend
785+
786+instance SwaggerMonoid (HashMap Text (Referenced Schema)) where
787+ swaggerMempty = HashMap.empty
788+ swaggerMappend = HashMap.unionWith swaggerMappend
965
789
966instance Monoid a => SwaggerMonoid (Referenced a) where
790instance Monoid a => SwaggerMonoid (Referenced a) where
967 swaggerMempty = Inline mempty
791 swaggerMempty = Inline mempty
968− swaggerMappend (Inline x) (Inline y) = Inline (mappend x y)
792+ swaggerMappend (Inline x) (Inline y) = Inline (x <> y)
969 swaggerMappend _ y = y
793 swaggerMappend _ y = y
970
794
795+instance SwaggerMonoid (HashMap Text Param) where
796+ swaggerMempty = HashMap.empty
797+ swaggerMappend = HashMap.unionWith mappend
798+
799+instance SwaggerMonoid (HashMap Text Response) where
800+ swaggerMempty = HashMap.empty
801+ swaggerMappend = flip HashMap.union
802+
803+instance SwaggerMonoid (HashMap Text SecurityScheme) where
804+ swaggerMempty = HashMap.empty
805+ swaggerMappend = flip HashMap.union
806+
807+instance SwaggerMonoid (HashMap FilePath PathItem) where
808+ swaggerMempty = HashMap.empty
809+ swaggerMappend = HashMap.unionWith mappend
810+
811+instance SwaggerMonoid (HashMap HeaderName Header) where
812+ swaggerMempty = HashMap.empty
813+ swaggerMappend = flip HashMap.union
814+
815+instance SwaggerMonoid (HashMap HttpStatusCode (Referenced Response)) where
816+ swaggerMempty = HashMap.empty
817+ swaggerMappend = flip HashMap.union
818+
971instance SwaggerMonoid ParamAnySchema where
819instance SwaggerMonoid ParamAnySchema where
972 swaggerMempty = ParamOther swaggerMempty
820 swaggerMempty = ParamOther swaggerMempty
973 swaggerMappend (ParamBody x) (ParamBody y) = ParamBody (swaggerMappend x y)
821 swaggerMappend (ParamBody x) (ParamBody y) = ParamBody (swaggerMappend x y)
@@ -1059,8 +907,7 @@ instance ToJSON OAuth2Flow where
1059 , "tokenUrl" .= tokenUrl ]
907 , "tokenUrl" .= tokenUrl ]
1060
908
1061instance ToJSON OAuth2Params where
909instance ToJSON OAuth2Params where
1062− toJSON = sopSwaggerGenericToJSON
910+ toJSON = omitEmpties . genericToJSONWithSub "flow" (jsonPrefix "oauth2")
1063− DEFINE_TOENCODING
1064
911
1065instance ToJSON SecuritySchemeType where
912instance ToJSON SecuritySchemeType where
1066 toJSON SecuritySchemeBasic
913 toJSON SecuritySchemeBasic
@@ -1073,38 +920,27 @@ instance ToJSON SecuritySchemeType where
1073 <+> object [ "type" .= ("oauth2" :: Text) ]
920 <+> object [ "type" .= ("oauth2" :: Text) ]
1074
921
1075instance ToJSON Swagger where
922instance ToJSON Swagger where
1076− toJSON = sopSwaggerGenericToJSON
923+ toJSON = omitEmpties . addVersion . genericToJSON (jsonPrefix "")
1077− DEFINE_TOENCODING
924+ where
925+ addVersion (Object o) = Object (HashMap.insert "swagger" "2.0" o)
926+ addVersion _ = error "impossible"
1078
927
1079instance ToJSON SecurityScheme where
928instance ToJSON SecurityScheme where
1080− toJSON = sopSwaggerGenericToJSON
929+ toJSON = genericToJSONWithSub "type" (jsonPrefix "securityScheme")
1081− DEFINE_TOENCODING
1082
930
1083instance ToJSON Schema where
931instance ToJSON Schema where
1084− toJSON = sopSwaggerGenericToJSON
932+ toJSON = omitEmpties . genericToJSONWithSub "paramSchema" (jsonPrefix "schema")
1085− DEFINE_TOENCODING
1086
933
1087instance ToJSON Header where
934instance ToJSON Header where
1088− toJSON = sopSwaggerGenericToJSON
935+ toJSON = genericToJSONWithSub "paramSchema" (jsonPrefix "header")
1089− DEFINE_TOENCODING
936+
1090−
937+instance ToJSON Items where
1091−-- | As for nullary schema for 0-arity type constructors, see
938+ toJSON = genericToJSONWithSub "paramSchema" (jsonPrefix "items")
1092−-- <https://github.com/GetShopTV/swagger2/issues/167>.
939+
1093−--
1094−-- >>> encode (SwaggerItemsArray [])
1095−-- "{\"example\":[],\"items\":{},\"maxItems\":0}"
1096−--
1097−instance ToJSON (ParamSchema t) => ToJSON (SwaggerItems t) where
940+instance ToJSON (SwaggerItems t) where
1098− toJSON (SwaggerItemsPrimitive fmt schema) = object
941+ toJSON (SwaggerItemsPrimitive x) = toJSON x
1099− [ "collectionFormat" .= fmt
1100− , "items" .= schema ]
1101− toJSON (SwaggerItemsObject x) = object [ "items" .= x ]
942+ toJSON (SwaggerItemsObject x) = toJSON x
1102− toJSON (SwaggerItemsArray []) = object
943+ toJSON (SwaggerItemsArray x) = toJSON x
1103− [ "items" .= object []
1104− , "maxItems" .= (0 :: Int)
1105− , "example" .= Array mempty
1106− ]
1107− toJSON (SwaggerItemsArray x) = object [ "items" .= x ]
1108
944
1109instance ToJSON Host where
945instance ToJSON Host where
1110 toJSON (Host host mport) = toJSON $
946 toJSON (Host host mport) = toJSON $
@@ -1112,43 +948,38 @@ instance ToJSON Host where
1112 Nothing -> host
948 Nothing -> host
1113 Just port -> host ++ ":" ++ show port
949 Just port -> host ++ ":" ++ show port
1114
950
951+instance ToJSON Paths where
952+ toJSON (Paths m) = toJSON m
953+
1115instance ToJSON MimeList where
954instance ToJSON MimeList where
1116 toJSON (MimeList xs) = toJSON (map show xs)
955 toJSON (MimeList xs) = toJSON (map show xs)
1117
956
1118instance ToJSON Param where
957instance ToJSON Param where
1119− toJSON = sopSwaggerGenericToJSON
958+ toJSON = genericToJSONWithSub "schema" (jsonPrefix "param")
1120− DEFINE_TOENCODING
1121
959
1122instance ToJSON ParamAnySchema where
960instance ToJSON ParamAnySchema where
1123 toJSON (ParamBody s) = object [ "in" .= ("body" :: Text), "schema" .= s ]
961 toJSON (ParamBody s) = object [ "in" .= ("body" :: Text), "schema" .= s ]
1124 toJSON (ParamOther s) = toJSON s
962 toJSON (ParamOther s) = toJSON s
1125
963
1126instance ToJSON ParamOtherSchema where
964instance ToJSON ParamOtherSchema where
1127− toJSON = sopSwaggerGenericToJSON
965+ toJSON = genericToJSONWithSub "paramSchema" (jsonPrefix "paramOtherSchema")
1128− DEFINE_TOENCODING
1129
966
1130instance ToJSON Responses where
967instance ToJSON Responses where
1131− toJSON = sopSwaggerGenericToJSON
968+ toJSON (Responses def rs) = omitEmpties $
1132− DEFINE_TOENCODING
969+ toJSON (hashMapMapKeys show rs) <+> object [ "default" .= def ]
1133
970
1134instance ToJSON Response where
971instance ToJSON Response where
1135− toJSON = sopSwaggerGenericToJSON
972+ toJSON = omitEmpties . genericToJSON (jsonPrefix "response")
1136− DEFINE_TOENCODING
1137
973
1138instance ToJSON Operation where
974instance ToJSON Operation where
1139− toJSON = sopSwaggerGenericToJSON
975+ toJSON = omitEmpties . genericToJSON (jsonPrefix "operation")
1140− DEFINE_TOENCODING
1141
976
1142instance ToJSON PathItem where
977instance ToJSON PathItem where
1143− toJSON = sopSwaggerGenericToJSON
978+ toJSON = omitEmpties . genericToJSON (jsonPrefix "pathItem")
1144− DEFINE_TOENCODING
1145
979
1146instance ToJSON Example where
980instance ToJSON Example where
1147 toJSON = toJSON . Map.mapKeys show . getExample
981 toJSON = toJSON . Map.mapKeys show . getExample
1148
982
1149−instance ToJSON SecurityDefinitions where
1150− toJSON (SecurityDefinitions sd) = toJSON sd
1151−
1152instance ToJSON Reference where
983instance ToJSON Reference where
1153 toJSON (Reference ref) = object [ "$ref" .= ref ]
984 toJSON (Reference ref) = object [ "$ref" .= ref ]
1154
985
@@ -1177,14 +1008,8 @@ instance ToJSON (CollectionFormat t) where
1177 toJSON CollectionPipes = "pipes"
1008 toJSON CollectionPipes = "pipes"
1178 toJSON CollectionMulti = "multi"
1009 toJSON CollectionMulti = "multi"
1179
1010
1180−instance ToJSON (ParamSchema k) where
1011+instance ToJSON (ParamSchema t) where
1181− -- TODO: this is a bit fishy, why we need sub object only in `ToJSON`?
1012+ toJSON = genericToJSON (jsonPrefix "paramSchema")
1182− toJSON = sopSwaggerGenericToJSONWithOpts $
1183− mkSwaggerAesonOptions "paramSchema" & saoSubObject ?~ "items"
1184−
1185−instance ToJSON AdditionalProperties where
1186− toJSON (AdditionalPropertiesAllowed b) = toJSON b
1187− toJSON (AdditionalPropertiesSchema s) = toJSON s
1188
1013
1189-- =======================================================================
1014-- =======================================================================
1190-- Manual FromJSON instances
1015-- Manual FromJSON instances
@@ -1204,7 +1029,7 @@ instance FromJSON OAuth2Flow where
1204 parseJSON _ = empty
1029 parseJSON _ = empty
1205
1030
1206instance FromJSON OAuth2Params where
1031instance FromJSON OAuth2Params where
1207− parseJSON = sopSwaggerGenericParseJSON
1032+ parseJSON = genericParseJSONWithSub "flow" (jsonPrefix "oauth2")
1208
1033
1209instance FromJSON SecuritySchemeType where
1034instance FromJSON SecuritySchemeType where
1210 parseJSON js@(Object o) = do
1035 parseJSON js@(Object o) = do
@@ -1217,65 +1042,61 @@ instance FromJSON SecuritySchemeType where
1217 parseJSON _ = empty
1042 parseJSON _ = empty
1218
1043
1219instance FromJSON Swagger where
1044instance FromJSON Swagger where
1220− parseJSON = sopSwaggerGenericParseJSON
1045+ parseJSON js@(Object o) = do
1046+ (version :: Text) <- o .: "swagger"
1047+ when (version /= "2.0") empty
1048+ (genericParseJSON (jsonPrefix "")
1049+ `withDefaults` [ "consumes" .= (mempty :: MimeList)
1050+ , "produces" .= (mempty :: MimeList)
1051+ , "security" .= ([] :: [SecurityRequirement])
1052+ , "tags" .= ([] :: [Tag])
1053+ , "definitions" .= (mempty :: HashMap Text Schema)
1054+ , "parameters" .= (mempty :: HashMap Text Param)
1055+ , "responses" .= (mempty :: HashMap Text Response)
1056+ , "securityDefinitions" .= (mempty :: HashMap Text SecurityScheme)
1057+ ] ) js
1058+ parseJSON _ = empty
1221
1059
1222instance FromJSON SecurityScheme where
1060instance FromJSON SecurityScheme where
1223− parseJSON = sopSwaggerGenericParseJSON
1061+ parseJSON = genericParseJSONWithSub "type" (jsonPrefix "securityScheme")
1224
1062
1225instance FromJSON Schema where
1063instance FromJSON Schema where
1226− parseJSON = fmap nullaryCleanup . sopSwaggerGenericParseJSON
1064+ parseJSON = genericParseJSONWithSub "paramSchema" (jsonPrefix "schema")
1227− where nullaryCleanup :: Schema -> Schema
1065+ `withDefaults` [ "properties" .= (mempty :: HashMap Text Schema)
1228− nullaryCleanup s@Schema{_schemaParamSchema=ps} =
1066+ , "required" .= ([] :: [ParamName]) ]
1229− if _paramSchemaItems ps == Just (SwaggerItemsArray [])
1230− then s { _schemaExample = Nothing
1231− , _schemaParamSchema = ps { _paramSchemaMaxItems = Nothing } }
1232− else s
1233
1067
1234instance FromJSON Header where
1068instance FromJSON Header where
1235− parseJSON = sopSwaggerGenericParseJSON
1069+ parseJSON = genericParseJSONWithSub "paramSchema" (jsonPrefix "header")
1236−
1070+
1237−instance (FromJSON (CollectionFormat ('SwaggerKindNormal t)), FromJSON (ParamSchema ('SwaggerKindNormal t))) => FromJSON (SwaggerItems ('SwaggerKindNormal t)) where
1238− parseJSON = withObject "SwaggerItemsPrimitive" $ \o -> SwaggerItemsPrimitive
1239− <$> o .:? "collectionFormat"
1240− <*> (o .: "items" >>= parseJSON)
1241−
1242−instance FromJSON (SwaggerItems 'SwaggerKindParamOtherSchema) where
1071+instance FromJSON Items where
1243− parseJSON = withObject "SwaggerItemsPrimitive" $ \o -> SwaggerItemsPrimitive
1072+ parseJSON = genericParseJSONWithSub "paramSchema" (jsonPrefix "items")
1244− <$> o .:? "collectionFormat"
1073+
1245− <*> ((o .: "items" >>= parseJSON) <|> fail ("foo" ++ show o))
1074+instance {-# OVERLAPPABLE #-} FromJSON (SwaggerItems t) where
1246−
1075+ parseJSON js = SwaggerItemsPrimitive <$> parseJSON js
1247−-- |
1076+
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−--
1258−instance FromJSON (SwaggerItems 'SwaggerKindSchema) where
1077+instance {-# OVERLAPPING #-} FromJSON (SwaggerItems Schema) where
1259− parseJSON js@(Object obj)
1260− | null obj = pure $ SwaggerItemsArray [] -- Nullary schema.
1261− | otherwise = SwaggerItemsObject <$> parseJSON js
1078+ parseJSON js@(Object _) = SwaggerItemsObject <$> parseJSON js
1262 parseJSON js@(Array _) = SwaggerItemsArray <$> parseJSON js
1079 parseJSON js@(Array _) = SwaggerItemsArray <$> parseJSON js
1263 parseJSON _ = empty
1080 parseJSON _ = empty
1264
1081
1265instance FromJSON Host where
1082instance FromJSON Host where
1266− parseJSON (String s) = case map Text.unpack $ Text.split (== ':') s of
1083+ parseJSON (String s) =
1267− [host] -> return $ Host host Nothing
1084+ case fromInteger <$> readMaybe portStr of
1268− [host, port] -> case readMaybe port of
1085+ Nothing | not (null portStr) -> fail $ "Invalid port `" ++ portStr ++ "'"
1269− Nothing -> fail $ "Invalid port `" ++ port ++ "'"
1086+ mport -> pure $ Host host mport
1270− Just p -> return $ Host host (Just (fromInteger p))
1087+ where
1271− _ -> fail $ "Invalid host `" ++ Text.unpack s ++ "'"
1088+ (hostText, portText) = Text.breakOn ":" s
1089+ [host, portStr] = map Text.unpack [hostText, portText]
1272 parseJSON _ = empty
1090 parseJSON _ = empty
1273
1091
1092+instance FromJSON Paths where
1093+ parseJSON js = Paths <$> parseJSON js
1094+
1274instance FromJSON MimeList where
1095instance FromJSON MimeList where
1275 parseJSON js = (MimeList . map fromString) <$> parseJSON js
1096 parseJSON js = (MimeList . map fromString) <$> parseJSON js
1276
1097
1277instance FromJSON Param where
1098instance FromJSON Param where
1278− parseJSON = sopSwaggerGenericParseJSON
1099+ parseJSON = genericParseJSONWithSub "schema" (jsonPrefix "param")
1279
1100
1280instance FromJSON ParamAnySchema where
1101instance FromJSON ParamAnySchema where
1281 parseJSON js@(Object o) = do
1102 parseJSON js@(Object o) = do
@@ -1288,12 +1109,12 @@ instance FromJSON ParamAnySchema where
1288 parseJSON _ = empty
1109 parseJSON _ = empty
1289
1110
1290instance FromJSON ParamOtherSchema where
1111instance FromJSON ParamOtherSchema where
1291− parseJSON = sopSwaggerGenericParseJSON
1112+ parseJSON = genericParseJSONWithSub "paramSchema" (jsonPrefix "paramOtherSchema")
1292
1113
1293instance FromJSON Responses where
1114instance FromJSON Responses where
1294 parseJSON (Object o) = Responses
1115 parseJSON (Object o) = Responses
1295 <$> o .:? "default"
1116 <$> o .:? "default"
1296− <*> (parseJSON (Object (HashMap.delete "default" o)))
1117+ <*> (parseJSON (Object (HashMap.delete "default" o)) >>= hashMapReadKeys)
1297 parseJSON _ = empty
1118 parseJSON _ = empty
1298
1119
1299instance FromJSON Example where
1120instance FromJSON Example where
@@ -1302,16 +1123,16 @@ instance FromJSON Example where
1302 pure $ Example (Map.mapKeys fromString m)
1123 pure $ Example (Map.mapKeys fromString m)
1303
1124
1304instance FromJSON Response where
1125instance FromJSON Response where
1305− parseJSON = sopSwaggerGenericParseJSON
1126+ parseJSON = genericParseJSON (jsonPrefix "response")
1127+ `withDefaults` [ "headers" .= (mempty :: HashMap HeaderName Header) ]
1306
1128
1307instance FromJSON Operation where
1129instance FromJSON Operation where
1308− parseJSON = sopSwaggerGenericParseJSON
1130+ parseJSON = genericParseJSON (jsonPrefix "operation")
1131+ `withDefaults` [ "security" .= ([] :: [SecurityRequirement]) ]
1309
1132
1310instance FromJSON PathItem where
1133instance FromJSON PathItem where
1311− parseJSON = sopSwaggerGenericParseJSON
1134+ parseJSON = genericParseJSON (jsonPrefix "pathItem")
1312−
1135+ `withDefaults` [ "parameters" .= ([] :: [Param]) ]
1313−instance FromJSON SecurityDefinitions where
1314− parseJSON js = SecurityDefinitions <$> parseJSON js
1315
1136
1316instance FromJSON Reference where
1137instance FromJSON Reference where
1317 parseJSON (Object o) = Reference <$> o .: "$ref"
1138 parseJSON (Object o) = Reference <$> o .: "$ref"
@@ -1328,7 +1149,6 @@ referencedParseJSON prefix js@(Object o) = do
1328 case Text.stripPrefix prefix s of
1149 case Text.stripPrefix prefix s of
1329 Nothing -> fail $ "expected $ref of the form \"" <> Text.unpack prefix <> "*\", but got " <> show s
1150 Nothing -> fail $ "expected $ref of the form \"" <> Text.unpack prefix <> "*\", but got " <> show s
1330 Just suffix -> pure (Reference suffix)
1151 Just suffix -> pure (Reference suffix)
1331−referencedParseJSON _ _ = fail "referenceParseJSON: not an object"
1332
1152
1333instance FromJSON (Referenced Schema) where parseJSON = referencedParseJSON "#/definitions/"
1153instance FromJSON (Referenced Schema) where parseJSON = referencedParseJSON "#/definitions/"
1334instance FromJSON (Referenced Param) where parseJSON = referencedParseJSON "#/parameters/"
1154instance FromJSON (Referenced Param) where parseJSON = referencedParseJSON "#/parameters/"
@@ -1337,91 +1157,25 @@ instance FromJSON (Referenced Response) where parseJSON = referencedParseJSON "#
1337instance FromJSON Xml where
1157instance FromJSON Xml where
1338 parseJSON = genericParseJSON (jsonPrefix "xml")
1158 parseJSON = genericParseJSON (jsonPrefix "xml")
1339
1159
1340−instance FromJSON (SwaggerType 'SwaggerKindSchema) where
1160+instance FromJSON (SwaggerType Schema) where
1341 parseJSON = parseOneOf [SwaggerString, SwaggerInteger, SwaggerNumber, SwaggerBoolean, SwaggerArray, SwaggerNull, SwaggerObject]
1161 parseJSON = parseOneOf [SwaggerString, SwaggerInteger, SwaggerNumber, SwaggerBoolean, SwaggerArray, SwaggerNull, SwaggerObject]
1342
1162
1343−instance FromJSON (SwaggerType 'SwaggerKindParamOtherSchema) where
1163+instance FromJSON (SwaggerType ParamOtherSchema) where
1344 parseJSON = parseOneOf [SwaggerString, SwaggerInteger, SwaggerNumber, SwaggerBoolean, SwaggerArray, SwaggerFile]
1164 parseJSON = parseOneOf [SwaggerString, SwaggerInteger, SwaggerNumber, SwaggerBoolean, SwaggerArray, SwaggerFile]
1345
1165
1346−instance FromJSON (SwaggerType ('SwaggerKindNormal t)) where
1166+instance {-# OVERLAPPABLE #-} FromJSON (SwaggerType t) where
1347 parseJSON = parseOneOf [SwaggerString, SwaggerInteger, SwaggerNumber, SwaggerBoolean, SwaggerArray]
1167 parseJSON = parseOneOf [SwaggerString, SwaggerInteger, SwaggerNumber, SwaggerBoolean, SwaggerArray]
1348
1168
1349−instance FromJSON (CollectionFormat ('SwaggerKindNormal t)) where
1169+instance FromJSON (CollectionFormat Param) where
1350− parseJSON = parseOneOf [CollectionCSV, CollectionSSV, CollectionTSV, CollectionPipes]
1351−
1352−-- NOTE: There aren't collections of 'Schema'
1353−--instance FromJSON (CollectionFormat (SwaggerKindSchema)) where
1354−-- parseJSON = parseOneOf [CollectionCSV, CollectionSSV, CollectionTSV, CollectionPipes]
1355−
1356−instance FromJSON (CollectionFormat 'SwaggerKindParamOtherSchema) where
1357 parseJSON = parseOneOf [CollectionCSV, CollectionSSV, CollectionTSV, CollectionPipes, CollectionMulti]
1170 parseJSON = parseOneOf [CollectionCSV, CollectionSSV, CollectionTSV, CollectionPipes, CollectionMulti]
1358
1171
1359−instance (FromJSON (SwaggerType ('SwaggerKindNormal t)), FromJSON (SwaggerItems ('SwaggerKindNormal t))) => FromJSON (ParamSchema ('SwaggerKindNormal t)) where
1172+instance FromJSON (CollectionFormat Items) where
1360− parseJSON = sopSwaggerGenericParseJSON
1173+ parseJSON = parseOneOf [CollectionCSV, CollectionSSV, CollectionTSV, CollectionPipes]
1361−instance FromJSON (ParamSchema 'SwaggerKindParamOtherSchema) where
1174+
1362− parseJSON = sopSwaggerGenericParseJSON
1175+-- NOTE: The constraints @FromJSON (SwaggerType t)@ and
1363−instance FromJSON (ParamSchema 'SwaggerKindSchema) where
1176+-- @FromJSON (SwaggerItems t)@ are necessary here!
1364− parseJSON = sopSwaggerGenericParseJSON
1177+-- Without the constraint the general instance will be used
1365−
1178+-- that only accepts common types (i.e. NOT object, null or file)
1366−instance FromJSON AdditionalProperties where
1179+-- and primitive array items.
1367− parseJSON (Bool b) = pure $ AdditionalPropertiesAllowed b
1180+instance (FromJSON (SwaggerType t), FromJSON (SwaggerItems t)) => FromJSON (ParamSchema t) where
1368− parseJSON js = AdditionalPropertiesSchema <$> parseJSON js
1181+ parseJSON = genericParseJSON (jsonPrefix "ParamSchema")
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.hsdeleted−346
@@ -1,346 +0,0 @@
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+40−163
@@ -1,80 +1,31 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE DataKinds #-}
3{-# LANGUAGE DefaultSignatures #-}
1{-# LANGUAGE DefaultSignatures #-}
4{-# LANGUAGE FlexibleContexts #-}
2{-# LANGUAGE FlexibleContexts #-}
5{-# LANGUAGE FlexibleInstances #-}
3{-# LANGUAGE FlexibleInstances #-}
6{-# LANGUAGE KindSignatures #-}
4{-# LANGUAGE KindSignatures #-}
7{-# LANGUAGE OverloadedStrings #-}
5{-# LANGUAGE OverloadedStrings #-}
8−{-# LANGUAGE PackageImports #-}
9{-# LANGUAGE PolyKinds #-}
6{-# LANGUAGE PolyKinds #-}
10{-# LANGUAGE ScopedTypeVariables #-}
7{-# LANGUAGE ScopedTypeVariables #-}
11−{-# LANGUAGE TypeFamilies #-}
12{-# LANGUAGE TypeOperators #-}
8{-# LANGUAGE TypeOperators #-}
13{-# LANGUAGE TypeSynonymInstances #-}
9{-# 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
21−#include "overlapping-compat.h"
22module Data.Swagger.Internal.ParamSchema where
10module Data.Swagger.Internal.ParamSchema where
23
11
24import Control.Lens
12import Control.Lens
25−import Data.Aeson (ToJSON (..))
13+import Data.Aeson
26import Data.Proxy
14import Data.Proxy
27import GHC.Generics
15import GHC.Generics
28
16
29import Data.Int
17import Data.Int
30−import "unordered-containers" Data.HashSet (HashSet)
31import Data.Monoid
18import Data.Monoid
32−import Data.Set (Set)
33import Data.Scientific
19import Data.Scientific
34−import Data.Fixed (HasResolution(..), Fixed, Pico)
35import qualified Data.Text as T
20import qualified Data.Text as T
36import qualified Data.Text.Lazy as TL
21import qualified Data.Text.Lazy as TL
37import Data.Time
22import 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)
44import Data.Word
23import Data.Word
45−import Data.UUID.Types (UUID)
46−import Web.Cookie (SetCookie)
47
24
48import Data.Swagger.Internal
25import Data.Swagger.Internal
49import Data.Swagger.Lens
26import Data.Swagger.Lens
50import Data.Swagger.SchemaOptions
27import Data.Swagger.SchemaOptions
51
28
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−
78-- | Convert a type into a plain @'ParamSchema'@.
29-- | Convert a type into a plain @'ParamSchema'@.
79--
30--
80-- An example type and instance:
31-- An example type and instance:
@@ -87,9 +38,9 @@ passwordParamSchema = mempty
87-- data Direction = Up | Down
38-- data Direction = Up | Down
88--
39--
89-- instance ToParamSchema Direction where
40-- instance ToParamSchema Direction where
90−-- toParamSchema _ = mempty
41+-- toParamSchema = mempty
91−-- & type_ ?~ SwaggerString
42+-- & schemaType .~ SwaggerString
92−-- & enum_ ?~ [ \"Up\", \"Down\" ]
43+-- & schemaEnum .~ [ \"Up\", \"Down\" ]
93-- @
44-- @
94--
45--
95-- Instead of manually writing your @'ToParamSchema'@ instance you can
46-- Instead of manually writing your @'ToParamSchema'@ instance you can
@@ -115,34 +66,24 @@ class ToParamSchema a where
115 --
66 --
116 -- >>> encode $ toParamSchema (Proxy :: Proxy Integer)
67 -- >>> encode $ toParamSchema (Proxy :: Proxy Integer)
117 -- "{\"type\":\"integer\"}"
68 -- "{\"type\":\"integer\"}"
118− toParamSchema :: Proxy a -> ParamSchema t
69+ toParamSchema :: proxy a -> ParamSchema t
119− default toParamSchema :: (Generic a, GToParamSchema (Rep a)) => Proxy a -> ParamSchema t
70+ default toParamSchema :: (Generic a, GToParamSchema (Rep a)) => proxy a -> ParamSchema t
120 toParamSchema = genericToParamSchema defaultSchemaOptions
71 toParamSchema = genericToParamSchema defaultSchemaOptions
121
72
122−instance OVERLAPPING_ ToParamSchema String where
73+instance {-# OVERLAPPING #-} ToParamSchema String where
123− toParamSchema _ = mempty & type_ ?~ SwaggerString
74+ toParamSchema _ = mempty & schemaType .~ SwaggerString
124
75
125instance ToParamSchema Bool where
76instance ToParamSchema Bool where
126− toParamSchema _ = mempty & type_ ?~ SwaggerBoolean
77+ toParamSchema _ = mempty & schemaType .~ SwaggerBoolean
127
78
128instance ToParamSchema Integer where
79instance ToParamSchema Integer where
129− toParamSchema _ = mempty & type_ ?~ SwaggerInteger
80+ toParamSchema _ = mempty & schemaType .~ SwaggerInteger
130−
131−instance ToParamSchema Natural where
132− toParamSchema _ = mempty
133− & type_ ?~ SwaggerInteger
134− & minimum_ ?~ 0
135− & exclusiveMinimum ?~ False
136
81
137instance ToParamSchema Int where toParamSchema = toParamSchemaBoundedIntegral
82instance ToParamSchema Int where toParamSchema = toParamSchemaBoundedIntegral
138instance ToParamSchema Int8 where toParamSchema = toParamSchemaBoundedIntegral
83instance ToParamSchema Int8 where toParamSchema = toParamSchemaBoundedIntegral
139instance ToParamSchema Int16 where toParamSchema = toParamSchemaBoundedIntegral
84instance ToParamSchema Int16 where toParamSchema = toParamSchemaBoundedIntegral
140−
141−instance ToParamSchema Int32 where
142− toParamSchema proxy = toParamSchemaBoundedIntegral proxy & format ?~ "int32"
85+instance ToParamSchema Int32 where toParamSchema = toParamSchemaBoundedIntegral
143−
144−instance ToParamSchema Int64 where
145− toParamSchema proxy = toParamSchemaBoundedIntegral proxy & format ?~ "int64"
86+instance ToParamSchema Int64 where toParamSchema = toParamSchemaBoundedIntegral
146
87
147instance ToParamSchema Word where toParamSchema = toParamSchemaBoundedIntegral
88instance ToParamSchema Word where toParamSchema = toParamSchemaBoundedIntegral
148instance ToParamSchema Word8 where toParamSchema = toParamSchemaBoundedIntegral
89instance ToParamSchema Word8 where toParamSchema = toParamSchemaBoundedIntegral
@@ -154,71 +95,58 @@ instance ToParamSchema Word64 where toParamSchema = toParamSchemaBoundedIntegral
154--
95--
155-- >>> encode $ toParamSchemaBoundedIntegral (Proxy :: Proxy Int8)
96-- >>> encode $ toParamSchemaBoundedIntegral (Proxy :: Proxy Int8)
156-- "{\"maximum\":127,\"minimum\":-128,\"type\":\"integer\"}"
97-- "{\"maximum\":127,\"minimum\":-128,\"type\":\"integer\"}"
157−toParamSchemaBoundedIntegral :: forall a t. (Bounded a, Integral a) => Proxy a -> ParamSchema t
98+toParamSchemaBoundedIntegral :: forall proxy a t. (Bounded a, Integral a) => proxy a -> ParamSchema t
158toParamSchemaBoundedIntegral _ = mempty
99toParamSchemaBoundedIntegral _ = mempty
159− & type_ ?~ SwaggerInteger
100+ & schemaType .~ SwaggerInteger
160− & minimum_ ?~ fromInteger (toInteger (minBound :: a))
101+ & schemaMinimum ?~ fromInteger (toInteger (minBound :: a))
161− & maximum_ ?~ fromInteger (toInteger (maxBound :: a))
102+ & schemaMaximum ?~ fromInteger (toInteger (maxBound :: a))
162
103
163instance ToParamSchema Char where
104instance ToParamSchema Char where
164 toParamSchema _ = mempty
105 toParamSchema _ = mempty
165− & type_ ?~ SwaggerString
106+ & schemaType .~ SwaggerString
166− & maxLength ?~ 1
107+ & schemaMaxLength ?~ 1
167− & minLength ?~ 1
108+ & schemaMinLength ?~ 1
168
109
169instance ToParamSchema Scientific where
110instance ToParamSchema Scientific where
170− toParamSchema _ = mempty & type_ ?~ SwaggerNumber
111+ toParamSchema _ = mempty & schemaType .~ SwaggerNumber
171−
172−instance HasResolution a => ToParamSchema (Fixed a) where
173− toParamSchema _ = mempty
174− & type_ ?~ SwaggerNumber
175− & multipleOf ?~ (recip . fromInteger $ resolution (Proxy :: Proxy a))
176
112
177instance ToParamSchema Double where
113instance ToParamSchema Double where
178− toParamSchema _ = mempty
114+ toParamSchema _ = mempty & schemaType .~ SwaggerNumber
179− & type_ ?~ SwaggerNumber
180− & format ?~ "double"
181
115
182instance ToParamSchema Float where
116instance ToParamSchema Float where
183− toParamSchema _ = mempty
117+ toParamSchema _ = mempty & schemaType .~ SwaggerNumber
184− & type_ ?~ SwaggerNumber
185− & format ?~ "float"
186
118
187timeParamSchema :: String -> ParamSchema t
119timeParamSchema :: String -> ParamSchema t
188−timeParamSchema fmt = mempty
120+timeParamSchema format = mempty
189− & type_ ?~ SwaggerString
121+ & schemaType .~ SwaggerString
190− & format ?~ T.pack fmt
122+ & schemaFormat ?~ T.pack format
191−
192−-- | Format @"date"@ corresponds to @yyyy-mm-dd@ format.
193−instance ToParamSchema Day where
194− toParamSchema _ = timeParamSchema "date"
195
123
196-- |
124-- |
197−-- >>> toParamSchema (Proxy :: Proxy TimeOfDay) ^. format
125+-- >>> toParamSchema (Proxy :: Proxy Day) ^. schemaFormat
198−-- Just "hh:MM:ss"
126+-- Just "yyyy-mm-dd"
199−instance ToParamSchema TimeOfDay where
127+instance ToParamSchema Day where
200− toParamSchema _ = timeParamSchema "hh:MM:ss"
128+ toParamSchema _ = timeParamSchema "yyyy-mm-dd"
201
129
202-- |
130-- |
203−-- >>> toParamSchema (Proxy :: Proxy LocalTime) ^. format
131+-- >>> toParamSchema (Proxy :: Proxy LocalTime) ^. schemaFormat
204-- Just "yyyy-mm-ddThh:MM:ss"
132-- Just "yyyy-mm-ddThh:MM:ss"
205instance ToParamSchema LocalTime where
133instance ToParamSchema LocalTime where
206 toParamSchema _ = timeParamSchema "yyyy-mm-ddThh:MM:ss"
134 toParamSchema _ = timeParamSchema "yyyy-mm-ddThh:MM:ss"
207
135
208-- |
136-- |
209−-- >>> toParamSchema (Proxy :: Proxy ZonedTime) ^. format
137+-- >>> toParamSchema (Proxy :: Proxy ZonedTime) ^. schemaFormat
210-- Just "yyyy-mm-ddThh:MM:ss+hhMM"
138-- Just "yyyy-mm-ddThh:MM:ss+hhMM"
211instance ToParamSchema ZonedTime where
139instance ToParamSchema ZonedTime where
212 toParamSchema _ = timeParamSchema "yyyy-mm-ddThh:MM:ss+hhMM"
140 toParamSchema _ = timeParamSchema "yyyy-mm-ddThh:MM:ss+hhMM"
213
141
214-- |
142-- |
215−-- >>> toParamSchema (Proxy :: Proxy UTCTime) ^. format
143+-- >>> toParamSchema (Proxy :: Proxy UTCTime) ^. schemaFormat
216-- Just "yyyy-mm-ddThh:MM:ssZ"
144-- Just "yyyy-mm-ddThh:MM:ssZ"
217instance ToParamSchema UTCTime where
145instance ToParamSchema UTCTime where
218 toParamSchema _ = timeParamSchema "yyyy-mm-ddThh:MM:ssZ"
146 toParamSchema _ = timeParamSchema "yyyy-mm-ddThh:MM:ssZ"
219
147
220instance ToParamSchema NominalDiffTime where
148instance ToParamSchema NominalDiffTime where
221− toParamSchema _ = toParamSchema (Proxy :: Proxy Pico)
149+ toParamSchema _ = toParamSchema (Proxy :: Proxy Integer)
222
150
223instance ToParamSchema T.Text where
151instance ToParamSchema T.Text where
224 toParamSchema _ = toParamSchema (Proxy :: Proxy String)
152 toParamSchema _ = toParamSchema (Proxy :: Proxy String)
@@ -226,28 +154,6 @@ instance ToParamSchema T.Text where
226instance ToParamSchema TL.Text where
154instance ToParamSchema TL.Text where
227 toParamSchema _ = toParamSchema (Proxy :: Proxy String)
155 toParamSchema _ = toParamSchema (Proxy :: Proxy String)
228
156
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−
251instance ToParamSchema All where toParamSchema _ = toParamSchema (Proxy :: Proxy Bool)
157instance ToParamSchema All where toParamSchema _ = toParamSchema (Proxy :: Proxy Bool)
252instance ToParamSchema Any where toParamSchema _ = toParamSchema (Proxy :: Proxy Bool)
158instance ToParamSchema Any where toParamSchema _ = toParamSchema (Proxy :: Proxy Bool)
253instance ToParamSchema a => ToParamSchema (Sum a) where toParamSchema _ = toParamSchema (Proxy :: Proxy a)
159instance ToParamSchema a => ToParamSchema (Sum a) where toParamSchema _ = toParamSchema (Proxy :: Proxy a)
@@ -256,37 +162,13 @@ instance ToParamSchema a => ToParamSchema (First a) where toParamSchema _ = to
256instance ToParamSchema a => ToParamSchema (Last a) where toParamSchema _ = toParamSchema (Proxy :: Proxy a)
162instance ToParamSchema a => ToParamSchema (Last a) where toParamSchema _ = toParamSchema (Proxy :: Proxy a)
257instance ToParamSchema a => ToParamSchema (Dual a) where toParamSchema _ = toParamSchema (Proxy :: Proxy a)
163instance ToParamSchema a => ToParamSchema (Dual a) where toParamSchema _ = toParamSchema (Proxy :: Proxy a)
258
164
259−instance ToParamSchema a => ToParamSchema (Identity a) where toParamSchema _ = toParamSchema (Proxy :: Proxy a)
260−
261−instance ToParamSchema a => ToParamSchema [a] where
262− toParamSchema _ = mempty
263− & type_ ?~ SwaggerArray
264− & items ?~ SwaggerItemsPrimitive Nothing (toParamSchema (Proxy :: Proxy a))
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−
271−instance ToParamSchema a => ToParamSchema (Set a) where
272− toParamSchema _ = toParamSchema (Proxy :: Proxy [a])
273− & uniqueItems ?~ True
274−
275−instance ToParamSchema a => ToParamSchema (HashSet a) where
276− toParamSchema _ = toParamSchema (Proxy :: Proxy (Set a))
277−
278-- |
165-- |
279-- >>> encode $ toParamSchema (Proxy :: Proxy ())
166-- >>> encode $ toParamSchema (Proxy :: Proxy ())
280-- "{\"type\":\"string\",\"enum\":[\"_\"]}"
167-- "{\"type\":\"string\",\"enum\":[\"_\"]}"
281instance ToParamSchema () where
168instance ToParamSchema () where
282 toParamSchema _ = mempty
169 toParamSchema _ = mempty
283− & type_ ?~ SwaggerString
170+ & schemaType .~ SwaggerString
284− & enum_ ?~ ["_"]
171+ & schemaEnum ?~ ["_"]
285−
286−instance ToParamSchema UUID where
287− toParamSchema _ = mempty
288− & type_ ?~ SwaggerString
289− & format ?~ "uuid"
290
172
291-- | A configurable generic @'ParamSchema'@ creator.
173-- | A configurable generic @'ParamSchema'@ creator.
292--
174--
@@ -294,18 +176,15 @@ instance ToParamSchema UUID where
294-- >>> data Color = Red | Blue deriving Generic
176-- >>> data Color = Red | Blue deriving Generic
295-- >>> encode $ genericToParamSchema defaultSchemaOptions (Proxy :: Proxy Color)
177-- >>> encode $ genericToParamSchema defaultSchemaOptions (Proxy :: Proxy Color)
296-- "{\"type\":\"string\",\"enum\":[\"Red\",\"Blue\"]}"
178-- "{\"type\":\"string\",\"enum\":[\"Red\",\"Blue\"]}"
297−genericToParamSchema :: forall a t. (Generic a, GToParamSchema (Rep a)) => SchemaOptions -> Proxy a -> ParamSchema t
179+genericToParamSchema :: forall proxy a t. (Generic a, GToParamSchema (Rep a)) => SchemaOptions -> proxy a -> ParamSchema t
298genericToParamSchema opts _ = gtoParamSchema opts (Proxy :: Proxy (Rep a)) mempty
180genericToParamSchema opts _ = gtoParamSchema opts (Proxy :: Proxy (Rep a)) mempty
299
181
300class GToParamSchema (f :: * -> *) where
182class GToParamSchema (f :: * -> *) where
301− gtoParamSchema :: SchemaOptions -> Proxy f -> ParamSchema t -> ParamSchema t
183+ gtoParamSchema :: SchemaOptions -> proxy f -> ParamSchema t -> ParamSchema t
302
184
303instance GToParamSchema f => GToParamSchema (D1 d f) where
185instance GToParamSchema f => GToParamSchema (D1 d f) where
304 gtoParamSchema opts _ = gtoParamSchema opts (Proxy :: Proxy f)
186 gtoParamSchema opts _ = gtoParamSchema opts (Proxy :: Proxy f)
305
187
306−instance Constructor c => GToParamSchema (C1 c U1) where
307− gtoParamSchema = genumParamSchema
308−
309instance GToParamSchema f => GToParamSchema (C1 c (S1 s f)) where
188instance GToParamSchema f => GToParamSchema (C1 c (S1 s f)) where
310 gtoParamSchema opts _ = gtoParamSchema opts (Proxy :: Proxy f)
189 gtoParamSchema opts _ = gtoParamSchema opts (Proxy :: Proxy f)
311
190
@@ -316,15 +195,15 @@ instance (GEnumParamSchema f, GEnumParamSchema g) => GToParamSchema (f :+: g) wh
316 gtoParamSchema opts _ = genumParamSchema opts (Proxy :: Proxy (f :+: g))
195 gtoParamSchema opts _ = genumParamSchema opts (Proxy :: Proxy (f :+: g))
317
196
318class GEnumParamSchema (f :: * -> *) where
197class GEnumParamSchema (f :: * -> *) where
319− genumParamSchema :: SchemaOptions -> Proxy f -> ParamSchema t -> ParamSchema t
198+ genumParamSchema :: SchemaOptions -> proxy f -> ParamSchema t -> ParamSchema t
320
199
321instance (GEnumParamSchema f, GEnumParamSchema g) => GEnumParamSchema (f :+: g) where
200instance (GEnumParamSchema f, GEnumParamSchema g) => GEnumParamSchema (f :+: g) where
322 genumParamSchema opts _ = genumParamSchema opts (Proxy :: Proxy f) . genumParamSchema opts (Proxy :: Proxy g)
201 genumParamSchema opts _ = genumParamSchema opts (Proxy :: Proxy f) . genumParamSchema opts (Proxy :: Proxy g)
323
202
324instance Constructor c => GEnumParamSchema (C1 c U1) where
203instance Constructor c => GEnumParamSchema (C1 c U1) where
325 genumParamSchema opts _ s = s
204 genumParamSchema opts _ s = s
326− & type_ ?~ SwaggerString
205+ & schemaType .~ SwaggerString
327− & enum_ %~ addEnumValue tag
206+ & schemaEnum %~ addEnumValue tag
328 where
207 where
329 tag = toJSON (constructorTagModifier opts (conName (Proxy3 :: Proxy3 c f p)))
208 tag = toJSON (constructorTagModifier opts (conName (Proxy3 :: Proxy3 c f p)))
330
209
@@ -333,5 +212,3 @@ instance Constructor c => GEnumParamSchema (C1 c U1) where
333
212
334data Proxy3 a b c = Proxy3
213data Proxy3 a b c = Proxy3
335
214
336−-- $setup
337−-- >>> import Data.Aeson (encode)
src/Data/Swagger/Internal/Schema.hs+155−472
@@ -1,10 +1,7 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE ConstraintKinds #-}
3{-# LANGUAGE DefaultSignatures #-}
1{-# LANGUAGE DefaultSignatures #-}
4{-# LANGUAGE FlexibleContexts #-}
2{-# LANGUAGE FlexibleContexts #-}
5{-# LANGUAGE FlexibleInstances #-}
3{-# LANGUAGE FlexibleInstances #-}
6{-# LANGUAGE KindSignatures #-}
4{-# LANGUAGE KindSignatures #-}
7−{-# LANGUAGE DataKinds #-}
8{-# LANGUAGE OverloadedLists #-}
5{-# LANGUAGE OverloadedLists #-}
9{-# LANGUAGE OverloadedStrings #-}
6{-# LANGUAGE OverloadedStrings #-}
10{-# LANGUAGE PackageImports #-}
7{-# LANGUAGE PackageImports #-}
@@ -14,84 +11,61 @@
14{-# LANGUAGE TypeFamilies #-}
11{-# LANGUAGE TypeFamilies #-}
15{-# LANGUAGE TypeOperators #-}
12{-# LANGUAGE TypeOperators #-}
16{-# LANGUAGE TypeSynonymInstances #-}
13{-# 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
24−#include "overlapping-compat.h"
25module Data.Swagger.Internal.Schema where
14module Data.Swagger.Internal.Schema where
26
15
27−import Prelude ()
28−import Prelude.Compat
29−
30import Control.Lens
16import Control.Lens
31import Data.Data.Lens (template)
17import Data.Data.Lens (template)
32
18
33import Control.Monad
19import Control.Monad
34import Control.Monad.Writer
20import Control.Monad.Writer
35−import Data.Aeson (ToJSON (..), ToJSONKey (..), ToJSONKeyFunction (..), Value (..), Object(..))
21+import Data.Aeson
36import Data.Char
22import Data.Char
37import Data.Data (Data)
23import Data.Data (Data)
38import Data.Foldable (traverse_)
24import Data.Foldable (traverse_)
39import Data.HashMap.Strict (HashMap)
25import Data.HashMap.Strict (HashMap)
40import qualified Data.HashMap.Strict as HashMap
26import qualified Data.HashMap.Strict as HashMap
41−import "unordered-containers" Data.HashSet (HashSet)
27+import "unordered-containers" Data.HashSet (HashSet)
42−import qualified "unordered-containers" Data.HashSet as HashSet
43−import qualified Data.HashMap.Strict.InsOrd as InsOrdHashMap
44import Data.Int
28import Data.Int
45import Data.IntSet (IntSet)
29import Data.IntSet (IntSet)
46import Data.IntMap (IntMap)
30import Data.IntMap (IntMap)
47−import Data.List.NonEmpty.Compat (NonEmpty)
48import Data.Map (Map)
31import Data.Map (Map)
32+import Data.Monoid
49import Data.Proxy
33import Data.Proxy
50import Data.Scientific (Scientific)
34import Data.Scientific (Scientific)
51−import Data.Fixed (Fixed, HasResolution, Pico)
52import Data.Set (Set)
35import Data.Set (Set)
53import qualified Data.Text as T
36import qualified Data.Text as T
54import qualified Data.Text.Lazy as TL
37import qualified Data.Text.Lazy as TL
55import Data.Time
38import 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)
62import Data.Word
39import Data.Word
63import GHC.Generics
40import GHC.Generics
64−import qualified Data.UUID.Types as UUID
65
41
66import Data.Swagger.Declare
42import Data.Swagger.Declare
67import Data.Swagger.Internal
43import Data.Swagger.Internal
68import Data.Swagger.Internal.ParamSchema (ToParamSchema(..))
44import Data.Swagger.Internal.ParamSchema (ToParamSchema(..))
69−import Data.Swagger.Lens hiding (name, schema)
45+import Data.Swagger.Lens
70−import qualified Data.Swagger.Lens as Swagger
71import Data.Swagger.SchemaOptions
46import Data.Swagger.SchemaOptions
72−import Data.Swagger.Internal.TypeShape
73
47
74−#if __GLASGOW_HASKELL__ < 800
48+-- | A @'Schema'@ with an optional name.
75−#else
49+-- This name can be used in references.
76−import qualified Data.ByteString as BS
50+type NamedSchema = (Maybe T.Text, Schema)
77−import qualified Data.ByteString.Lazy as BSL
51+
78−import GHC.TypeLits (TypeError, ErrorMessage(..))
52+-- | Schema definitions, a mapping from schema name to @'Schema'@.
79−#endif
53+type Definitions = HashMap T.Text Schema
80
54
81unnamed :: Schema -> NamedSchema
55unnamed :: Schema -> NamedSchema
82−unnamed schema = NamedSchema Nothing schema
56+unnamed schema = (Nothing, schema)
83
57
84named :: T.Text -> Schema -> NamedSchema
58named :: T.Text -> Schema -> NamedSchema
85−named name schema = NamedSchema (Just name) schema
59+named name schema = (Just name, schema)
86
60
87−plain :: Schema -> Declare (Definitions Schema) NamedSchema
61+plain :: Schema -> Declare Definitions NamedSchema
88plain = pure . unnamed
62plain = pure . unnamed
89
63
90unname :: NamedSchema -> NamedSchema
64unname :: NamedSchema -> NamedSchema
91−unname (NamedSchema _ schema) = unnamed schema
65+unname (_, schema) = (Nothing, schema)
92
66
93rename :: Maybe T.Text -> NamedSchema -> NamedSchema
67rename :: Maybe T.Text -> NamedSchema -> NamedSchema
94−rename name (NamedSchema _ schema) = NamedSchema name schema
68+rename name (_, schema) = (name, schema)
95
69
96-- | Convert a type into @'Schema'@.
70-- | Convert a type into @'Schema'@.
97--
71--
@@ -102,21 +76,19 @@ rename name (NamedSchema _ schema) = NamedSchema name schema
102-- {-\# LANGUAGE OverloadedLists \#-} -- allows to write 'Map' and 'HashMap' as lists
76-- {-\# LANGUAGE OverloadedLists \#-} -- allows to write 'Map' and 'HashMap' as lists
103--
77--
104-- import Control.Lens
78-- import Control.Lens
105−-- import Data.Proxy
106−-- import Data.Swagger
107--
79--
108-- data Coord = Coord { x :: Double, y :: Double }
80-- data Coord = Coord { x :: Double, y :: Double }
109--
81--
110-- instance ToSchema Coord where
82-- instance ToSchema Coord where
111−-- declareNamedSchema _ = do
83+-- declareNamedSchema = pure (Just \"Coord\", schema)
112−-- doubleSchema <- declareSchemaRef (Proxy :: Proxy Double)
84+-- where
113−-- return $ NamedSchema (Just \"Coord\") $ mempty
85+-- schema = mempty
114−-- & type_ ?~ SwaggerObject
86+-- & schemaType .~ SwaggerObject
115−-- & properties .~
87+-- & schemaProperties .~
116−-- [ (\"x\", doubleSchema)
88+-- [ (\"x\", toSchemaRef (Proxy :: Proxy Double))
117−-- , (\"y\", doubleSchema)
89+-- , (\"y\", toSchemaRef (Proxy :: Proxy Double))
118−-- ]
90+-- ]
119−-- & required .~ [ \"x\", \"y\" ]
91+-- & schemaRequired .~ [ \"x\", \"y\" ]
120-- @
92-- @
121--
93--
122-- Instead of manually writing your @'ToSchema'@ instance you can
94-- Instead of manually writing your @'ToSchema'@ instance you can
@@ -142,31 +114,22 @@ class ToSchema a where
142 -- together with all used definitions.
114 -- together with all used definitions.
143 -- Note that the schema itself is included in definitions
115 -- Note that the schema itself is included in definitions
144 -- only if it is recursive (and thus needs its definition in scope).
116 -- only if it is recursive (and thus needs its definition in scope).
145− declareNamedSchema :: Proxy a -> Declare (Definitions Schema) NamedSchema
117+ declareNamedSchema :: proxy a -> Declare Definitions NamedSchema
146− default declareNamedSchema :: (Generic a, GToSchema (Rep a), TypeHasSimpleShape a "genericDeclareNamedSchemaUnrestricted") =>
118+ default declareNamedSchema :: (Generic a, GToSchema (Rep a)) => proxy a -> Declare Definitions NamedSchema
147− Proxy a -> Declare (Definitions Schema) NamedSchema
148 declareNamedSchema = genericDeclareNamedSchema defaultSchemaOptions
119 declareNamedSchema = genericDeclareNamedSchema defaultSchemaOptions
149
120
150−instance ToSchema TimeOfDay where
151− declareNamedSchema _ = pure $ named "TimeOfDay" $ timeSchema "hh:MM:ss"
152− & example ?~ toJSON (TimeOfDay 12 33 15)
153−
154-- | Convert a type into a schema and declare all used schema definitions.
121-- | Convert a type into a schema and declare all used schema definitions.
155−declareSchema :: ToSchema a => Proxy a -> Declare (Definitions Schema) Schema
122+declareSchema :: ToSchema a => proxy a -> Declare Definitions Schema
156−declareSchema = fmap _namedSchemaSchema . declareNamedSchema
123+declareSchema = fmap snd . declareNamedSchema
157
124
158-- | Convert a type into an optionally named schema.
125-- | Convert a type into an optionally named schema.
159--
126--
160−-- >>> toNamedSchema (Proxy :: Proxy String) ^. name
161−-- Nothing
162−-- >>> encode (toNamedSchema (Proxy :: Proxy String) ^. schema)
127+-- >>> encode <$> toNamedSchema (Proxy :: Proxy String)
163−-- "{\"type\":\"string\"}"
128+-- (Nothing,"{\"type\":\"string\"}")
164--
129--
165−-- >>> toNamedSchema (Proxy :: Proxy Day) ^. name
166−-- Just "Day"
167−-- >>> encode (toNamedSchema (Proxy :: Proxy Day) ^. schema)
130+-- >>> encode <$> toNamedSchema (Proxy :: Proxy Day)
168−-- "{\"example\":\"2016-07-22\",\"format\":\"date\",\"type\":\"string\"}"
131+-- (Just "Day","{\"format\":\"yyyy-mm-dd\",\"type\":\"string\"}")
169−toNamedSchema :: ToSchema a => Proxy a -> NamedSchema
132+toNamedSchema :: ToSchema a => proxy a -> NamedSchema
170toNamedSchema = undeclare . declareNamedSchema
133toNamedSchema = undeclare . declareNamedSchema
171
134
172-- | Get type's schema name according to its @'ToSchema'@ instance.
135-- | Get type's schema name according to its @'ToSchema'@ instance.
@@ -176,8 +139,8 @@ toNamedSchema = undeclare . declareNamedSchema
176--
139--
177-- >>> schemaName (Proxy :: Proxy UTCTime)
140-- >>> schemaName (Proxy :: Proxy UTCTime)
178-- Just "UTCTime"
141-- Just "UTCTime"
179−schemaName :: ToSchema a => Proxy a -> Maybe T.Text
142+schemaName :: ToSchema a => proxy a -> Maybe T.Text
180−schemaName = _namedSchemaName . toNamedSchema
143+schemaName = fst . toNamedSchema
181
144
182-- | Convert a type into a schema.
145-- | Convert a type into a schema.
183--
146--
@@ -186,8 +149,8 @@ schemaName = _namedSchemaName . toNamedSchema
186--
149--
187-- >>> encode $ toSchema (Proxy :: Proxy [Day])
150-- >>> encode $ toSchema (Proxy :: Proxy [Day])
188-- "{\"items\":{\"$ref\":\"#/definitions/Day\"},\"type\":\"array\"}"
151-- "{\"items\":{\"$ref\":\"#/definitions/Day\"},\"type\":\"array\"}"
189−toSchema :: ToSchema a => Proxy a -> Schema
152+toSchema :: ToSchema a => proxy a -> Schema
190−toSchema = _namedSchemaSchema . toNamedSchema
153+toSchema = snd . toNamedSchema
191
154
192-- | Convert a type into a referenced schema if possible.
155-- | Convert a type into a referenced schema if possible.
193-- Only named schemas can be referenced, nameless schemas are inlined.
156-- Only named schemas can be referenced, nameless schemas are inlined.
@@ -197,7 +160,7 @@ toSchema = _namedSchemaSchema . toNamedSchema
197--
160--
198-- >>> encode $ toSchemaRef (Proxy :: Proxy Day)
161-- >>> encode $ toSchemaRef (Proxy :: Proxy Day)
199-- "{\"$ref\":\"#/definitions/Day\"}"
162-- "{\"$ref\":\"#/definitions/Day\"}"
200−toSchemaRef :: ToSchema a => Proxy a -> Referenced Schema
163+toSchemaRef :: ToSchema a => proxy a -> Referenced Schema
201toSchemaRef = undeclare . declareSchemaRef
164toSchemaRef = undeclare . declareSchemaRef
202
165
203-- | Convert a type into a referenced schema if possible
166-- | Convert a type into a referenced schema if possible
@@ -207,10 +170,10 @@ toSchemaRef = undeclare . declareSchemaRef
207-- Schema definitions are typically declared for every referenced schema.
170-- Schema definitions are typically declared for every referenced schema.
208-- If @'declareSchemaRef'@ returns a reference, a corresponding schema
171-- If @'declareSchemaRef'@ returns a reference, a corresponding schema
209-- will be declared (regardless of whether it is recusive or not).
172-- will be declared (regardless of whether it is recusive or not).
210−declareSchemaRef :: ToSchema a => Proxy a -> Declare (Definitions Schema) (Referenced Schema)
173+declareSchemaRef :: ToSchema a => proxy a -> Declare Definitions (Referenced Schema)
211declareSchemaRef proxy = do
174declareSchemaRef proxy = do
212 case toNamedSchema proxy of
175 case toNamedSchema proxy of
213− NamedSchema (Just name) schema -> do
176+ (Just name, schema) -> do
214 -- This check is very important as it allows generically
177 -- This check is very important as it allows generically
215 -- derive used definitions for recursive schemas.
178 -- derive used definitions for recursive schemas.
216 -- Lazy Declare monad allows toNamedSchema to ignore
179 -- Lazy Declare monad allows toNamedSchema to ignore
@@ -219,7 +182,7 @@ declareSchemaRef proxy = do
219 -- have already declared it.
182 -- have already declared it.
220 -- If we have, we don't need to declare anything for
183 -- If we have, we don't need to declare anything for
221 -- this schema this time and thus simply return the reference.
184 -- this schema this time and thus simply return the reference.
222− known <- looks (InsOrdHashMap.member name)
185+ known <- looks (HashMap.member name)
223 when (not known) $ do
186 when (not known) $ do
224 declare [(name, schema)]
187 declare [(name, schema)]
225 void $ declareNamedSchema proxy
188 void $ declareNamedSchema proxy
@@ -233,12 +196,12 @@ declareSchemaRef proxy = do
233--
196--
234-- __WARNING:__ @'inlineSchemasWhen'@ will produce infinite schemas
197-- __WARNING:__ @'inlineSchemasWhen'@ will produce infinite schemas
235-- when inlining recursive schemas.
198-- when inlining recursive schemas.
236−inlineSchemasWhen :: Data s => (T.Text -> Bool) -> (Definitions Schema) -> s -> s
199+inlineSchemasWhen :: Data s => (T.Text -> Bool) -> Definitions -> s -> s
237inlineSchemasWhen p defs = template %~ deref
200inlineSchemasWhen p defs = template %~ deref
238 where
201 where
239 deref r@(Ref (Reference name))
202 deref r@(Ref (Reference name))
240 | p name =
203 | p name =
241− case InsOrdHashMap.lookup name defs of
204+ case HashMap.lookup name defs of
242 Just schema -> Inline (inlineSchemasWhen p defs schema)
205 Just schema -> Inline (inlineSchemasWhen p defs schema)
243 Nothing -> r
206 Nothing -> r
244 | otherwise = r
207 | otherwise = r
@@ -249,38 +212,38 @@ inlineSchemasWhen p defs = template %~ deref
249-- /NOTE:/ if a referenced schema is not found in definitions
212-- /NOTE:/ if a referenced schema is not found in definitions
250-- it stays referenced even if it appears in the list of names.
213-- it stays referenced even if it appears in the list of names.
251--
214--
252−-- __WARNING:__ @'inlineSchemas'@ will produce infinite schemas
215+-- __WARNING:__ @'inlineSchemasWhen'@ will produce infinite schemas
253-- when inlining recursive schemas.
216-- when inlining recursive schemas.
254−inlineSchemas :: Data s => [T.Text] -> (Definitions Schema) -> s -> s
217+inlineSchemas :: Data s => [T.Text] -> Definitions -> s -> s
255inlineSchemas names = inlineSchemasWhen (`elem` names)
218inlineSchemas names = inlineSchemasWhen (`elem` names)
256
219
257-- | Inline all schema references for which the definition
220-- | Inline all schema references for which the definition
258-- can be found in @'Definitions'@.
221-- can be found in @'Definitions'@.
259--
222--
260−-- __WARNING:__ @'inlineAllSchemas'@ will produce infinite schemas
223+-- __WARNING:__ @'inlineSchemasWhen'@ will produce infinite schemas
261-- when inlining recursive schemas.
224-- when inlining recursive schemas.
262−inlineAllSchemas :: Data s => (Definitions Schema) -> s -> s
225+inlineAllSchemas :: Data s => Definitions -> s -> s
263inlineAllSchemas = inlineSchemasWhen (const True)
226inlineAllSchemas = inlineSchemasWhen (const True)
264
227
265-- | Convert a type into a schema without references.
228-- | Convert a type into a schema without references.
266--
229--
267-- >>> encode $ toInlinedSchema (Proxy :: Proxy [Day])
230-- >>> encode $ toInlinedSchema (Proxy :: Proxy [Day])
268−-- "{\"items\":{\"example\":\"2016-07-22\",\"format\":\"date\",\"type\":\"string\"},\"type\":\"array\"}"
231+-- "{\"items\":{\"format\":\"yyyy-mm-dd\",\"type\":\"string\"},\"type\":\"array\"}"
269--
232--
270-- __WARNING:__ @'toInlinedSchema'@ will produce infinite schema
233-- __WARNING:__ @'toInlinedSchema'@ will produce infinite schema
271-- when inlining recursive schemas.
234-- when inlining recursive schemas.
272−toInlinedSchema :: ToSchema a => Proxy a -> Schema
235+toInlinedSchema :: ToSchema a => proxy a -> Schema
273toInlinedSchema proxy = inlineAllSchemas defs schema
236toInlinedSchema proxy = inlineAllSchemas defs schema
274 where
237 where
275 (defs, schema) = runDeclare (declareSchema proxy) mempty
238 (defs, schema) = runDeclare (declareSchema proxy) mempty
276
239
277-- | Inline all /non-recursive/ schemas for which the definition
240-- | Inline all /non-recursive/ schemas for which the definition
278-- can be found in @'Definitions'@.
241-- can be found in @'Definitions'@.
279−inlineNonRecursiveSchemas :: Data s => (Definitions Schema) -> s -> s
242+inlineNonRecursiveSchemas :: Data s => Definitions -> s -> s
280inlineNonRecursiveSchemas defs = inlineSchemasWhen nonRecursive defs
243inlineNonRecursiveSchemas defs = inlineSchemasWhen nonRecursive defs
281 where
244 where
282 nonRecursive name =
245 nonRecursive name =
283− case InsOrdHashMap.lookup name defs of
246+ case HashMap.lookup name defs of
284 Just schema -> name `notElem` execDeclare (usedNames schema) mempty
247 Just schema -> name `notElem` execDeclare (usedNames schema) mempty
285 Nothing -> False
248 Nothing -> False
286
249
@@ -292,141 +255,22 @@ inlineNonRecursiveSchemas defs = inlineSchemasWhen nonRecursive defs
292 seen <- looks (name `elem`)
255 seen <- looks (name `elem`)
293 when (not seen) $ do
256 when (not seen) $ do
294 declare [name]
257 declare [name]
295− traverse_ usedNames (InsOrdHashMap.lookup name defs)
258+ traverse_ usedNames (HashMap.lookup name defs)
296 Inline subschema -> usedNames subschema
259 Inline subschema -> usedNames subschema
297
260
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−
416class GToSchema (f :: * -> *) where
261class GToSchema (f :: * -> *) where
417− gdeclareNamedSchema :: SchemaOptions -> Proxy f -> Schema -> Declare (Definitions Schema) NamedSchema
262+ gdeclareNamedSchema :: SchemaOptions -> proxy f -> Schema -> Declare Definitions NamedSchema
418
263
419−instance OVERLAPPABLE_ ToSchema a => ToSchema [a] where
264+instance {-# OVERLAPPABLE #-} ToSchema a => ToSchema [a] where
420 declareNamedSchema _ = do
265 declareNamedSchema _ = do
421 ref <- declareSchemaRef (Proxy :: Proxy a)
266 ref <- declareSchemaRef (Proxy :: Proxy a)
422 return $ unnamed $ mempty
267 return $ unnamed $ mempty
423− & type_ ?~ SwaggerArray
268+ & schemaType .~ SwaggerArray
424− & items ?~ SwaggerItemsObject ref
269+ & schemaItems ?~ SwaggerItemsObject ref
425
270
426−instance OVERLAPPING_ ToSchema String where declareNamedSchema = plain . paramSchemaToSchema
271+instance {-# OVERLAPPING #-} ToSchema String where declareNamedSchema = plain . paramSchemaToSchema
427instance ToSchema Bool where declareNamedSchema = plain . paramSchemaToSchema
272instance ToSchema Bool where declareNamedSchema = plain . paramSchemaToSchema
428instance ToSchema Integer where declareNamedSchema = plain . paramSchemaToSchema
273instance ToSchema Integer where declareNamedSchema = plain . paramSchemaToSchema
429−instance ToSchema Natural where declareNamedSchema = plain . paramSchemaToSchema
430instance ToSchema Int where declareNamedSchema = plain . paramSchemaToSchema
274instance ToSchema Int where declareNamedSchema = plain . paramSchemaToSchema
431instance ToSchema Int8 where declareNamedSchema = plain . paramSchemaToSchema
275instance ToSchema Int8 where declareNamedSchema = plain . paramSchemaToSchema
432instance ToSchema Int16 where declareNamedSchema = plain . paramSchemaToSchema
276instance ToSchema Int16 where declareNamedSchema = plain . paramSchemaToSchema
@@ -438,29 +282,17 @@ instance ToSchema Word16 where declareNamedSchema = plain . paramSchemaToSchema
438instance ToSchema Word32 where declareNamedSchema = plain . paramSchemaToSchema
282instance ToSchema Word32 where declareNamedSchema = plain . paramSchemaToSchema
439instance ToSchema Word64 where declareNamedSchema = plain . paramSchemaToSchema
283instance ToSchema Word64 where declareNamedSchema = plain . paramSchemaToSchema
440
284
441−instance ToSchema Char where
442− declareNamedSchema proxy = plain (paramSchemaToSchema proxy)
285+instance ToSchema Char where declareNamedSchema = plain . paramSchemaToSchema
443− & mapped.Swagger.schema.example ?~ toJSON '?'
444−
445instance ToSchema Scientific where declareNamedSchema = plain . paramSchemaToSchema
286instance ToSchema Scientific where declareNamedSchema = plain . paramSchemaToSchema
446instance ToSchema Double where declareNamedSchema = plain . paramSchemaToSchema
287instance ToSchema Double where declareNamedSchema = plain . paramSchemaToSchema
447instance ToSchema Float where declareNamedSchema = plain . paramSchemaToSchema
288instance ToSchema Float where declareNamedSchema = plain . paramSchemaToSchema
448
289
449−instance HasResolution a => ToSchema (Fixed a) where declareNamedSchema = plain . paramSchemaToSchema
450−
451instance ToSchema a => ToSchema (Maybe a) where
290instance ToSchema a => ToSchema (Maybe a) where
452 declareNamedSchema _ = declareNamedSchema (Proxy :: Proxy a)
291 declareNamedSchema _ = declareNamedSchema (Proxy :: Proxy a)
453
292
454instance (ToSchema a, ToSchema b) => ToSchema (Either a b)
293instance (ToSchema a, ToSchema b) => ToSchema (Either a b)
455
294
456−instance ToSchema () where
295+instance ToSchema ()
457− declareNamedSchema _ = pure (NamedSchema Nothing nullarySchema)
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−
464instance (ToSchema a, ToSchema b) => ToSchema (a, b)
296instance (ToSchema a, ToSchema b) => ToSchema (a, b)
465instance (ToSchema a, ToSchema b, ToSchema c) => ToSchema (a, b, c)
297instance (ToSchema a, ToSchema b, ToSchema c) => ToSchema (a, b, c)
466instance (ToSchema a, ToSchema b, ToSchema c, ToSchema d) => ToSchema (a, b, c, d)
298instance (ToSchema a, ToSchema b, ToSchema c, ToSchema d) => ToSchema (a, b, c, d)
@@ -469,83 +301,52 @@ instance (ToSchema a, ToSchema b, ToSchema c, ToSchema d, ToSchema e, ToSchema f
469instance (ToSchema a, ToSchema b, ToSchema c, ToSchema d, ToSchema e, ToSchema f, ToSchema g) => ToSchema (a, b, c, d, e, f, g)
301instance (ToSchema a, ToSchema b, ToSchema c, ToSchema d, ToSchema e, ToSchema f, ToSchema g) => ToSchema (a, b, c, d, e, f, g)
470
302
471timeSchema :: T.Text -> Schema
303timeSchema :: T.Text -> Schema
472−timeSchema fmt = mempty
304+timeSchema format = mempty
473− & type_ ?~ SwaggerString
305+ & schemaType .~ SwaggerString
474− & format ?~ fmt
306+ & schemaFormat ?~ format
475
307
476−-- | Format @"date"@ corresponds to @yyyy-mm-dd@ format.
308+-- |
309+-- >>> toSchema (Proxy :: Proxy Day) ^. schemaFormat
310+-- Just "yyyy-mm-dd"
477instance ToSchema Day where
311instance ToSchema Day where
478− declareNamedSchema _ = pure $ named "Day" $ timeSchema "date"
312+ declareNamedSchema _ = pure $ named "Day" (timeSchema "yyyy-mm-dd")
479− & example ?~ toJSON (fromGregorian 2016 7 22)
480
313
481-- |
314-- |
482−-- >>> toSchema (Proxy :: Proxy LocalTime) ^. format
315+-- >>> toSchema (Proxy :: Proxy LocalTime) ^. schemaFormat
483-- Just "yyyy-mm-ddThh:MM:ss"
316-- Just "yyyy-mm-ddThh:MM:ss"
484instance ToSchema LocalTime where
317instance ToSchema LocalTime where
485− declareNamedSchema _ = pure $ named "LocalTime" $ timeSchema "yyyy-mm-ddThh:MM:ss"
318+ declareNamedSchema _ = pure $ named "LocalTime" (timeSchema "yyyy-mm-ddThh:MM:ss")
486− & example ?~ toJSON (LocalTime (fromGregorian 2016 7 22) (TimeOfDay 7 40 0))
487
319
320+-- |
321+-- >>> toSchema (Proxy :: Proxy ZonedTime) ^. schemaFormat
488−-- | Format @"date"@ corresponds to @yyyy-mm-ddThh:MM:ss(Z|+hh:MM)@ format.
322+-- Just "yyyy-mm-ddThh:MM:ss(Z|+hh:MM)"
489instance ToSchema ZonedTime where
323instance ToSchema ZonedTime where
490− declareNamedSchema _ = pure $ named "ZonedTime" $ timeSchema "date-time"
324+ declareNamedSchema _ = pure $ named "ZonedTime" $ timeSchema "yyyy-mm-ddThh:MM:ss(Z|+hh:MM)"
491− & example ?~ toJSON (ZonedTime (LocalTime (fromGregorian 2016 7 22) (TimeOfDay 7 40 0)) (hoursToTimeZone 3))
492
325
493instance ToSchema NominalDiffTime where
326instance ToSchema NominalDiffTime where
494− declareNamedSchema _ = declareNamedSchema (Proxy :: Proxy Pico)
327+ declareNamedSchema _ = declareNamedSchema (Proxy :: Proxy Integer)
495
328
496-- |
329-- |
497−-- >>> toSchema (Proxy :: Proxy UTCTime) ^. format
330+-- >>> toSchema (Proxy :: Proxy UTCTime) ^. schemaFormat
498-- Just "yyyy-mm-ddThh:MM:ssZ"
331-- Just "yyyy-mm-ddThh:MM:ssZ"
499instance ToSchema UTCTime where
332instance ToSchema UTCTime where
500− declareNamedSchema _ = pure $ named "UTCTime" $ timeSchema "yyyy-mm-ddThh:MM:ssZ"
333+ declareNamedSchema _ = pure $ named "UTCTime" (timeSchema "yyyy-mm-ddThh:MM:ssZ")
501− & example ?~ toJSON (UTCTime (fromGregorian 2016 7 22) 0)
502
334
503instance ToSchema T.Text where declareNamedSchema = plain . paramSchemaToSchema
335instance ToSchema T.Text where declareNamedSchema = plain . paramSchemaToSchema
504instance ToSchema TL.Text where declareNamedSchema = plain . paramSchemaToSchema
336instance ToSchema TL.Text where declareNamedSchema = plain . paramSchemaToSchema
505
337
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−
520instance ToSchema IntSet where declareNamedSchema _ = declareNamedSchema (Proxy :: Proxy (Set Int))
338instance ToSchema IntSet where declareNamedSchema _ = declareNamedSchema (Proxy :: Proxy (Set Int))
521
339
522-- | NOTE: This schema does not account for the uniqueness of keys.
340-- | NOTE: This schema does not account for the uniqueness of keys.
523instance ToSchema a => ToSchema (IntMap a) where
341instance ToSchema a => ToSchema (IntMap a) where
524 declareNamedSchema _ = declareNamedSchema (Proxy :: Proxy [(Int, a)])
342 declareNamedSchema _ = declareNamedSchema (Proxy :: Proxy [(Int, a)])
525
343
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−
543instance ToSchema a => ToSchema (Map String a) where
344instance ToSchema a => ToSchema (Map String a) where
544 declareNamedSchema _ = do
345 declareNamedSchema _ = do
545− schema <- declareSchemaRef (Proxy :: Proxy a)
346+ schema <- declareSchema (Proxy :: Proxy a)
546 return $ unnamed $ mempty
347 return $ unnamed $ mempty
547− & type_ ?~ SwaggerObject
348+ & schemaType .~ SwaggerObject
548− & additionalProperties ?~ schema
349+ & schemaAdditionalProperties ?~ schema
549
350
550instance ToSchema a => ToSchema (Map T.Text a) where declareNamedSchema _ = declareNamedSchema (Proxy :: Proxy (Map String a))
351instance ToSchema a => ToSchema (Map T.Text a) where declareNamedSchema _ = declareNamedSchema (Proxy :: Proxy (Map String a))
551instance ToSchema a => ToSchema (Map TL.Text a) where declareNamedSchema _ = declareNamedSchema (Proxy :: Proxy (Map String a))
352instance ToSchema a => ToSchema (Map TL.Text a) where declareNamedSchema _ = declareNamedSchema (Proxy :: Proxy (Map String a))
@@ -554,34 +355,14 @@ instance ToSchema a => ToSchema (HashMap String a) where declareNamedSchema _ =
554instance ToSchema a => ToSchema (HashMap T.Text a) where declareNamedSchema _ = declareNamedSchema (Proxy :: Proxy (Map String a))
355instance ToSchema a => ToSchema (HashMap T.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))
356instance ToSchema a => ToSchema (HashMap TL.Text a) where declareNamedSchema _ = declareNamedSchema (Proxy :: Proxy (Map String a))
556
357
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−
570instance ToSchema a => ToSchema (Set a) where
358instance ToSchema a => ToSchema (Set a) where
571 declareNamedSchema _ = do
359 declareNamedSchema _ = do
572 schema <- declareSchema (Proxy :: Proxy [a])
360 schema <- declareSchema (Proxy :: Proxy [a])
573 return $ unnamed $ schema
361 return $ unnamed $ schema
574− & uniqueItems ?~ True
362+ & schemaUniqueItems ?~ True
575
363
576instance ToSchema a => ToSchema (HashSet a) where declareNamedSchema _ = declareNamedSchema (Proxy :: Proxy (Set a))
364instance ToSchema a => ToSchema (HashSet a) where declareNamedSchema _ = declareNamedSchema (Proxy :: Proxy (Set a))
577
365
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−
585instance ToSchema All where declareNamedSchema = plain . paramSchemaToSchema
366instance ToSchema All where declareNamedSchema = plain . paramSchemaToSchema
586instance ToSchema Any where declareNamedSchema = plain . paramSchemaToSchema
367instance ToSchema Any where declareNamedSchema = plain . paramSchemaToSchema
587
368
@@ -591,178 +372,96 @@ instance ToSchema a => ToSchema (First a) where declareNamedSchema _ = unname
591instance ToSchema a => ToSchema (Last a) where declareNamedSchema _ = unname <$> declareNamedSchema (Proxy :: Proxy a)
372instance ToSchema a => ToSchema (Last a) where declareNamedSchema _ = unname <$> declareNamedSchema (Proxy :: Proxy a)
592instance ToSchema a => ToSchema (Dual a) where declareNamedSchema _ = unname <$> declareNamedSchema (Proxy :: Proxy a)
373instance ToSchema a => ToSchema (Dual a) where declareNamedSchema _ = unname <$> declareNamedSchema (Proxy :: Proxy a)
593
374
594−instance ToSchema a => ToSchema (Identity a) where declareNamedSchema _ = declareNamedSchema (Proxy :: Proxy a)
595−
596-- | Default schema for @'Bounded'@, @'Integral'@ types.
375-- | Default schema for @'Bounded'@, @'Integral'@ types.
597--
376--
598-- >>> encode $ toSchemaBoundedIntegral (Proxy :: Proxy Int16)
377-- >>> encode $ toSchemaBoundedIntegral (Proxy :: Proxy Int16)
599-- "{\"maximum\":32767,\"minimum\":-32768,\"type\":\"integer\"}"
378-- "{\"maximum\":32767,\"minimum\":-32768,\"type\":\"integer\"}"
600−toSchemaBoundedIntegral :: forall a. (Bounded a, Integral a) => Proxy a -> Schema
379+toSchemaBoundedIntegral :: forall a proxy. (Bounded a, Integral a) => proxy a -> Schema
601toSchemaBoundedIntegral _ = mempty
380toSchemaBoundedIntegral _ = mempty
602− & type_ ?~ SwaggerInteger
381+ & schemaType .~ SwaggerInteger
603− & minimum_ ?~ fromInteger (toInteger (minBound :: a))
382+ & schemaMinimum ?~ fromInteger (toInteger (minBound :: a))
604− & maximum_ ?~ fromInteger (toInteger (maxBound :: a))
383+ & schemaMaximum ?~ fromInteger (toInteger (maxBound :: a))
605
384
606-- | Default generic named schema for @'Bounded'@, @'Integral'@ types.
385-- | Default generic named schema for @'Bounded'@, @'Integral'@ types.
607−genericToNamedSchemaBoundedIntegral :: forall a d f.
386+genericToNamedSchemaBoundedIntegral :: forall a d f proxy.
608 ( Bounded a, Integral a
387 ( Bounded a, Integral a
609 , Generic a, Rep a ~ D1 d f, Datatype d)
388 , Generic a, Rep a ~ D1 d f, Datatype d)
610− => SchemaOptions -> Proxy a -> NamedSchema
389+ => SchemaOptions -> proxy a -> NamedSchema
611genericToNamedSchemaBoundedIntegral opts proxy
390genericToNamedSchemaBoundedIntegral opts proxy
612− = genericNameSchema opts proxy (toSchemaBoundedIntegral proxy)
391+ = (gdatatypeSchemaName opts (Proxy :: Proxy d), 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
668
392
669-- | A configurable generic @'Schema'@ creator.
393-- | A configurable generic @'Schema'@ creator.
670−genericDeclareSchema :: (Generic a, GToSchema (Rep a), TypeHasSimpleShape a "genericDeclareSchemaUnrestricted") =>
671− SchemaOptions -> Proxy a -> Declare (Definitions Schema) Schema
394+genericDeclareSchema :: (Generic a, GToSchema (Rep a)) => SchemaOptions -> proxy a -> Declare Definitions Schema
672−genericDeclareSchema = genericDeclareSchemaUnrestricted
395+genericDeclareSchema opts proxy = snd <$> genericDeclareNamedSchema opts proxy
673
396
674-- | A configurable generic @'NamedSchema'@ creator.
397-- | A configurable generic @'NamedSchema'@ creator.
675-- This function applied to @'defaultSchemaOptions'@
398-- This function applied to @'defaultSchemaOptions'@
676-- is used as the default for @'declareNamedSchema'@
399-- is used as the default for @'declareNamedSchema'@
677-- when the type is an instance of @'Generic'@.
400-- when the type is an instance of @'Generic'@.
678−genericDeclareNamedSchema :: (Generic a, GToSchema (Rep a), TypeHasSimpleShape a "genericDeclareNamedSchemaUnrestricted") =>
679− SchemaOptions -> Proxy a -> Declare (Definitions Schema) NamedSchema
401+genericDeclareNamedSchema :: forall a proxy. (Generic a, GToSchema (Rep a)) => SchemaOptions -> proxy a -> Declare Definitions NamedSchema
680−genericDeclareNamedSchema = genericDeclareNamedSchemaUnrestricted
402+genericDeclareNamedSchema opts _ = gdeclareNamedSchema opts (Proxy :: Proxy (Rep a)) mempty
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
403
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−
703−gdatatypeSchemaName :: forall d. Datatype d => SchemaOptions -> Proxy d -> Maybe T.Text
404+gdatatypeSchemaName :: forall proxy d. Datatype d => SchemaOptions -> proxy d -> Maybe T.Text
704−gdatatypeSchemaName opts _ = case orig of
405+gdatatypeSchemaName opts _ = case name of
705 (c:_) | isAlpha c && isUpper c -> Just (T.pack name)
406 (c:_) | isAlpha c && isUpper c -> Just (T.pack name)
706 _ -> Nothing
407 _ -> Nothing
707 where
408 where
708− orig = datatypeName (Proxy3 :: Proxy3 d f a)
409+ name = datatypeNameModifier opts (datatypeName (Proxy3 :: Proxy3 d f a))
709− name = datatypeNameModifier opts orig
710
410
711-- | Lift a plain @'ParamSchema'@ into a model @'NamedSchema'@.
411-- | Lift a plain @'ParamSchema'@ into a model @'NamedSchema'@.
412+paramSchemaToNamedSchema :: forall a d f proxy.
712−paramSchemaToNamedSchema :: (ToParamSchema a, Generic a, Rep a ~ D1 d f, Datatype d) =>
413+ (ToParamSchema a, Generic a, Rep a ~ D1 d f, Datatype d)
713− SchemaOptions -> Proxy a -> NamedSchema
414+ => SchemaOptions -> proxy a -> NamedSchema
714−paramSchemaToNamedSchema opts proxy = genericNameSchema opts proxy (paramSchemaToSchema proxy)
415+paramSchemaToNamedSchema opts proxy = (gdatatypeSchemaName opts (Proxy :: Proxy d), paramSchemaToSchema proxy)
715
416
716-- | Lift a plain @'ParamSchema'@ into a model @'Schema'@.
417-- | Lift a plain @'ParamSchema'@ into a model @'Schema'@.
717−paramSchemaToSchema :: ToParamSchema a => Proxy a -> Schema
418+paramSchemaToSchema :: forall a proxy. ToParamSchema a => proxy a -> Schema
718−paramSchemaToSchema proxy = mempty & paramSchema .~ toParamSchema proxy
419+paramSchemaToSchema _ = mempty & schemaParamSchema .~ toParamSchema (Proxy :: Proxy a)
719
420
720nullarySchema :: Schema
421nullarySchema :: Schema
721nullarySchema = mempty
422nullarySchema = mempty
722− & type_ ?~ SwaggerArray
423+ & schemaType .~ SwaggerArray
723− & items ?~ SwaggerItemsArray []
424+ & schemaEnum ?~ [ toJSON () ]
724
425
725−gtoNamedSchema :: GToSchema f => SchemaOptions -> Proxy f -> NamedSchema
426+gtoNamedSchema :: GToSchema f => SchemaOptions -> proxy f -> NamedSchema
726gtoNamedSchema opts proxy = undeclare $ gdeclareNamedSchema opts proxy mempty
427gtoNamedSchema opts proxy = undeclare $ gdeclareNamedSchema opts proxy mempty
727
428
728−gdeclareSchema :: GToSchema f => SchemaOptions -> Proxy f -> Declare (Definitions Schema) Schema
429+gdeclareSchema :: GToSchema f => SchemaOptions -> proxy f -> Declare Definitions Schema
729−gdeclareSchema opts proxy = _namedSchemaSchema <$> gdeclareNamedSchema opts proxy mempty
430+gdeclareSchema opts proxy = snd <$> gdeclareNamedSchema opts proxy mempty
431+
432+instance GToSchema U1 where
433+ gdeclareNamedSchema _ _ _ = plain nullarySchema
730
434
731instance (GToSchema f, GToSchema g) => GToSchema (f :*: g) where
435instance (GToSchema f, GToSchema g) => GToSchema (f :*: g) where
732 gdeclareNamedSchema opts _ schema = do
436 gdeclareNamedSchema opts _ schema = do
733− NamedSchema _ gschema <- gdeclareNamedSchema opts (Proxy :: Proxy f) schema
437+ (_, gschema) <- gdeclareNamedSchema opts (Proxy :: Proxy g) schema
734− gdeclareNamedSchema opts (Proxy :: Proxy g) gschema
438+ gdeclareNamedSchema opts (Proxy :: Proxy f) gschema
735
439
736instance (Datatype d, GToSchema f) => GToSchema (D1 d f) where
440instance (Datatype d, GToSchema f) => GToSchema (D1 d f) where
737 gdeclareNamedSchema opts _ s = rename name <$> gdeclareNamedSchema opts (Proxy :: Proxy f) s
441 gdeclareNamedSchema opts _ s = rename name <$> gdeclareNamedSchema opts (Proxy :: Proxy f) s
738 where
442 where
739 name = gdatatypeSchemaName opts (Proxy :: Proxy d)
443 name = gdatatypeSchemaName opts (Proxy :: Proxy d)
740
444
741−instance OVERLAPPABLE_ GToSchema f => GToSchema (C1 c f) where
445+instance {-# OVERLAPPABLE #-} GToSchema f => GToSchema (C1 c f) where
742 gdeclareNamedSchema opts _ = gdeclareNamedSchema opts (Proxy :: Proxy f)
446 gdeclareNamedSchema opts _ = gdeclareNamedSchema opts (Proxy :: Proxy f)
743
447
744−instance OVERLAPPING_ Constructor c => GToSchema (C1 c U1) where
745− gdeclareNamedSchema = gdeclareNamedSumSchema
746−
747-- | Single field constructor.
448-- | Single field constructor.
748−instance (Selector s, GToSchema f, GToSchema (S1 s f)) => GToSchema (C1 c (S1 s f)) where
449+instance (Selector s, GToSchema f) => GToSchema (C1 c (S1 s f)) where
749 gdeclareNamedSchema opts _ s
450 gdeclareNamedSchema opts _ s
750 | unwrapUnaryRecords opts = fieldSchema
451 | unwrapUnaryRecords opts = fieldSchema
751− | otherwise =
452+ | otherwise = do
453+ (_, schema) <- recordSchema
752− case schema ^. items of
454+ case schema ^. schemaItems of
753 Just (SwaggerItemsArray [_]) -> fieldSchema
455 Just (SwaggerItemsArray [_]) -> fieldSchema
754− _ -> do
755− declare defs
756− return (unnamed schema)
456+ _ -> pure (unnamed schema)
757 where
457 where
758− (defs, NamedSchema _ schema) = runDeclare recordSchema mempty
759 recordSchema = gdeclareNamedSchema opts (Proxy :: Proxy (S1 s f)) s
458 recordSchema = gdeclareNamedSchema opts (Proxy :: Proxy (S1 s f)) s
760 fieldSchema = gdeclareNamedSchema opts (Proxy :: Proxy f) s
459 fieldSchema = gdeclareNamedSchema opts (Proxy :: Proxy f) s
761
460
762−gdeclareSchemaRef :: GToSchema a => SchemaOptions -> Proxy a -> Declare (Definitions Schema) (Referenced Schema)
461+gdeclareSchemaRef :: GToSchema a => SchemaOptions -> proxy a -> Declare Definitions (Referenced Schema)
763gdeclareSchemaRef opts proxy = do
462gdeclareSchemaRef opts proxy = do
764 case gtoNamedSchema opts proxy of
463 case gtoNamedSchema opts proxy of
765− NamedSchema (Just name) schema -> do
464+ (Just name, schema) -> do
766 -- This check is very important as it allows generically
465 -- This check is very important as it allows generically
767 -- derive used definitions for recursive schemas.
466 -- derive used definitions for recursive schemas.
768 -- Lazy Declare monad allows toNamedSchema to ignore
467 -- Lazy Declare monad allows toNamedSchema to ignore
@@ -771,95 +470,83 @@ gdeclareSchemaRef opts proxy = do
771 -- have already declared it.
470 -- have already declared it.
772 -- If we have, we don't need to declare anything for
471 -- If we have, we don't need to declare anything for
773 -- this schema this time and thus simply return the reference.
472 -- this schema this time and thus simply return the reference.
774− known <- looks (InsOrdHashMap.member name)
473+ known <- looks (HashMap.member name)
775 when (not known) $ do
474 when (not known) $ do
776 declare [(name, schema)]
475 declare [(name, schema)]
777 void $ gdeclareNamedSchema opts proxy mempty
476 void $ gdeclareNamedSchema opts proxy mempty
778 return $ Ref (Reference name)
477 return $ Ref (Reference name)
779 _ -> Inline <$> gdeclareSchema opts proxy
478 _ -> Inline <$> gdeclareSchema opts proxy
780
479
781−appendItem :: Referenced Schema -> Maybe (SwaggerItems 'SwaggerKindSchema) -> Maybe (SwaggerItems 'SwaggerKindSchema)
480+appendItem :: Referenced Schema -> Maybe (SwaggerItems Schema) -> Maybe (SwaggerItems Schema)
782appendItem x Nothing = Just (SwaggerItemsArray [x])
481appendItem x Nothing = Just (SwaggerItemsArray [x])
783−appendItem x (Just (SwaggerItemsArray xs)) = Just (SwaggerItemsArray (xs ++ [x]))
482+appendItem x (Just (SwaggerItemsArray xs)) = Just (SwaggerItemsArray (x:xs))
784appendItem _ _ = error "GToSchema.appendItem: cannot append to SwaggerItemsObject"
483appendItem _ _ = error "GToSchema.appendItem: cannot append to SwaggerItemsObject"
785
484
786withFieldSchema :: forall proxy s f. (Selector s, GToSchema f) =>
485withFieldSchema :: forall proxy s f. (Selector s, GToSchema f) =>
787− SchemaOptions -> proxy s f -> Bool -> Schema -> Declare (Definitions Schema) Schema
486+ SchemaOptions -> proxy s f -> Bool -> Schema -> Declare Definitions Schema
788withFieldSchema opts _ isRequiredField schema = do
487withFieldSchema opts _ isRequiredField schema = do
789 ref <- gdeclareSchemaRef opts (Proxy :: Proxy f)
488 ref <- gdeclareSchemaRef opts (Proxy :: Proxy f)
790 return $
489 return $
791 if T.null fname
490 if T.null fname
792 then schema
491 then schema
793− & type_ ?~ SwaggerArray
492+ & schemaType .~ SwaggerArray
794− & items %~ appendItem ref
493+ & schemaItems %~ appendItem ref
795− & maxItems %~ Just . maybe 1 (+1) -- increment maxItems
796− & minItems %~ Just . maybe 1 (+1) -- increment minItems
797 else schema
494 else schema
798− & type_ ?~ SwaggerObject
495+ & schemaType .~ SwaggerObject
799− & properties . at fname ?~ ref
496+ & schemaProperties . at fname ?~ ref
800 & if isRequiredField
497 & if isRequiredField
801− then required %~ (++ [fname])
498+ then schemaRequired %~ (fname :)
802 else id
499 else id
803 where
500 where
804 fname = T.pack (fieldLabelModifier opts (selName (Proxy3 :: Proxy3 s f p)))
501 fname = T.pack (fieldLabelModifier opts (selName (Proxy3 :: Proxy3 s f p)))
805
502
806-- | Optional record fields.
503-- | Optional record fields.
807−instance OVERLAPPING_ (Selector s, ToSchema c) => GToSchema (S1 s (K1 i (Maybe c))) where
504+instance {-# OVERLAPPING #-} (Selector s, ToSchema c) => GToSchema (S1 s (K1 i (Maybe c))) where
808 gdeclareNamedSchema opts _ = fmap unnamed . withFieldSchema opts (Proxy2 :: Proxy2 s (K1 i (Maybe c))) False
505 gdeclareNamedSchema opts _ = fmap unnamed . withFieldSchema opts (Proxy2 :: Proxy2 s (K1 i (Maybe c))) False
809
506
810-- | Record fields.
507-- | Record fields.
811−instance OVERLAPPABLE_ (Selector s, GToSchema f) => GToSchema (S1 s f) where
508+instance {-# OVERLAPPABLE #-} (Selector s, GToSchema f) => GToSchema (S1 s f) where
812 gdeclareNamedSchema opts _ = fmap unnamed . withFieldSchema opts (Proxy2 :: Proxy2 s f) True
509 gdeclareNamedSchema opts _ = fmap unnamed . withFieldSchema opts (Proxy2 :: Proxy2 s f) True
813
510
814−instance OVERLAPPING_ ToSchema c => GToSchema (K1 i (Maybe c)) where
511+instance {-# OVERLAPPING #-} ToSchema c => GToSchema (K1 i (Maybe c)) where
815 gdeclareNamedSchema _ _ _ = declareNamedSchema (Proxy :: Proxy c)
512 gdeclareNamedSchema _ _ _ = declareNamedSchema (Proxy :: Proxy c)
816
513
817−instance OVERLAPPABLE_ ToSchema c => GToSchema (K1 i c) where
514+instance {-# OVERLAPPABLE #-} ToSchema c => GToSchema (K1 i c) where
818 gdeclareNamedSchema _ _ _ = declareNamedSchema (Proxy :: Proxy c)
515 gdeclareNamedSchema _ _ _ = declareNamedSchema (Proxy :: Proxy c)
819
516
820−instance ( GSumToSchema f
517+instance (GSumToSchema f, GSumToSchema g) => GToSchema (f :+: g) where
821− , GSumToSchema g
822− ) => GToSchema (f :+: g)
823− where
824− gdeclareNamedSchema = gdeclareNamedSumSchema
518+ gdeclareNamedSchema opts _ s
825−
826−gdeclareNamedSumSchema :: GSumToSchema f => SchemaOptions -> Proxy f -> Schema -> Declare (Definitions Schema) NamedSchema
827−gdeclareNamedSumSchema opts proxy s
828− | allNullaryToStringTag opts && allNullary = pure $ unnamed (toStringTag sumSchema)
519+ | allNullaryToStringTag opts && allNullary = pure $ unnamed (toStringTag sumSchema)
829− | otherwise = (unnamed . fst) <$> runWriterT declareSumSchema
520+ | otherwise = (unnamed . fst) <$> runWriterT declareSumSchema
830− where
521+ where
831− declareSumSchema = gsumToSchema opts proxy s
522+ declareSumSchema = gsumToSchema opts (Proxy :: Proxy (f :+: g)) s
832− (sumSchema, All allNullary) = undeclare (runWriterT declareSumSchema)
523+ (sumSchema, All allNullary) = undeclare (runWriterT declareSumSchema)
833
524
834− toStringTag schema = mempty
525+ toStringTag schema = mempty
835− & type_ ?~ SwaggerString
526+ & schemaType .~ SwaggerString
836− & enum_ ?~ map toJSON (schema ^.. properties.ifolded.asIndex)
527+ & schemaEnum ?~ map toJSON (schema ^.. schemaProperties.ifolded.asIndex)
837
528
838type AllNullary = All
529type AllNullary = All
839
530
840−class GSumToSchema (f :: * -> *) where
531+class GSumToSchema f where
841− gsumToSchema :: SchemaOptions -> Proxy f -> Schema -> WriterT AllNullary (Declare (Definitions Schema)) Schema
532+ gsumToSchema :: SchemaOptions -> proxy f -> Schema -> WriterT AllNullary (Declare Definitions) Schema
842
533
843instance (GSumToSchema f, GSumToSchema g) => GSumToSchema (f :+: g) where
534instance (GSumToSchema f, GSumToSchema g) => GSumToSchema (f :+: g) where
844− gsumToSchema opts _ = gsumToSchema opts (Proxy :: Proxy f) >=> gsumToSchema opts (Proxy :: Proxy g)
535+ gsumToSchema opts _ = gsumToSchema opts (Proxy :: Proxy f) <=< gsumToSchema opts (Proxy :: Proxy g)
845−
536+
846−gsumConToSchemaWith :: forall c f. (GToSchema (C1 c f), Constructor c) =>
537+gsumConToSchema :: forall c f proxy. (GToSchema (C1 c f), Constructor c) =>
847− Referenced Schema -> SchemaOptions -> Proxy (C1 c f) -> Schema -> Schema
538+ SchemaOptions -> proxy (C1 c f) -> Schema -> Declare Definitions Schema
848−gsumConToSchemaWith ref opts _ schema = schema
539+gsumConToSchema opts _ schema = do
540+ ref <- gdeclareSchemaRef opts (Proxy :: Proxy (C1 c f))
541+ return $ schema
849− & type_ ?~ SwaggerObject
542+ & schemaType .~ SwaggerObject
850− & properties . at tag ?~ ref
543+ & schemaProperties . at tag ?~ ref
851− & maxProperties ?~ 1
544+ & schemaMaxProperties ?~ 1
852− & minProperties ?~ 1
545+ & schemaMinProperties ?~ 1
853 where
546 where
854 tag = T.pack (constructorTagModifier opts (conName (Proxy3 :: Proxy3 c f p)))
547 tag = T.pack (constructorTagModifier opts (conName (Proxy3 :: Proxy3 c f p)))
855
548
856−gsumConToSchema :: (GToSchema (C1 c f), Constructor c) =>
857− SchemaOptions -> Proxy (C1 c f) -> Schema -> Declare (Definitions Schema) Schema
858−gsumConToSchema opts proxy schema = do
859− ref <- gdeclareSchemaRef opts proxy
860− return $ gsumConToSchemaWith ref opts proxy schema
861−
862−instance OVERLAPPABLE_ (Constructor c, GToSchema f) => GSumToSchema (C1 c f) where
549+instance {-# OVERLAPPABLE #-} (Constructor c, GToSchema f) => GSumToSchema (C1 c f) where
863 gsumToSchema opts proxy schema = do
550 gsumToSchema opts proxy schema = do
864 tell (All False)
551 tell (All False)
865 lift $ gsumConToSchema opts proxy schema
552 lift $ gsumConToSchema opts proxy schema
@@ -870,13 +557,9 @@ instance (Constructor c, Selector s, GToSchema f) => GSumToSchema (C1 c (S1 s f)
870 lift $ gsumConToSchema opts proxy schema
557 lift $ gsumConToSchema opts proxy schema
871
558
872instance Constructor c => GSumToSchema (C1 c U1) where
559instance Constructor c => GSumToSchema (C1 c U1) where
873− gsumToSchema opts proxy = pure . gsumConToSchemaWith (Inline nullarySchema) opts proxy
560+ gsumToSchema opts proxy = lift . gsumConToSchema opts proxy
874
561
875data Proxy2 a b = Proxy2
562data Proxy2 a b = Proxy2
876
563
877data Proxy3 a b c = Proxy3
564data Proxy3 a b c = Proxy3
878
565
879−-- $setup
880−-- >>> import Data.Swagger
881−-- >>> import Data.Aeson (encode)
882−-- >>> import Data.Aeson.Types (toJSONKeyText)
src/Data/Swagger/Internal/Schema/Validation.hsdeleted−511
@@ -1,511 +0,0 @@
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.hsdeleted−66
@@ -1,66 +0,0 @@
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+40−41
@@ -1,16 +1,12 @@
1{-# LANGUAGE DefaultSignatures #-}
1{-# LANGUAGE DefaultSignatures #-}
2{-# LANGUAGE FlexibleContexts #-}
2{-# LANGUAGE FlexibleContexts #-}
3−{-# LANGUAGE FlexibleInstances #-}
4{-# LANGUAGE OverloadedStrings #-}
3{-# LANGUAGE OverloadedStrings #-}
5{-# LANGUAGE RankNTypes #-}
4{-# LANGUAGE RankNTypes #-}
6{-# LANGUAGE TypeOperators #-}
5{-# LANGUAGE TypeOperators #-}
7module Data.Swagger.Internal.Utils where
6module Data.Swagger.Internal.Utils where
8
7
9−import Prelude ()
8+import Control.Arrow (first)
10−import Prelude.Compat
11−
12−import Control.Lens ((&), (%~))
13−import Control.Lens.TH
9+import Control.Applicative
14import Data.Aeson
10import Data.Aeson
15import Data.Aeson.Types
11import Data.Aeson.Types
16import Data.Char
12import Data.Char
@@ -18,39 +14,27 @@ import Data.Data
18import Data.Hashable (Hashable)
14import Data.Hashable (Hashable)
19import Data.HashMap.Strict (HashMap)
15import Data.HashMap.Strict (HashMap)
20import qualified Data.HashMap.Strict as HashMap
16import qualified Data.HashMap.Strict as HashMap
21−import Data.HashMap.Strict.InsOrd (InsOrdHashMap)
17+import Data.Monoid
22−import qualified Data.HashMap.Strict.InsOrd as InsOrdHashMap
23−import Data.Map (Map)
24−import Data.Set (Set)
25import Data.Text (Text)
18import Data.Text (Text)
26import GHC.Generics
19import GHC.Generics
27−import Language.Haskell.TH (mkName)
20+import Text.Read (readMaybe)
28−
29−swaggerFieldRules :: LensRules
30−swaggerFieldRules = defaultFieldRules & lensField %~ swaggerFieldNamer
31− where
32− swaggerFieldNamer namer dname fnames fname =
33− map fixDefName (namer dname fnames fname)
34−
35− fixDefName (MethodName cname mname) = MethodName cname (fixName mname)
36− fixDefName (TopName name) = TopName (fixName name)
37−
38− fixName = mkName . fixName' . show
39−
40− fixName' "in" = "in_" -- keyword
41− fixName' "type" = "type_" -- keyword
42− fixName' "default" = "default_" -- keyword
43− fixName' "minimum" = "minimum_" -- Prelude conflict
44− fixName' "maximum" = "maximum_" -- Prelude conflict
45− fixName' "enum" = "enum_" -- Control.Lens conflict
46− fixName' "head" = "head_" -- Prelude conflict
47− fixName' n = n
48
21
49gunfoldEnum :: String -> [a] -> (forall b r. Data b => c (b -> r) -> c r) -> (forall r. r -> c r) -> Constr -> c a
22gunfoldEnum :: String -> [a] -> (forall b r. Data b => c (b -> r) -> c r) -> (forall r. r -> c r) -> Constr -> c a
50gunfoldEnum tname xs _k z c = case lookup (constrIndex c) (zip [1..] xs) of
23gunfoldEnum tname xs _k z c = case lookup (constrIndex c) (zip [1..] xs) of
51 Just x -> z x
24 Just x -> z x
52 Nothing -> error $ "Data.Data.gunfold: Constructor " ++ show c ++ " is not of type " ++ tname ++ "."
25 Nothing -> error $ "Data.Data.gunfold: Constructor " ++ show c ++ " is not of type " ++ tname ++ "."
53
26
27+hashMapMapKeys :: (Eq k', Hashable k') => (k -> k') -> HashMap k v -> HashMap k' v
28+hashMapMapKeys f = HashMap.fromList . map (first f) . HashMap.toList
29+
30+hashMapTraverseKeys :: (Eq k', Hashable k', Applicative f) => (k -> f k') -> HashMap k v -> f (HashMap k' v)
31+hashMapTraverseKeys f = fmap HashMap.fromList . traverse g . HashMap.toList
32+ where
33+ g (x, y) = (\a -> (a, y)) <$> f x
34+
35+hashMapReadKeys :: (Eq k, Read k, Hashable k, Alternative f) => HashMap String v -> f (HashMap k v)
36+hashMapReadKeys = hashMapTraverseKeys (maybe empty pure . readMaybe)
37+
54jsonPrefix :: String -> Options
38jsonPrefix :: String -> Options
55jsonPrefix prefix = defaultOptions
39jsonPrefix prefix = defaultOptions
56 { fieldLabelModifier = modifier . drop 1
40 { fieldLabelModifier = modifier . drop 1
@@ -72,10 +56,34 @@ parseOneOf xs js =
72 where
56 where
73 ys = zip (map toJSON xs) xs
57 ys = zip (map toJSON xs) xs
74
58
59+omitEmpties :: Value -> Value
60+omitEmpties (Object o) = Object (HashMap.filter nonEmpty o)
61+ where
62+ nonEmpty js = (js /= Object mempty) && (js /= Array mempty) && (js /= Null)
63+omitEmpties js = js
64+
65+genericToJSONWithSub :: (Generic a, GToJSON (Rep a)) => Text -> Options -> a -> Value
66+genericToJSONWithSub sub opts x =
67+ case genericToJSON opts x of
68+ Object o ->
69+ let so = HashMap.lookupDefault (error "impossible") sub o
70+ in Object (HashMap.delete sub o) <+> so
71+ _ -> error "genericToJSONWithSub: subjson is not an object"
72+
73+genericParseJSONWithSub :: (Generic a, GFromJSON (Rep a)) => Text -> Options -> Value -> Parser a
74+genericParseJSONWithSub sub opts (Object o) = genericParseJSON opts js
75+ where
76+ js = Object (HashMap.insert sub (Object o) o)
77+genericParseJSONWithSub _ _ _ = error "genericParseJSONWithSub: given json is not an object"
78+
75(<+>) :: Value -> Value -> Value
79(<+>) :: Value -> Value -> Value
76Object x <+> Object y = Object (x <> y)
80Object x <+> Object y = Object (x <> y)
77_ <+> _ = error "<+>: merging non-objects"
81_ <+> _ = error "<+>: merging non-objects"
78
82
83+withDefaults :: (Value -> Parser a) -> [Pair] -> Value -> Parser a
84+withDefaults parser defs js@(Object _) = parser (js <+> object defs)
85+withDefaults _ _ _ = empty
86+
79genericMempty :: (Generic a, GMonoid (Rep a)) => a
87genericMempty :: (Generic a, GMonoid (Rep a)) => a
80genericMempty = to gmempty
88genericMempty = to gmempty
81
89
@@ -111,16 +119,6 @@ class SwaggerMonoid m where
111 swaggerMappend = mappend
119 swaggerMappend = mappend
112
120
113instance SwaggerMonoid [a]
121instance SwaggerMonoid [a]
114−instance Ord a => SwaggerMonoid (Set a)
115−instance Ord k => SwaggerMonoid (Map k v)
116−
117−instance (Eq k, Hashable k) => SwaggerMonoid (HashMap k v) where
118− swaggerMempty = mempty
119− swaggerMappend = HashMap.unionWith (\_old new -> new)
120−
121−instance (Eq k, Hashable k) => SwaggerMonoid (InsOrdHashMap k v) where
122− swaggerMempty = mempty
123− swaggerMappend = InsOrdHashMap.unionWith (\_old new -> new)
124
122
125instance SwaggerMonoid Text where
123instance SwaggerMonoid Text where
126 swaggerMempty = mempty
124 swaggerMempty = mempty
@@ -131,3 +129,4 @@ instance SwaggerMonoid (Maybe a) where
131 swaggerMempty = Nothing
129 swaggerMempty = Nothing
132 swaggerMappend x Nothing = x
130 swaggerMappend x Nothing = x
133 swaggerMappend _ y = y
131 swaggerMappend _ y = y
132+
src/Data/Swagger/Lens.hs+121−167
@@ -1,186 +1,140 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE FlexibleContexts #-}
3{-# LANGUAGE FlexibleInstances #-}
1{-# LANGUAGE FlexibleInstances #-}
4{-# LANGUAGE FunctionalDependencies #-}
2{-# LANGUAGE FunctionalDependencies #-}
5{-# LANGUAGE GADTs #-}
3{-# LANGUAGE GADTs #-}
6{-# LANGUAGE MultiParamTypeClasses #-}
4{-# LANGUAGE MultiParamTypeClasses #-}
7−{-# LANGUAGE RankNTypes #-}
8{-# LANGUAGE TemplateHaskell #-}
5{-# LANGUAGE TemplateHaskell #-}
9−{-# LANGUAGE TypeFamilies #-}
10−{-# LANGUAGE DataKinds #-}
11−{-# LANGUAGE UndecidableInstances #-}
12−{-# OPTIONS_GHC -fno-warn-orphans #-}
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.
20module Data.Swagger.Lens where
6module Data.Swagger.Lens where
21
7
22import Control.Lens
8import Control.Lens
23import Data.Aeson (Value)
9import Data.Aeson (Value)
24import Data.Scientific (Scientific)
10import Data.Scientific (Scientific)
25import Data.Swagger.Internal
11import Data.Swagger.Internal
26−import Data.Swagger.Internal.Utils
27import Data.Text (Text)
12import Data.Text (Text)
28
13
14+-- =======================================================================
29−-- * Classy lenses
15+-- * TH derived lenses
30−
16+
31−makeFields ''Swagger
17+-- ** 'Swagger' lenses
32−makeFields ''Host
18+makeLenses ''Swagger
33−makeFields ''Info
19+-- ** 'Host' lenses
34−makeFields ''Contact
20+makeLenses ''Host
35−makeFields ''License
21+-- ** 'Info' lenses
36−makeLensesWith swaggerFieldRules ''PathItem
22+makeLenses ''Info
37−makeFields ''Tag
23+-- ** 'Contact' lenses
38−makeFields ''Operation
24+makeLenses ''Contact
39−makeFields ''Param
25+-- ** 'License' lenses
40−makeLensesWith swaggerFieldRules ''ParamOtherSchema
26+makeLenses ''License
41−makeFields ''Header
27+-- ** 'Paths' lenses
42−makeFields ''Schema
28+makeLenses ''Paths
43−makeFields ''NamedSchema
29+-- ** 'PathItem' lenses
44−makeLensesWith swaggerFieldRules ''ParamSchema
30+makeLenses ''PathItem
45−makeFields ''Xml
31+-- ** 'Tag' lenses
46−makeLensesWith swaggerFieldRules ''Responses
32+makeLenses ''Tag
47−makeFields ''Response
33+-- ** 'Operation' lenses
48−makeLensesWith swaggerFieldRules ''SecurityScheme
34+makeLenses ''Operation
49−makeFields ''ApiKeyParams
35+-- ** 'Param' lenses
50−makeFields ''OAuth2Params
36+makeLenses ''Param
51−makeFields ''ExternalDocs
52−
53−-- * Prisms
54-- ** 'ParamAnySchema' prisms
37-- ** 'ParamAnySchema' prisms
55makePrisms ''ParamAnySchema
38makePrisms ''ParamAnySchema
39+-- ** 'ParamOtherSchema' lenses
40+makeLenses ''ParamOtherSchema
41+-- ** 'Items' lenses
42+makeLenses ''Items
43+-- ** 'Header' lenses
44+makeLenses ''Header
45+-- ** 'Schema' lenses
46+makeLenses ''Schema
47+-- ** 'SwaggerItems' prisms
48+makePrisms ''SwaggerItems
49+-- ** 'ParamSchema' lenses
50+makeLenses ''ParamSchema
51+-- ** 'Xml' lenses
52+makeLenses ''Xml
53+-- ** 'Responses' lenses
54+makeLenses ''Responses
55+-- ** 'Response' lenses
56+makeLenses ''Response
57+-- ** 'SecurityScheme' lenses
58+makeLenses ''SecurityScheme
56-- ** 'SecuritySchemeType' prisms
59-- ** 'SecuritySchemeType' prisms
57makePrisms ''SecuritySchemeType
60makePrisms ''SecuritySchemeType
58−-- ** 'Referenced' prisms
61+-- ** 'ApiKeyParams' lenses
59−makePrisms ''Referenced
62+makeLenses ''ApiKeyParams
63+-- ** 'OAuth2Params' lenses
64+makeLenses ''OAuth2Params
65+-- ** 'ExternalDocs' lenses
66+makeLenses ''ExternalDocs
60
67
61−-- ** 'SwaggerItems' prisms
68+-- =======================================================================
69+-- * Helper classy lenses
70+
71+class HasDescription s d | s -> d where
72+ description :: Lens' s d
73+
74+instance HasDescription Response Text where description = responseDescription
75+instance HasDescription Info (Maybe Text) where description = infoDescription
76+instance HasDescription Tag (Maybe Text) where description = tagDescription
77+instance HasDescription Operation (Maybe Text) where description = operationDescription
78+instance HasDescription Param (Maybe Text) where description = paramDescription
79+instance HasDescription Header (Maybe Text) where description = headerDescription
80+instance HasDescription Schema (Maybe Text) where description = schemaDescription
81+instance HasDescription SecurityScheme (Maybe Text) where description = securitySchemeDescription
82+instance HasDescription ExternalDocs (Maybe Text) where description = externalDocsDescription
83+
84+class HasParamSchema s t | s -> t where
85+ parameterSchema :: Lens' s (ParamSchema t)
86+
87+instance HasParamSchema Schema Schema where parameterSchema = schemaParamSchema
88+instance HasParamSchema ParamOtherSchema ParamOtherSchema where parameterSchema = paramOtherSchemaParamSchema
89+instance HasParamSchema Items Items where parameterSchema = itemsParamSchema
90+instance HasParamSchema Header Header where parameterSchema = headerParamSchema
91+instance HasParamSchema (ParamSchema t) t where parameterSchema = id
92+
93+schemaType :: HasParamSchema s t => Lens' s (SwaggerType t)
94+schemaType = parameterSchema.paramSchemaType
95+
96+schemaFormat :: HasParamSchema s t => Lens' s (Maybe Format)
97+schemaFormat = parameterSchema.paramSchemaFormat
98+
99+schemaItems :: HasParamSchema s t => Lens' s (Maybe (SwaggerItems t))
100+schemaItems = parameterSchema.paramSchemaItems
101+
102+schemaDefault :: HasParamSchema s t => Lens' s (Maybe Value)
103+schemaDefault = parameterSchema.paramSchemaDefault
104+
105+schemaMaximum :: HasParamSchema s t => Lens' s (Maybe Scientific)
106+schemaMaximum = parameterSchema.paramSchemaMaximum
107+
108+schemaExclusiveMaximum :: HasParamSchema s t => Lens' s (Maybe Bool)
109+schemaExclusiveMaximum = parameterSchema.paramSchemaExclusiveMaximum
110+
111+schemaMinimum :: HasParamSchema s t => Lens' s (Maybe Scientific)
112+schemaMinimum = parameterSchema.paramSchemaMinimum
113+
114+schemaExclusiveMinimum :: HasParamSchema s t => Lens' s (Maybe Bool)
115+schemaExclusiveMinimum = parameterSchema.paramSchemaExclusiveMinimum
116+
117+schemaMaxLength :: HasParamSchema s t => Lens' s (Maybe Integer)
118+schemaMaxLength = parameterSchema.paramSchemaMaxLength
119+
120+schemaMinLength :: HasParamSchema s t => Lens' s (Maybe Integer)
121+schemaMinLength = parameterSchema.paramSchemaMinLength
122+
123+schemaPattern :: HasParamSchema s t => Lens' s (Maybe Text)
124+schemaPattern = parameterSchema.paramSchemaPattern
125+
126+schemaMaxItems :: HasParamSchema s t => Lens' s (Maybe Integer)
127+schemaMaxItems = parameterSchema.paramSchemaMaxItems
128+
129+schemaMinItems :: HasParamSchema s t => Lens' s (Maybe Integer)
130+schemaMinItems = parameterSchema.paramSchemaMinItems
131+
132+schemaUniqueItems :: HasParamSchema s t => Lens' s (Maybe Bool)
133+schemaUniqueItems = parameterSchema.paramSchemaUniqueItems
134+
135+schemaEnum :: HasParamSchema s t => Lens' s (Maybe [Value])
136+schemaEnum = parameterSchema.paramSchemaEnum
137+
138+schemaMultipleOf :: HasParamSchema s t => Lens' s (Maybe Scientific)
139+schemaMultipleOf = parameterSchema.paramSchemaMultipleOf
62
140
63−_SwaggerItemsArray :: Review (SwaggerItems 'SwaggerKindSchema) [Referenced Schema]
64−_SwaggerItemsArray
65− = unto (\x -> SwaggerItemsArray x)
66−{- \x -> case x of
67− SwaggerItemsPrimitive c p -> Left (SwaggerItemsPrimitive c p)
68− SwaggerItemsObject o -> Left (SwaggerItemsObject o)
69− SwaggerItemsArray a -> Right a
70−-}
71−
72−_SwaggerItemsObject :: Review (SwaggerItems 'SwaggerKindSchema) (Referenced Schema)
73−_SwaggerItemsObject
74− = unto (\x -> SwaggerItemsObject x)
75−{- \x -> case x of
76− SwaggerItemsPrimitive c p -> Left (SwaggerItemsPrimitive c p)
77− SwaggerItemsObject o -> Right o
78− SwaggerItemsArray a -> Left (SwaggerItemsArray a)
79−-}
80−
81−_SwaggerItemsPrimitive :: forall t p f. (Profunctor p, Bifunctor p, Functor f) => Optic' p f (SwaggerItems t) (Maybe (CollectionFormat t), ParamSchema t)
82−_SwaggerItemsPrimitive = unto (\(c, p) -> SwaggerItemsPrimitive c p)
83−
84−-- =============================================================
85−-- More helpful instances for easier access to schema properties
86−
87−type instance Index Responses = HttpStatusCode
88−type instance Index Operation = HttpStatusCode
89−
90−type instance IxValue Responses = Referenced Response
91−type instance IxValue Operation = Referenced Response
92−
93−instance Ixed Responses where ix n = responses . ix n
94−instance At Responses where at n = responses . at n
95−
96−instance Ixed Operation where ix n = responses . ix n
97−instance At Operation where at n = responses . at n
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−
107−-- HasType instances
108−instance HasType Header (Maybe (SwaggerType ('SwaggerKindNormal Header))) where type_ = paramSchema.type_
109−instance HasType Schema (Maybe (SwaggerType 'SwaggerKindSchema)) where type_ = paramSchema.type_
110−instance HasType NamedSchema (Maybe (SwaggerType 'SwaggerKindSchema)) where type_ = paramSchema.type_
111−instance HasType ParamOtherSchema (Maybe (SwaggerType 'SwaggerKindParamOtherSchema)) where type_ = paramSchema.type_
112−
113−-- HasDefault instances
114−instance HasDefault Header (Maybe Value) where default_ = paramSchema.default_
115−instance HasDefault Schema (Maybe Value) where default_ = paramSchema.default_
116−instance HasDefault ParamOtherSchema (Maybe Value) where default_ = paramSchema.default_
117−
118−-- OVERLAPPABLE instances
119−
120−instance
121−#if __GLASGOW_HASKELL__ >= 710
122− OVERLAPPABLE_
123−#endif
124− HasParamSchema s (ParamSchema t)
125− => HasFormat s (Maybe Format) where
126− format = paramSchema.format
127−
128−instance
129−#if __GLASGOW_HASKELL__ >= 710
130− OVERLAPPABLE_
131−#endif
132− HasParamSchema s (ParamSchema t)
133− => HasItems s (Maybe (SwaggerItems t)) where
134− items = paramSchema.items
135−
136−instance
137−#if __GLASGOW_HASKELL__ >= 710
138− OVERLAPPABLE_
139−#endif
140− HasParamSchema s (ParamSchema t)
141− => HasMaximum s (Maybe Scientific) where
142− maximum_ = paramSchema.maximum_
143−
144−instance OVERLAPPABLE_ HasParamSchema s (ParamSchema t)
145− => HasExclusiveMaximum s (Maybe Bool) where
146− exclusiveMaximum = paramSchema.exclusiveMaximum
147−
148−instance OVERLAPPABLE_ HasParamSchema s (ParamSchema t)
149− => HasMinimum s (Maybe Scientific) where
150− minimum_ = paramSchema.minimum_
151−
152−instance OVERLAPPABLE_ HasParamSchema s (ParamSchema t)
153− => HasExclusiveMinimum s (Maybe Bool) where
154− exclusiveMinimum = paramSchema.exclusiveMinimum
155−
156−instance OVERLAPPABLE_ HasParamSchema s (ParamSchema t)
157− => HasMaxLength s (Maybe Integer) where
158− maxLength = paramSchema.maxLength
159−
160−instance OVERLAPPABLE_ HasParamSchema s (ParamSchema t)
161− => HasMinLength s (Maybe Integer) where
162− minLength = paramSchema.minLength
163−
164−instance OVERLAPPABLE_ HasParamSchema s (ParamSchema t)
165− => HasPattern s (Maybe Text) where
166− pattern = paramSchema.pattern
167−
168−instance OVERLAPPABLE_ HasParamSchema s (ParamSchema t)
169− => HasMaxItems s (Maybe Integer) where
170− maxItems = paramSchema.maxItems
171−
172−instance OVERLAPPABLE_ HasParamSchema s (ParamSchema t)
173− => HasMinItems s (Maybe Integer) where
174− minItems = paramSchema.minItems
175−
176−instance OVERLAPPABLE_ HasParamSchema s (ParamSchema t)
177− => HasUniqueItems s (Maybe Bool) where
178− uniqueItems = paramSchema.uniqueItems
179−
180−instance OVERLAPPABLE_ HasParamSchema s (ParamSchema t)
181− => HasEnum s (Maybe [Value]) where
182− enum_ = paramSchema.enum_
183−
184−instance OVERLAPPABLE_ HasParamSchema s (ParamSchema t)
185− => HasMultipleOf s (Maybe Scientific) where
186− multipleOf = paramSchema.multipleOf
src/Data/Swagger/Operation.hsdeleted−193
@@ -1,193 +0,0 @@
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.hsdeleted−597
@@ -1,597 +0,0 @@
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+2−5
@@ -1,5 +1,7 @@
1-- |
1-- |
2-- Module: Data.Swagger.ParamSchema
2-- Module: Data.Swagger.ParamSchema
3+-- Copyright: (c) 2015 GetShopTV
4+-- License: BSD3
3-- Maintainer: Nickolay Kudasov <nickolay@getshoptv.com>
5-- Maintainer: Nickolay Kudasov <nickolay@getshoptv.com>
4-- Stability: experimental
6-- Stability: experimental
5--
7--
@@ -12,11 +14,6 @@ module Data.Swagger.ParamSchema (
12 genericToParamSchema,
14 genericToParamSchema,
13 toParamSchemaBoundedIntegral,
15 toParamSchemaBoundedIntegral,
14
16
15− -- * Schema templates
16− passwordParamSchema,
17− binaryParamSchema,
18− byteParamSchema,
19−
20 -- * Generic encoding configuration
17 -- * Generic encoding configuration
21 SchemaOptions(..),
18 SchemaOptions(..),
22 defaultSchemaOptions,
19 defaultSchemaOptions,
src/Data/Swagger/Schema.hs+4−24
@@ -1,5 +1,7 @@
1-- |
1-- |
2-- Module: Data.Swagger.Schema
2-- Module: Data.Swagger.Schema
3+-- Copyright: (c) 2015 GetShopTV
4+-- License: BSD3
3-- Maintainer: Nickolay Kudasov <nickolay@getshoptv.com>
5-- Maintainer: Nickolay Kudasov <nickolay@getshoptv.com>
4-- Stability: experimental
6-- Stability: experimental
5--
7--
@@ -7,6 +9,8 @@
7module Data.Swagger.Schema (
9module Data.Swagger.Schema (
8 -- * Encoding
10 -- * Encoding
9 ToSchema(..),
11 ToSchema(..),
12+ Definitions,
13+ NamedSchema,
10 declareSchema,
14 declareSchema,
11 declareSchemaRef,
15 declareSchemaRef,
12 toSchema,
16 toSchema,
@@ -17,34 +21,11 @@ module Data.Swagger.Schema (
17 -- * Generic schema encoding
21 -- * Generic schema encoding
18 genericDeclareNamedSchema,
22 genericDeclareNamedSchema,
19 genericDeclareSchema,
23 genericDeclareSchema,
20− genericDeclareNamedSchemaNewtype,
21− genericNameSchema,
22−
23− -- ** 'Bounded' 'Integral'
24 genericToNamedSchemaBoundedIntegral,
24 genericToNamedSchemaBoundedIntegral,
25 toSchemaBoundedIntegral,
25 toSchemaBoundedIntegral,
26−
27− -- ** 'Bounded' 'Enum' key mappings
28− declareSchemaBoundedEnumKeyMapping,
29− toSchemaBoundedEnumKeyMapping,
30−
31− -- ** Reusing 'ToParamSchema'
32 paramSchemaToNamedSchema,
26 paramSchemaToNamedSchema,
33 paramSchemaToSchema,
27 paramSchemaToSchema,
34
28
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−
48 -- * Inlining @'Schema'@s
29 -- * Inlining @'Schema'@s
49 inlineNonRecursiveSchemas,
30 inlineNonRecursiveSchemas,
50 inlineAllSchemas,
31 inlineAllSchemas,
@@ -54,7 +35,6 @@ module Data.Swagger.Schema (
54 -- * Generic encoding configuration
35 -- * Generic encoding configuration
55 SchemaOptions(..),
36 SchemaOptions(..),
56 defaultSchemaOptions,
37 defaultSchemaOptions,
57− fromAesonOptions,
58) where
38) where
59
39
60import Data.Swagger.Internal.Schema
40import Data.Swagger.Internal.Schema
src/Data/Swagger/Schema/Generator.hsdeleted−114
@@ -1,114 +0,0 @@
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.hsdeleted−90
@@ -1,90 +0,0 @@
1−-- |
2−-- Module: Data.Swagger.Schema.Validation
3−-- Maintainer: Nickolay Kudasov <nickolay@getshoptv.com>
4−-- Stability: experimental
5−--
6−-- Validate JSON values with Swagger Schema.
7−module Data.Swagger.Schema.Validation (
8− -- * How to use validation
9− -- $howto
10−
11− -- ** Examples
12− -- $examples
13−
14− -- ** Validating @'Maybe'@
15− -- $maybe
16−
17− -- * JSON validation
18−
19− ValidationError,
20−
21− -- ** Using 'ToJSON' and 'ToSchema'
22− validatePrettyToJSON,
23− validateToJSON,
24− validateToJSONWithPatternChecker,
25− renderValidationErrors,
26−
27− -- ** Using 'Value' and 'Schema'
28− validateJSON,
29− validateJSONWithPatternChecker,
30−) where
31−
32−import Data.Swagger.Internal.Schema.Validation
33−
34−-- $setup
35−-- >>> import Control.Lens
36−-- >>> import Data.Aeson
37−-- >>> import Data.Proxy
38−-- >>> import Data.Swagger
39−-- >>> import GHC.Generics
40−-- >>> :set -XDeriveGeneric
41−
42−-- $howto
43−--
44−-- This module provides helpful functions for JSON validation.
45−-- These functions are meant to be used in test suites for your application
46−-- to ensure that JSON respresentation for your data corresponds to
47−-- schemas you're using for the Swagger specification.
48−--
49−-- It is recommended to use validation functions as QuickCheck properties
50−-- (see <http://hackage.haskell.org/package/QuickCheck>).
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,14 +1,5 @@
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'@.
8module Data.Swagger.SchemaOptions where
1module Data.Swagger.SchemaOptions where
9
2
10−import qualified Data.Aeson.Types as Aeson
11−
12-- | Options that specify how to encode your type to Swagger schema.
3-- | Options that specify how to encode your type to Swagger schema.
13data SchemaOptions = SchemaOptions
4data SchemaOptions = SchemaOptions
14 { -- | Function applied to field labels. Handy for removing common record prefixes for example.
5 { -- | Function applied to field labels. Handy for removing common record prefixes for example.
@@ -44,29 +35,3 @@ defaultSchemaOptions = SchemaOptions
44 , unwrapUnaryRecords = False
35 , unwrapUnaryRecords = False
45 }
36 }
46
37
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.yaml+2−6
@@ -1,9 +1,5 @@
1−resolver: lts-14.3
1+flags: {}
2packages:
2packages:
3- '.'
3- '.'
4extra-deps:
4extra-deps:
5−- optics-core-0.2
5+resolver: lts-3.12
6−- optics-th-0.2
7−- optics-extra-0.2
8−- indexed-profunctors-0.1
9−- insert-ordered-containers-0.2.3
swagger2.cabal+33−107
@@ -1,152 +1,78 @@
1−cabal-version: >=1.10
2name: swagger2
1name: swagger2
3−version: 2.5
2+version: 0.4.1
4−
5synopsis: Swagger 2.0 data model
3synopsis: Swagger 2.0 data model
6−category: Web, Swagger
7−description:
4+description: Please see README.md
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−
13homepage: https://github.com/GetShopTV/swagger2
5homepage: https://github.com/GetShopTV/swagger2
14bug-reports: https://github.com/GetShopTV/swagger2/issues
6bug-reports: https://github.com/GetShopTV/swagger2/issues
15license: BSD3
7license: BSD3
16license-file: LICENSE
8license-file: LICENSE
17author: Nickolay Kudasov
9author: Nickolay Kudasov
18maintainer: nickolay@getshoptv.com
10maintainer: nickolay@getshoptv.com
19−copyright: (c) 2015-2016, GetShopTV
11+copyright: (c) 2015, GetShopTV
12+category: Web
20−build-type: Custom
13+build-type: Simple
21extra-source-files:
14extra-source-files:
22 README.md
15 README.md
23 , CHANGELOG.md
16 , CHANGELOG.md
24 , examples/*.hs
17 , examples/*.hs
25− , include/overlapping-compat.h
18+cabal-version: >=1.10
26−tested-with:
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
36
19
37library
20library
38 hs-source-dirs: src
21 hs-source-dirs: src
39− include-dirs: include
40 exposed-modules:
22 exposed-modules:
41 Data.Swagger
23 Data.Swagger
42 Data.Swagger.Declare
24 Data.Swagger.Declare
43 Data.Swagger.Lens
25 Data.Swagger.Lens
44− Data.Swagger.Operation
45− Data.Swagger.Optics
46 Data.Swagger.ParamSchema
26 Data.Swagger.ParamSchema
47 Data.Swagger.Schema
27 Data.Swagger.Schema
48− Data.Swagger.Schema.Generator
49− Data.Swagger.Schema.Validation
50 Data.Swagger.SchemaOptions
28 Data.Swagger.SchemaOptions
51
29
52 -- internal modules
30 -- internal modules
53 Data.Swagger.Internal
31 Data.Swagger.Internal
54 Data.Swagger.Internal.Schema
32 Data.Swagger.Internal.Schema
55− Data.Swagger.Internal.Schema.Validation
56 Data.Swagger.Internal.ParamSchema
33 Data.Swagger.Internal.ParamSchema
57 Data.Swagger.Internal.Utils
34 Data.Swagger.Internal.Utils
58− Data.Swagger.Internal.AesonUtils
59− Data.Swagger.Internal.TypeShape
60−
61− -- GHC boot libraries
62− build-depends:
35+ build-depends: base == 4.*
63− base >=4.9 && <4.14
64− , aeson-pretty >=0.8.7 && <0.9
36+ , aeson
65− , bytestring >=0.10.4.0 && <0.11
66− , containers >=0.5.5.1 && <0.7
37+ , containers
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
78− , aeson >=1.4.2.0 && <1.5
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
82− , hashable >=1.2.7.0 && <1.4
38+ , hashable
83− , http-media >=0.7.1.2 && <0.9
39+ , http-media
40+ , mtl
41+ , network
42+ , text
43+ , time
84− , insert-ordered-containers >=0.2.3 && <0.3
44+ , unordered-containers
85− , lens >=4.16.1 && <4.19
45+ , lens
86− , network >=2.6.3.5 && <3.2
87− , optics-core >=0.2 && <0.3
88− , optics-th >=0.2 && <0.3
89− , scientific >=0.3.6.2 && <0.4
46+ , scientific
90− , transformers-compat >=0.3 && <0.7
91− , unordered-containers >=0.2.9.0 && <0.3
92− , uuid-types >=1.0.3 && <1.1
93− , vector >=0.12.0.1 && <0.13
94− , QuickCheck >=2.10.1 && <2.14
95−
96 default-language: Haskell2010
47 default-language: Haskell2010
97
48
98test-suite spec
49test-suite spec
99 type: exitcode-stdio-1.0
50 type: exitcode-stdio-1.0
100 hs-source-dirs: test
51 hs-source-dirs: test
101 main-is: Spec.hs
52 main-is: Spec.hs
102−
103− -- From library parat
104− -- We need aeson's toEncoding for doctests too
105− build-depends:
53+ build-depends: base == 4.*
106− base
107− , swagger2
54+ , swagger2
108− , aeson
55+ , hspec
109− , base-compat-batteries
56+ , HUnit
110− , bytestring
57+ , QuickCheck
111− , containers
112− , hashable
113− , insert-ordered-containers
114− , lens
115− , mtl
116− , template-haskell
117− , text
58+ , text
118− , time
59+ , aeson
60+ , aeson-qq
61+ , containers
119− , unordered-containers
62+ , unordered-containers
120− , vector
63+ , vector
121− , QuickCheck
64+ , lens
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−
134 other-modules:
65 other-modules:
135 SpecCommon
66 SpecCommon
136 Data.SwaggerSpec
67 Data.SwaggerSpec
137− Data.Swagger.CommonTestTypes
138− Data.Swagger.ParamSchemaSpec
139 Data.Swagger.SchemaSpec
68 Data.Swagger.SchemaSpec
140− Data.Swagger.Schema.ValidationSpec
141− Data.Swagger.Schema.GeneratorSpec
142 default-language: Haskell2010
69 default-language: Haskell2010
143
70
144−test-suite doctests
71+test-suite doctest
145− -- See QuickCheck note in https://github.com/phadej/cabal-doctest#notes
146− build-depends: base, doctest, Glob, QuickCheck
72+ build-depends: base, doctest, Glob
147 default-language: Haskell2010
73 default-language: Haskell2010
148 hs-source-dirs: test
74 hs-source-dirs: test
149− main-is: doctests.hs
75+ main-is: DocTest.hs
150 type: exitcode-stdio-1.0
76 type: exitcode-stdio-1.0
151
77
152source-repository head
78source-repository head
test/Data/Swagger/CommonTestTypes.hsdeleted−679
@@ -1,679 +0,0 @@
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+68−11
@@ -1,40 +1,97 @@
1{-# LANGUAGE DeriveGeneric #-}
1{-# LANGUAGE DeriveGeneric #-}
2−{-# LANGUAGE DataKinds #-}
2+{-# LANGUAGE DeriveAnyClass #-}
3{-# LANGUAGE ScopedTypeVariables #-}
3{-# LANGUAGE ScopedTypeVariables #-}
4{-# LANGUAGE TemplateHaskell #-}
4{-# LANGUAGE TemplateHaskell #-}
5{-# LANGUAGE QuasiQuotes #-}
5{-# LANGUAGE QuasiQuotes #-}
6−{-# LANGUAGE OverloadedStrings #-}
7module Data.Swagger.ParamSchemaSpec where
6module Data.Swagger.ParamSchemaSpec where
8
7
9import Data.Aeson
8import Data.Aeson
10−import Data.Aeson.QQ.Simple
9+import Data.Aeson.QQ
11import Data.Char
10import Data.Char
12import Data.Proxy
11import Data.Proxy
12+import Data.Set (Set)
13import GHC.Generics
13import GHC.Generics
14
14
15import Data.Swagger
15import Data.Swagger
16−import Data.Swagger.Internal (SwaggerKind(..))
17
16
18−import Data.Swagger.CommonTestTypes
19import SpecCommon
17import SpecCommon
20import Test.Hspec
18import Test.Hspec
21−import Data.Time.LocalTime
22−
23−import qualified Data.HashMap.Strict as HM
24
19
25checkToParamSchema :: ToParamSchema a => Proxy a -> Value -> Spec
20checkToParamSchema :: ToParamSchema a => Proxy a -> Value -> Spec
26−checkToParamSchema proxy js = (toParamSchema proxy :: ParamSchema ('SwaggerKindNormal Param)) <=> js
21+checkToParamSchema proxy js = (toParamSchema proxy :: ParamSchema Param) <=> js
27
22
28spec :: Spec
23spec :: Spec
29spec = do
24spec = do
30 describe "Generic ToParamSchema" $ do
25 describe "Generic ToParamSchema" $ do
31− context "Unit" $ checkToParamSchema (Proxy :: Proxy Unit) unitSchemaJSON
32 context "Color (bounded enum)" $ checkToParamSchema (Proxy :: Proxy Color) colorSchemaJSON
26 context "Color (bounded enum)" $ checkToParamSchema (Proxy :: Proxy Color) colorSchemaJSON
33 context "Status (constructorTagModifier)" $ checkToParamSchema (Proxy :: Proxy Status) statusSchemaJSON
27 context "Status (constructorTagModifier)" $ checkToParamSchema (Proxy :: Proxy Status) statusSchemaJSON
34 context "Unary records" $ do
28 context "Unary records" $ do
35 context "Email (unary record)" $ checkToParamSchema (Proxy :: Proxy Email) emailSchemaJSON
29 context "Email (unary record)" $ checkToParamSchema (Proxy :: Proxy Email) emailSchemaJSON
36 context "UserId (non-record newtype)" $ checkToParamSchema (Proxy :: Proxy UserId) userIdSchemaJSON
30 context "UserId (non-record newtype)" $ checkToParamSchema (Proxy :: Proxy UserId) userIdSchemaJSON
37− context "TimeOfDay" $ checkToParamSchema (Proxy :: Proxy Data.Time.LocalTime.TimeOfDay) timeOfDayParamSchemaJSON
38
31
39main :: IO ()
32main :: IO ()
40main = hspec spec
33main = hspec spec
34+
35+-- ========================================================================
36+-- Color (enum)
37+-- ========================================================================
38+data Color
39+ = Red
40+ | Green
41+ | Blue
42+ deriving (Generic, ToParamSchema)
43+
44+colorSchemaJSON :: Value
45+colorSchemaJSON = [aesonQQ|
46+{
47+ "type": "string",
48+ "enum": ["Red", "Green", "Blue"]
49+}
50+|]
51+
52+-- ========================================================================
53+-- Status (constructorTagModifier)
54+-- ========================================================================
55+
56+data Status = StatusOk | StatusError deriving (Generic)
57+
58+instance ToParamSchema Status where
59+ toParamSchema = genericToParamSchema defaultSchemaOptions
60+ { constructorTagModifier = map toLower . drop (length "Status") }
61+
62+statusSchemaJSON :: Value
63+statusSchemaJSON = [aesonQQ|
64+{
65+ "type": "string",
66+ "enum": ["ok", "error"]
67+}
68+|]
69+
70+-- ========================================================================
71+-- Email (newtype with unwrapUnaryRecords set to True)
72+-- ========================================================================
73+
74+newtype Email = Email { getEmail :: String }
75+ deriving (Generic, ToParamSchema)
76+
77+emailSchemaJSON :: Value
78+emailSchemaJSON = [aesonQQ|
79+{
80+ "type": "string"
81+}
82+|]
83+
84+-- ========================================================================
85+-- UserId (non-record newtype)
86+-- ========================================================================
87+
88+newtype UserId = UserId Integer
89+ deriving (Generic, ToParamSchema)
90+
91+userIdSchemaJSON :: Value
92+userIdSchemaJSON = [aesonQQ|
93+{
94+ "type": "integer"
95+}
96+|]
97+
test/Data/Swagger/Schema/GeneratorSpec.hsdeleted−168
@@ -1,168 +0,0 @@
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.hsdeleted−278
@@ -1,278 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE DeriveGeneric #-}
3−{-# LANGUAGE PackageImports #-}
4−{-# LANGUAGE RecordWildCards #-}
5−{-# LANGUAGE ScopedTypeVariables #-}
6−{-# OPTIONS_GHC -fno-warn-orphans #-}
7−module Data.Swagger.Schema.ValidationSpec where
8−
9−import Control.Applicative
10−import Control.Lens ((&), (.~), (?~))
11−import Data.Aeson
12−import Data.Aeson.Types
13−import Data.Hashable (Hashable)
14−import Data.HashMap.Strict (HashMap)
15−import qualified Data.HashMap.Strict as HashMap
16−import "unordered-containers" Data.HashSet (HashSet)
17−import qualified "unordered-containers" Data.HashSet as HashSet
18−import Data.Int
19−import Data.IntMap (IntMap)
20−import Data.List.NonEmpty.Compat (NonEmpty (..), nonEmpty)
21−import Data.Map (Map, fromList)
22−import Data.Monoid (mempty)
23−import Data.Proxy
24−import Data.Set (Set)
25−import qualified Data.Text as T
26−import qualified Data.Text.Lazy as TL
27−import Data.Time
28−import Data.Version (Version)
29−import Data.Word
30−import GHC.Generics
31−
32−import Data.Swagger
33−import Data.Swagger.Declare
34−
35−import Test.Hspec
36−import Test.Hspec.QuickCheck
37−import Test.QuickCheck
38−import Test.QuickCheck.Instances ()
39−
40−shouldValidate :: (ToJSON a, ToSchema a) => Proxy a -> a -> Bool
41−shouldValidate _ x = validateToJSON x == []
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−
48−spec :: Spec
49−spec = do
50− describe "Validation" $ do
51− prop "Bool" $ shouldValidate (Proxy :: Proxy Bool)
52− prop "Char" $ shouldValidate (Proxy :: Proxy Char)
53− prop "Double" $ shouldValidate (Proxy :: Proxy Double)
54− prop "Float" $ shouldValidate (Proxy :: Proxy Float)
55− prop "Int" $ shouldValidate (Proxy :: Proxy Int)
56− prop "Int8" $ shouldValidate (Proxy :: Proxy Int8)
57− prop "Int16" $ shouldValidate (Proxy :: Proxy Int16)
58− prop "Int32" $ shouldValidate (Proxy :: Proxy Int32)
59− prop "Int64" $ shouldValidate (Proxy :: Proxy Int64)
60− prop "Integer" $ shouldValidate (Proxy :: Proxy Integer)
61− prop "Word" $ shouldValidate (Proxy :: Proxy Word)
62− prop "Word8" $ shouldValidate (Proxy :: Proxy Word8)
63− prop "Word16" $ shouldValidate (Proxy :: Proxy Word16)
64− prop "Word32" $ shouldValidate (Proxy :: Proxy Word32)
65− prop "Word64" $ shouldValidate (Proxy :: Proxy Word64)
66− prop "String" $ shouldValidate (Proxy :: Proxy String)
67− prop "()" $ shouldValidate (Proxy :: Proxy ())
68− prop "ZonedTime" $ shouldValidate (Proxy :: Proxy ZonedTime)
69− prop "UTCTime" $ shouldValidate (Proxy :: Proxy UTCTime)
70− prop "T.Text" $ shouldValidate (Proxy :: Proxy T.Text)
71− prop "TL.Text" $ shouldValidate (Proxy :: Proxy TL.Text)
72− prop "[String]" $ shouldValidate (Proxy :: Proxy [String])
73− -- prop "(Maybe [Int])" $ shouldValidate (Proxy :: Proxy (Maybe [Int]))
74− prop "(IntMap String)" $ shouldValidate (Proxy :: Proxy (IntMap String))
75− prop "(Set Bool)" $ shouldValidate (Proxy :: Proxy (Set Bool))
76− prop "(NonEmpty Bool)" $ shouldValidate (Proxy :: Proxy (NonEmpty Bool))
77− prop "(HashSet Bool)" $ shouldValidate (Proxy :: Proxy (HashSet Bool))
78− prop "(Either Int String)" $ shouldValidate (Proxy :: Proxy (Either Int String))
79− prop "(Int, String)" $ shouldValidate (Proxy :: Proxy (Int, String))
80− prop "(Map String Int)" $ shouldValidate (Proxy :: Proxy (Map String Int))
81− prop "(Map T.Text Int)" $ shouldValidate (Proxy :: Proxy (Map T.Text Int))
82− prop "(Map TL.Text Bool)" $ shouldValidate (Proxy :: Proxy (Map TL.Text Bool))
83− prop "(HashMap String Int)" $ shouldValidate (Proxy :: Proxy (HashMap String Int))
84− prop "(HashMap T.Text Int)" $ shouldValidate (Proxy :: Proxy (HashMap T.Text Int))
85− prop "(HashMap TL.Text Bool)" $ shouldValidate (Proxy :: Proxy (HashMap TL.Text Bool))
86− prop "Object" $ shouldValidate (Proxy :: Proxy Object)
87− prop "(Int, String, Double)" $ shouldValidate (Proxy :: Proxy (Int, String, Double))
88− prop "(Int, String, Double, [Int])" $ shouldValidate (Proxy :: Proxy (Int, String, Double, [Int]))
89− prop "(Int, String, Double, [Int], Int)" $ shouldValidate (Proxy :: Proxy (Int, String, Double, [Int], Int))
90− prop "Person" $ shouldValidate (Proxy :: Proxy Person)
91− prop "Color" $ shouldValidate (Proxy :: Proxy Color)
92− prop "Paint" $ shouldValidate (Proxy :: Proxy Paint)
93− prop "MyRoseTree" $ shouldValidate (Proxy :: Proxy MyRoseTree)
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
105−
106−main :: IO ()
107−main = hspec spec
108−
109−-- ========================================================================
110−-- Person (simple record with optional fields)
111−-- ========================================================================
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
120−
121−instance Arbitrary Person where
122− arbitrary = Person <$> arbitrary <*> arbitrary <*> arbitrary
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−
131−-- ========================================================================
132−-- Color (enum)
133−-- ========================================================================
134−data Color = Red | Green | Blue deriving (Show, Generic, Bounded, Enum)
135−
136−instance ToJSON Color
137−instance ToSchema Color
138−
139−instance Arbitrary Color where
140− arbitrary = arbitraryBoundedEnum
141−
142−invalidColorToJSON :: Color -> Value
143−invalidColorToJSON Red = toJSON "red"
144−invalidColorToJSON Green = toJSON "green"
145−invalidColorToJSON Blue = toJSON "blue"
146−
147−-- ========================================================================
148−-- Paint (record with bounded enum property)
149−-- ========================================================================
150−
151−newtype Paint = Paint { color :: Color }
152− deriving (Show, Generic)
153−
154−instance ToJSON Paint
155−instance ToSchema Paint
156−
157−instance Arbitrary Paint where
158− arbitrary = Paint <$> arbitrary
159−
160−invalidPaintToJSON :: Paint -> Value
161−invalidPaintToJSON = toJSON . color
162−
163−-- ========================================================================
164−-- MyRoseTree (custom datatypeNameModifier)
165−-- ========================================================================
166−
167−data MyRoseTree = MyRoseTree
168− { root :: String
169− , trees :: [MyRoseTree]
170− } deriving (Show, Generic)
171−
172−instance ToJSON MyRoseTree
173−
174−instance ToSchema MyRoseTree where
175− declareNamedSchema = genericDeclareNamedSchema defaultSchemaOptions
176− { datatypeNameModifier = drop (length "My") }
177−
178−instance Arbitrary MyRoseTree where
179− arbitrary = fmap (cut limit) $ MyRoseTree <$> arbitrary <*> (take limit <$> arbitrary)
180− where
181− limit = 4
182− cut 0 (MyRoseTree x _ ) = MyRoseTree x []
183− cut n (MyRoseTree x xs) = MyRoseTree x (map (cut (n - 1)) xs)
184−
185−-- ========================================================================
186−-- Light (sum type)
187−-- ========================================================================
188−
189−data Light = NoLight | LightFreq Double | LightColor Color deriving (Show, Generic)
190−
191−instance ToSchema Light where
192− declareNamedSchema = genericDeclareNamedSchemaUnrestricted defaultSchemaOptions
193−
194−instance ToJSON Light where
195− toJSON = genericToJSON defaultOptions { sumEncoding = ObjectWithSingleField }
196−
197−instance Arbitrary Light where
198− arbitrary = oneof
199− [ return NoLight
200− , LightFreq <$> arbitrary
201− , LightColor <$> arbitrary
202− ]
203−
204−invalidLightToJSON :: Light -> Value
205−invalidLightToJSON = genericToJSON defaultOptions
206−
207−-- ========================================================================
208−-- ButtonImages (bounded enum key mapping)
209−-- ========================================================================
210−
211−data ButtonState = Neutral | Focus | Active | Hover | Disabled
212− deriving (Show, Eq, Ord, Bounded, Enum, Generic)
213−
214−instance ToJSON ButtonState
215−instance ToSchema ButtonState
216−instance ToJSONKey ButtonState where toJSONKey = toJSONKeyText (T.pack . show)
217−
218−instance Arbitrary ButtonState where
219− arbitrary = arbitraryBoundedEnum
220−
221−type ImageUrl = T.Text
222−
223−newtype ButtonImages = ButtonImages { getButtonImages :: Map ButtonState ImageUrl }
224− deriving (Show, Generic)
225−
226−instance ToJSON ButtonImages where
227− toJSON = toJSON . getButtonImages
228−
229−instance ToSchema ButtonImages where
230− declareNamedSchema = genericDeclareNamedSchemaNewtype defaultSchemaOptions
231− declareSchemaBoundedEnumKeyMapping
232−
233−invalidButtonImagesToJSON :: ButtonImages -> Value
234−invalidButtonImagesToJSON = genericToJSON defaultOptions
235−
236−instance Arbitrary ButtonImages where
237− arbitrary = ButtonImages <$> arbitrary
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)
261−
262−instance Eq ZonedTime where
263− ZonedTime t (TimeZone x _ _) == ZonedTime t' (TimeZone y _ _) = t == t' && x == y
264−
265−-- ========================================================================
266−-- Arbitrary instance for Data.Aeson.Value
267−-- ========================================================================
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+494−33
@@ -1,29 +1,27 @@
1{-# LANGUAGE DeriveGeneric #-}
1{-# LANGUAGE DeriveGeneric #-}
2+{-# LANGUAGE DeriveAnyClass #-}
2{-# LANGUAGE ScopedTypeVariables #-}
3{-# LANGUAGE ScopedTypeVariables #-}
3{-# LANGUAGE TemplateHaskell #-}
4{-# LANGUAGE TemplateHaskell #-}
4{-# LANGUAGE QuasiQuotes #-}
5{-# LANGUAGE QuasiQuotes #-}
5module Data.Swagger.SchemaSpec where
6module Data.Swagger.SchemaSpec where
6
7
7−import Prelude ()
8+import Data.Aeson
8−import Prelude.Compat
9+import Data.Aeson.QQ
9−
10−import Control.Lens ((^.))
11−import Data.Aeson (Value)
10+import Data.Char
12−import qualified Data.HashMap.Strict.InsOrd as InsOrdHashMap
11+import qualified Data.HashMap.Strict as HashMap
13import Data.Proxy
12import Data.Proxy
14import Data.Set (Set)
13import Data.Set (Set)
14+import qualified Data.Set as Set
15+import Data.Text (Text)
15import qualified Data.Text as Text
16import qualified Data.Text as Text
17+import GHC.Generics
16
18
17import Data.Swagger
19import Data.Swagger
18import Data.Swagger.Declare
20import Data.Swagger.Declare
19
21
20−import Data.Swagger.CommonTestTypes
21import SpecCommon
22import SpecCommon
22import Test.Hspec
23import Test.Hspec
23
24
24−import qualified Data.HashMap.Strict as HM
25−import Data.Time.LocalTime
26−
27checkToSchema :: ToSchema a => Proxy a -> Value -> Spec
25checkToSchema :: ToSchema a => Proxy a -> Value -> Spec
28checkToSchema proxy js = toSchema proxy <=> js
26checkToSchema proxy js = toSchema proxy <=> js
29
27
@@ -35,29 +33,22 @@ checkSchemaName sname proxy =
35checkDefs :: ToSchema a => Proxy a -> [String] -> Spec
33checkDefs :: ToSchema a => Proxy a -> [String] -> Spec
36checkDefs proxy names =
34checkDefs proxy names =
37 it ("uses these definitions " ++ show names) $
35 it ("uses these definitions " ++ show names) $
38− InsOrdHashMap.keys defs `shouldBe` map Text.pack names
36+ Set.fromList (HashMap.keys defs) `shouldBe` Set.fromList (map Text.pack names)
39 where
37 where
40 defs = execDeclare (declareNamedSchema proxy) mempty
38 defs = execDeclare (declareNamedSchema proxy) mempty
41
39
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−
49checkInlinedSchema :: ToSchema a => Proxy a -> Value -> Spec
40checkInlinedSchema :: ToSchema a => Proxy a -> Value -> Spec
50checkInlinedSchema proxy js = toInlinedSchema proxy <=> js
41checkInlinedSchema proxy js = toInlinedSchema proxy <=> js
51
42
52checkInlinedSchemas :: ToSchema a => [String] -> Proxy a -> Value -> Spec
43checkInlinedSchemas :: ToSchema a => [String] -> Proxy a -> Value -> Spec
53−checkInlinedSchemas names proxy js = inlineSchemas (map Text.pack names) defs s <=> js
44+checkInlinedSchemas names proxy js = inlineSchemas (map Text.pack names) defs schema <=> js
54 where
45 where
55− (defs, s) = runDeclare (declareSchema proxy) mempty
46+ (defs, schema) = runDeclare (declareSchema proxy) mempty
56
47
57checkInlinedRecSchema :: ToSchema a => Proxy a -> Value -> Spec
48checkInlinedRecSchema :: ToSchema a => Proxy a -> Value -> Spec
58−checkInlinedRecSchema proxy js = inlineNonRecursiveSchemas defs s <=> js
49+checkInlinedRecSchema proxy js = inlineNonRecursiveSchemas defs schema <=> js
59 where
50 where
60− (defs, s) = runDeclare (declareSchema proxy) mempty
51+ (defs, schema) = runDeclare (declareSchema proxy) mempty
61
52
62spec :: Spec
53spec :: Spec
63spec = do
54spec = do
@@ -66,9 +57,6 @@ spec = do
66 context "Person" $ checkToSchema (Proxy :: Proxy Person) personSchemaJSON
57 context "Person" $ checkToSchema (Proxy :: Proxy Person) personSchemaJSON
67 context "ISPair" $ checkToSchema (Proxy :: Proxy ISPair) ispairSchemaJSON
58 context "ISPair" $ checkToSchema (Proxy :: Proxy ISPair) ispairSchemaJSON
68 context "Point (fieldLabelModifier)" $ checkToSchema (Proxy :: Proxy Point) pointSchemaJSON
59 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
72 context "Color (bounded enum)" $ checkToSchema (Proxy :: Proxy Color) colorSchemaJSON
60 context "Color (bounded enum)" $ checkToSchema (Proxy :: Proxy Color) colorSchemaJSON
73 context "Shade (paramSchemaToNamedSchema)" $ checkToSchema (Proxy :: Proxy Shade) shadeSchemaJSON
61 context "Shade (paramSchemaToNamedSchema)" $ checkToSchema (Proxy :: Proxy Shade) shadeSchemaJSON
74 context "Paint (record with bounded enum field)" $ checkToSchema (Proxy :: Proxy Paint) paintSchemaJSON
62 context "Paint (record with bounded enum field)" $ checkToSchema (Proxy :: Proxy Paint) paintSchemaJSON
@@ -77,10 +65,8 @@ spec = do
77 context "Email (unwrapUnaryRecords)" $ checkToSchema (Proxy :: Proxy Email) emailSchemaJSON
65 context "Email (unwrapUnaryRecords)" $ checkToSchema (Proxy :: Proxy Email) emailSchemaJSON
78 context "UserId (non-record newtype)" $ checkToSchema (Proxy :: Proxy UserId) userIdSchemaJSON
66 context "UserId (non-record newtype)" $ checkToSchema (Proxy :: Proxy UserId) userIdSchemaJSON
79 context "Player (unary record)" $ checkToSchema (Proxy :: Proxy Player) playerSchemaJSON
67 context "Player (unary record)" $ checkToSchema (Proxy :: Proxy Player) playerSchemaJSON
80− context "SingleMaybeField (unary record with Maybe)" $ checkToSchema (Proxy :: Proxy SingleMaybeField) singleMaybeFieldSchemaJSON
81 context "Players (inlining schema)" $ checkToSchema (Proxy :: Proxy Players) playersSchemaJSON
68 context "Players (inlining schema)" $ checkToSchema (Proxy :: Proxy Players) playersSchemaJSON
82 context "MyRoseTree (datatypeNameModifier)" $ checkToSchema (Proxy :: Proxy MyRoseTree) myRoseTreeSchemaJSON
69 context "MyRoseTree (datatypeNameModifier)" $ checkToSchema (Proxy :: Proxy MyRoseTree) myRoseTreeSchemaJSON
83− context "MyRoseTree' (datatypeNameModifier)" $ checkToSchema (Proxy :: Proxy MyRoseTree') myRoseTreeSchemaJSON'
84 context "Sum types" $ do
70 context "Sum types" $ do
85 context "Status (sum of unary constructors)" $ checkToSchema (Proxy :: Proxy Status) statusSchemaJSON
71 context "Status (sum of unary constructors)" $ checkToSchema (Proxy :: Proxy Status) statusSchemaJSON
86 context "Character (ref and record sum)" $ checkToSchema (Proxy :: Proxy Character) characterSchemaJSON
72 context "Character (ref and record sum)" $ checkToSchema (Proxy :: Proxy Character) characterSchemaJSON
@@ -96,19 +82,494 @@ spec = do
96 context "Light" $ checkDefs (Proxy :: Proxy Light) ["Color"]
82 context "Light" $ checkDefs (Proxy :: Proxy Light) ["Color"]
97 context "Character" $ checkDefs (Proxy :: Proxy Character) ["Player", "Point"]
83 context "Character" $ checkDefs (Proxy :: Proxy Character) ["Player", "Point"]
98 context "MyRoseTree" $ checkDefs (Proxy :: Proxy MyRoseTree) ["RoseTree"]
84 context "MyRoseTree" $ checkDefs (Proxy :: Proxy MyRoseTree) ["RoseTree"]
99− context "MyRoseTree'" $ checkDefs (Proxy :: Proxy MyRoseTree') ["myrosetree'"]
100 context "[Set (Unit, Maybe Color)]" $ checkDefs (Proxy :: Proxy [Set (Unit, Maybe Color)]) ["Unit", "Color"]
85 context "[Set (Unit, Maybe Color)]" $ checkDefs (Proxy :: Proxy [Set (Unit, Maybe Color)]) ["Unit", "Color"]
101− context "ResourceId" $ checkDefs (Proxy :: Proxy ResourceId) []
102 describe "Inlining Schemas" $ do
86 describe "Inlining Schemas" $ do
103 context "Paint" $ checkInlinedSchema (Proxy :: Proxy Paint) paintInlinedSchemaJSON
87 context "Paint" $ checkInlinedSchema (Proxy :: Proxy Paint) paintInlinedSchemaJSON
104 context "Character" $ checkInlinedSchema (Proxy :: Proxy Character) characterInlinedSchemaJSON
88 context "Character" $ checkInlinedSchema (Proxy :: Proxy Character) characterInlinedSchemaJSON
105 context "Character (inlining only Player)" $ checkInlinedSchemas ["Player"] (Proxy :: Proxy Character) characterInlinedPlayerSchemaJSON
89 context "Character (inlining only Player)" $ checkInlinedSchemas ["Player"] (Proxy :: Proxy Character) characterInlinedPlayerSchemaJSON
106 context "Light" $ checkInlinedSchema (Proxy :: Proxy Light) lightInlinedSchemaJSON
90 context "Light" $ checkInlinedSchema (Proxy :: Proxy Light) lightInlinedSchemaJSON
107 context "MyRoseTree (inlineNonRecursiveSchemas)" $ checkInlinedRecSchema (Proxy :: Proxy MyRoseTree) myRoseTreeSchemaJSON
91 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
112
92
113main :: IO ()
93main :: IO ()
114main = hspec spec
94main = hspec spec
95+
96+-- ========================================================================
97+-- Person (simple record with optional fields)
98+-- ========================================================================
99+data Person = Person
100+ { name :: String
101+ , phone :: Integer
102+ , email :: Maybe String
103+ } deriving (Generic, ToSchema)
104+
105+personSchemaJSON :: Value
106+personSchemaJSON = [aesonQQ|
107+{
108+ "type": "object",
109+ "properties":
110+ {
111+ "name": { "type": "string" },
112+ "phone": { "type": "integer" },
113+ "email": { "type": "string" }
114+ },
115+ "required": ["name", "phone"]
116+}
117+|]
118+
119+-- ========================================================================
120+-- ISPair (non-record product data type)
121+-- ========================================================================
122+data ISPair = ISPair Integer String
123+ deriving (Generic, ToSchema)
124+
125+ispairSchemaJSON :: Value
126+ispairSchemaJSON = [aesonQQ|
127+{
128+ "type": "array",
129+ "items":
130+ [
131+ { "type": "integer" },
132+ { "type": "string" }
133+ ]
134+}
135+|]
136+
137+-- ========================================================================
138+-- Point (record data type with custom fieldLabelModifier)
139+-- ========================================================================
140+data Point = Point
141+ { pointX :: Double
142+ , pointY :: Double
143+ } deriving (Generic)
144+
145+instance ToSchema Point where
146+ declareNamedSchema = genericDeclareNamedSchema defaultSchemaOptions
147+ { fieldLabelModifier = map toLower . drop (length "point") }
148+
149+pointSchemaJSON :: Value
150+pointSchemaJSON = [aesonQQ|
151+{
152+ "type": "object",
153+ "properties":
154+ {
155+ "x": { "type": "number" },
156+ "y": { "type": "number" }
157+ },
158+ "required": ["x", "y"]
159+}
160+|]
161+
162+
163+-- ========================================================================
164+-- Color (enum)
165+-- ========================================================================
166+data Color
167+ = Red
168+ | Green
169+ | Blue
170+ deriving (Generic, ToSchema)
171+
172+colorSchemaJSON :: Value
173+colorSchemaJSON = [aesonQQ|
174+{
175+ "type": "string",
176+ "enum": ["Red", "Green", "Blue"]
177+}
178+|]
179+
180+-- ========================================================================
181+-- Shade (paramSchemaToNamedSchema)
182+-- ========================================================================
183+
184+data Shade = Dim | Bright deriving (Generic, ToParamSchema)
185+
186+instance ToSchema Shade where declareNamedSchema = pure . paramSchemaToNamedSchema defaultSchemaOptions
187+
188+shadeSchemaJSON :: Value
189+shadeSchemaJSON = [aesonQQ|
190+{
191+ "type": "string",
192+ "enum": ["Dim", "Bright"]
193+}
194+|]
195+
196+-- ========================================================================
197+-- Paint (record with bounded enum property)
198+-- ========================================================================
199+
200+newtype Paint = Paint { color :: Color }
201+ deriving (Generic, ToSchema)
202+
203+paintSchemaJSON :: Value
204+paintSchemaJSON = [aesonQQ|
205+{
206+ "type": "object",
207+ "properties":
208+ {
209+ "color":
210+ {
211+ "$ref": "#/definitions/Color"
212+ }
213+ },
214+ "required": ["color"]
215+}
216+|]
217+
218+paintInlinedSchemaJSON :: Value
219+paintInlinedSchemaJSON = [aesonQQ|
220+{
221+ "type": "object",
222+ "properties":
223+ {
224+ "color":
225+ {
226+ "type": "string",
227+ "enum": ["Red", "Green", "Blue"]
228+ }
229+ },
230+ "required": ["color"]
231+}
232+|]
233+
234+-- ========================================================================
235+-- Email (newtype with unwrapUnaryRecords set to True)
236+-- ========================================================================
237+
238+newtype Email = Email { getEmail :: String }
239+ deriving (Generic)
240+
241+instance ToSchema Email where
242+ declareNamedSchema = genericDeclareNamedSchema defaultSchemaOptions
243+ { unwrapUnaryRecords = True }
244+
245+emailSchemaJSON :: Value
246+emailSchemaJSON = [aesonQQ|
247+{
248+ "type": "string"
249+}
250+|]
251+
252+-- ========================================================================
253+-- UserId (non-record newtype)
254+-- ========================================================================
255+
256+newtype UserId = UserId Integer
257+ deriving (Eq, Ord, Generic, ToSchema)
258+
259+userIdSchemaJSON :: Value
260+userIdSchemaJSON = [aesonQQ|
261+{
262+ "type": "integer"
263+}
264+|]
265+
266+-- ========================================================================
267+-- UserGroup (set newtype)
268+-- ========================================================================
269+
270+newtype UserGroup = UserGroup (Set UserId)
271+ deriving (Generic, ToSchema)
272+
273+userGroupSchemaJSON :: Value
274+userGroupSchemaJSON = [aesonQQ|
275+{
276+ "type": "array",
277+ "items": { "$ref": "#/definitions/UserId" },
278+ "uniqueItems": true
279+}
280+|]
281+
282+-- ========================================================================
283+-- Player (record newtype)
284+-- ========================================================================
285+
286+newtype Player = Player
287+ { position :: Point
288+ } deriving (Generic, ToSchema)
289+
290+playerSchemaJSON :: Value
291+playerSchemaJSON = [aesonQQ|
292+{
293+ "type": "object",
294+ "properties":
295+ {
296+ "position":
297+ {
298+ "$ref": "#/definitions/Point"
299+ }
300+ },
301+ "required": ["position"]
302+}
303+|]
304+
305+-- ========================================================================
306+-- MyRoseTree (custom datatypeNameModifier)
307+-- ========================================================================
308+
309+data MyRoseTree = MyRoseTree
310+ { root :: String
311+ , trees :: [MyRoseTree]
312+ } deriving (Generic)
313+
314+instance ToSchema MyRoseTree where
315+ declareNamedSchema = genericDeclareNamedSchema defaultSchemaOptions
316+ { datatypeNameModifier = drop (length "My") }
317+
318+myRoseTreeSchemaJSON :: Value
319+myRoseTreeSchemaJSON = [aesonQQ|
320+{
321+ "type": "object",
322+ "properties":
323+ {
324+ "root": { "type": "string" },
325+ "trees":
326+ {
327+ "type": "array",
328+ "items":
329+ {
330+ "$ref": "#/definitions/RoseTree"
331+ }
332+ }
333+ },
334+ "required": ["root", "trees"]
335+}
336+|]
337+
338+-- ========================================================================
339+-- Inlined (newtype for inlining schemas)
340+-- ========================================================================
341+
342+newtype Inlined a = Inlined { getInlined :: a }
343+
344+instance ToSchema a => ToSchema (Inlined a) where
345+ declareNamedSchema _ = unname <$> declareNamedSchema (Proxy :: Proxy a)
346+ where
347+ unname (_, schema) = (Nothing, schema)
348+
349+newtype Players = Players [Inlined Player]
350+ deriving (Generic, ToSchema)
351+
352+playersSchemaJSON :: Value
353+playersSchemaJSON = [aesonQQ|
354+{
355+ "type": "array",
356+ "items":
357+ {
358+ "type": "object",
359+ "properties":
360+ {
361+ "position":
362+ {
363+ "$ref": "#/definitions/Point"
364+ }
365+ },
366+ "required": ["position"]
367+ }
368+}
369+|]
370+
371+-- ========================================================================
372+-- Status (sum type with unary constructors)
373+-- ========================================================================
374+
375+data Status
376+ = StatusOk String
377+ | StatusError String
378+ deriving (Generic)
379+
380+instance ToSchema Status where
381+ declareNamedSchema = genericDeclareNamedSchema defaultSchemaOptions
382+ { constructorTagModifier = map toLower . drop (length "Status") }
383+
384+statusSchemaJSON :: Value
385+statusSchemaJSON = [aesonQQ|
386+{
387+ "type": "object",
388+ "properties":
389+ {
390+ "ok": { "type": "string" },
391+ "error": { "type": "string" }
392+ },
393+ "maxProperties": 1,
394+ "minProperties": 1
395+}
396+|]
397+
398+-- ========================================================================
399+-- Unit type
400+-- ========================================================================
401+
402+data Unit = Unit deriving (Generic, ToSchema)
403+
404+unitSchemaJSON :: Value
405+unitSchemaJSON = [aesonQQ|
406+{
407+ "type": "array",
408+ "enum": [[]]
409+}
410+|]
411+
412+
413+-- ========================================================================
414+-- Character (sum type with ref and record in alternative)
415+-- ========================================================================
416+
417+data Character
418+ = PC Player
419+ | NPC { npcName :: String, npcPosition :: Point }
420+ deriving (Generic, ToSchema)
421+
422+characterSchemaJSON :: Value
423+characterSchemaJSON = [aesonQQ|
424+{
425+ "type": "object",
426+ "properties":
427+ {
428+ "PC": { "$ref": "#/definitions/Player" },
429+ "NPC":
430+ {
431+ "type": "object",
432+ "properties":
433+ {
434+ "npcName": { "type": "string" },
435+ "npcPosition": { "$ref": "#/definitions/Point" }
436+ },
437+ "required": ["npcName", "npcPosition"]
438+ }
439+ },
440+ "maxProperties": 1,
441+ "minProperties": 1
442+}
443+|]
444+
445+characterInlinedSchemaJSON :: Value
446+characterInlinedSchemaJSON = [aesonQQ|
447+{
448+ "type": "object",
449+ "properties":
450+ {
451+ "PC":
452+ {
453+ "type": "object",
454+ "properties":
455+ {
456+ "position":
457+ {
458+ "type": "object",
459+ "properties":
460+ {
461+ "x": { "type": "number" },
462+ "y": { "type": "number" }
463+ },
464+ "required": ["x", "y"]
465+ }
466+ },
467+ "required": ["position"]
468+ },
469+ "NPC":
470+ {
471+ "type": "object",
472+ "properties":
473+ {
474+ "npcName": { "type": "string" },
475+ "npcPosition":
476+ {
477+ "type": "object",
478+ "properties":
479+ {
480+ "x": { "type": "number" },
481+ "y": { "type": "number" }
482+ },
483+ "required": ["x", "y"]
484+ }
485+ },
486+ "required": ["npcName", "npcPosition"]
487+ }
488+ },
489+ "maxProperties": 1,
490+ "minProperties": 1
491+}
492+|]
493+
494+characterInlinedPlayerSchemaJSON :: Value
495+characterInlinedPlayerSchemaJSON = [aesonQQ|
496+{
497+ "type": "object",
498+ "properties":
499+ {
500+ "PC":
501+ {
502+ "type": "object",
503+ "properties":
504+ {
505+ "position":
506+ {
507+ "$ref": "#/definitions/Point"
508+ }
509+ },
510+ "required": ["position"]
511+ },
512+ "NPC":
513+ {
514+ "type": "object",
515+ "properties":
516+ {
517+ "npcName": { "type": "string" },
518+ "npcPosition": { "$ref": "#/definitions/Point" }
519+ },
520+ "required": ["npcName", "npcPosition"]
521+ }
522+ },
523+ "maxProperties": 1,
524+ "minProperties": 1
525+}
526+|]
527+
528+-- ========================================================================
529+-- Light (sum type with unwrapUnaryRecords)
530+-- ========================================================================
531+
532+data Light
533+ = LightFreq Double
534+ | LightColor Color
535+ | LightWaveLength { waveLength :: Double }
536+ deriving (Generic)
537+
538+instance ToSchema Light where
539+ declareNamedSchema = genericDeclareNamedSchema defaultSchemaOptions
540+ { unwrapUnaryRecords = True }
541+
542+lightSchemaJSON :: Value
543+lightSchemaJSON = [aesonQQ|
544+{
545+ "type": "object",
546+ "properties":
547+ {
548+ "LightFreq": { "type": "number" },
549+ "LightColor": { "$ref": "#/definitions/Color" },
550+ "LightWaveLength": { "type": "number" }
551+ },
552+ "maxProperties": 1,
553+ "minProperties": 1
554+}
555+|]
556+
557+lightInlinedSchemaJSON :: Value
558+lightInlinedSchemaJSON = [aesonQQ|
559+{
560+ "type": "object",
561+ "properties":
562+ {
563+ "LightFreq": { "type": "number" },
564+ "LightColor":
565+ {
566+ "type": "string",
567+ "enum": ["Red", "Green", "Blue"]
568+ },
569+ "LightWaveLength": { "type": "number" }
570+ },
571+ "maxProperties": 1,
572+ "minProperties": 1
573+}
574+|]
575+
test/Data/SwaggerSpec.hs+448−530
@@ -4,31 +4,19 @@
4{-# LANGUAGE QuasiQuotes #-}
4{-# LANGUAGE QuasiQuotes #-}
5module Data.SwaggerSpec where
5module Data.SwaggerSpec where
6
6
7−import Prelude ()
8−import Prelude.Compat
9−
10import Control.Lens
7import Control.Lens
11
8
12import Data.Aeson
9import Data.Aeson
13−import Data.Aeson.QQ.Simple
10+import Data.Aeson.QQ
14import Data.HashMap.Strict (HashMap)
11import Data.HashMap.Strict (HashMap)
15−import qualified Data.HashSet.InsOrd as InsOrdHS
16import Data.Text (Text)
12import Data.Text (Text)
17
13
18import Data.Swagger
14import Data.Swagger
19import SpecCommon
15import SpecCommon
20−import Test.Hspec hiding (example)
16+import Test.Hspec
21
17
22spec :: Spec
18spec :: Spec
23spec = do
19spec = 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
32 describe "License Object" $ licenseExample <=> licenseExampleJSON
20 describe "License Object" $ licenseExample <=> licenseExampleJSON
33 describe "Contact Object" $ contactExample <=> contactExampleJSON
21 describe "Contact Object" $ contactExample <=> contactExampleJSON
34 describe "Info Object" $ infoExample <=> infoExampleJSON
22 describe "Info Object" $ infoExample <=> infoExampleJSON
@@ -37,14 +25,11 @@ spec = do
37 context "Primitive Sample" $ schemaPrimitiveExample <=> schemaPrimitiveExampleJSON
25 context "Primitive Sample" $ schemaPrimitiveExample <=> schemaPrimitiveExampleJSON
38 context "Simple Model" $ schemaSimpleModelExample <=> schemaSimpleModelExampleJSON
26 context "Simple Model" $ schemaSimpleModelExample <=> schemaSimpleModelExampleJSON
39 context "Model with Map/Dictionary Properties" $ schemaModelDictExample <=> schemaModelDictExampleJSON
27 context "Model with Map/Dictionary Properties" $ schemaModelDictExample <=> schemaModelDictExampleJSON
40− context "Model with Arbitrary Properties" $ schemaAdditionalExample <=> schemaAdditionalExampleJSON
41 context "Model with Example" $ schemaWithExampleExample <=> schemaWithExampleExampleJSON
28 context "Model with Example" $ schemaWithExampleExample <=> schemaWithExampleExampleJSON
42 describe "Definitions Object" $ definitionsExample <=> definitionsExampleJSON
29 describe "Definitions Object" $ definitionsExample <=> definitionsExampleJSON
43 describe "Parameters Definition Object" $ paramsDefinitionExample <=> paramsDefinitionExampleJSON
30 describe "Parameters Definition Object" $ paramsDefinitionExample <=> paramsDefinitionExampleJSON
44 describe "Responses Definition Object" $ responsesDefinitionExample <=> responsesDefinitionExampleJSON
31 describe "Responses Definition Object" $ responsesDefinitionExample <=> responsesDefinitionExampleJSON
45 describe "Security Definitions Object" $ securityDefinitionsExample <=> securityDefinitionsExampleJSON
32 describe "Security Definitions Object" $ securityDefinitionsExample <=> securityDefinitionsExampleJSON
46− describe "OAuth2 Security Definitions with merged Scope" $ oAuth2SecurityDefinitionsExample <=> oAuth2SecurityDefinitionsExampleJSON
47− describe "Composition Schema Example" $ compositionSchemaExample <=> compositionSchemaExampleJSON
48 describe "Swagger Object" $ do
33 describe "Swagger Object" $ do
49 context "Todo Example" $ swaggerExample <=> swaggerExampleJSON
34 context "Todo Example" $ swaggerExample <=> swaggerExampleJSON
50 context "PetStore Example" $
35 context "PetStore Example" $
@@ -59,13 +44,13 @@ main = hspec spec
59-- =======================================================================
44-- =======================================================================
60
45
61infoExample :: Info
46infoExample :: Info
62−infoExample = mempty
47+infoExample = Info
63− & title .~ "Swagger Sample App"
48+ { _infoTitle = "Swagger Sample App"
64− & description ?~ "This is a sample server Petstore server."
49+ , _infoDescription = Just "This is a sample server Petstore server."
65− & termsOfService ?~ "http://swagger.io/terms/"
50+ , _infoTermsOfService = Just "http://swagger.io/terms/"
66− & contact ?~ contactExample
51+ , _infoContact = Just contactExample
67− & license ?~ licenseExample
52+ , _infoLicense = Just licenseExample
68− & version .~ "1.0.1"
53+ , _infoVersion = "1.0.1" }
69
54
70infoExampleJSON :: Value
55infoExampleJSON :: Value
71infoExampleJSON = [aesonQQ|
56infoExampleJSON = [aesonQQ|
@@ -91,10 +76,10 @@ infoExampleJSON = [aesonQQ|
91-- =======================================================================
76-- =======================================================================
92
77
93contactExample :: Contact
78contactExample :: Contact
94−contactExample = mempty
79+contactExample = Contact
95− & name ?~ "API Support"
80+ { _contactName = Just "API Support"
96− & url ?~ URL "http://www.swagger.io/support"
81+ , _contactUrl = Just (URL "http://www.swagger.io/support")
97− & email ?~ "support@swagger.io"
82+ , _contactEmail = Just "support@swagger.io" }
98
83
99contactExampleJSON :: Value
84contactExampleJSON :: Value
100contactExampleJSON = [aesonQQ|
85contactExampleJSON = [aesonQQ|
@@ -110,8 +95,9 @@ contactExampleJSON = [aesonQQ|
110-- =======================================================================
95-- =======================================================================
111
96
112licenseExample :: License
97licenseExample :: License
113−licenseExample = "Apache 2.0"
98+licenseExample = License
99+ { _licenseName = "Apache 2.0"
114− & url ?~ URL "http://www.apache.org/licenses/LICENSE-2.0.html"
100+ , _licenseUrl = Just (URL "http://www.apache.org/licenses/LICENSE-2.0.html") }
115
101
116licenseExampleJSON :: Value
102licenseExampleJSON :: Value
117licenseExampleJSON = [aesonQQ|
103licenseExampleJSON = [aesonQQ|
@@ -128,38 +114,46 @@ licenseExampleJSON = [aesonQQ|
128
114
129operationExample :: Operation
115operationExample :: Operation
130operationExample = mempty
116operationExample = mempty
131− & tags .~ InsOrdHS.fromList ["pet"]
117+ { _operationTags = ["pet"]
132− & summary ?~ "Updates a pet in the store with form data"
118+ , _operationSummary = Just "Updates a pet in the store with form data"
133− & description ?~ ""
119+ , _operationDescription = Just ""
134− & operationId ?~ "updatePetWithForm"
120+ , _operationOperationId = Just "updatePetWithForm"
135− & consumes ?~ MimeList ["application/x-www-form-urlencoded"]
121+ , _operationConsumes = Just (MimeList ["application/x-www-form-urlencoded"])
136− & produces ?~ MimeList ["application/json", "application/xml"]
122+ , _operationProduces = Just (MimeList ["application/json", "application/xml"])
123+ , _operationParameters = params
124+ , _operationResponses = responses
125+ , _operationSecurity = security
126+ }
127+ where
128+ security = [SecurityRequirement [("petstore_auth", ["write:pets", "read:pets"])]]
129+
130+ responses = mempty
131+ { _responsesResponses =
132+ [ (200, Inline mempty { _responseDescription = "Pet updated." })
133+ , (405, Inline mempty { _responseDescription = "Invalid input" }) ] }
134+
137− & parameters .~ map Inline
135+ params = map Inline
138− [ mempty
136+ [ Param
139− & name .~ "petId"
137+ { _paramName = "petId"
140− & description ?~ "ID of pet that needs to be updated"
138+ , _paramDescription = Just "ID of pet that needs to be updated"
141− & required ?~ True
139+ , _paramRequired = Just True
142− & schema .~ ParamOther (stringSchema ParamPath)
140+ , _paramSchema = ParamOther (stringSchema ParamPath) }
143− , mempty
141+ , Param
144− & name .~ "name"
142+ { _paramName = "name"
145− & description ?~ "Updated name of the pet"
143+ , _paramDescription = Just "Updated name of the pet"
146− & required ?~ False
144+ , _paramRequired = Just False
147− & schema .~ ParamOther (stringSchema ParamFormData)
145+ , _paramSchema = ParamOther (stringSchema ParamFormData) }
148− , mempty
146+ , Param
149− & name .~ "status"
147+ { _paramName = "status"
150− & description ?~ "Updated status of the pet"
148+ , _paramDescription = Just "Updated status of the pet"
151− & required ?~ False
149+ , _paramRequired = Just False
152− & schema .~ ParamOther (stringSchema ParamFormData)
150+ , _paramSchema = ParamOther (stringSchema ParamFormData) }
153 ]
151 ]
154
152
155− & at 200 ?~ "Pet updated."
156− & at 405 ?~ "Invalid input"
157− & security .~ [SecurityRequirement [("petstore_auth", ["write:pets", "read:pets"])]]
158− where
159 stringSchema :: ParamLocation -> ParamOtherSchema
153 stringSchema :: ParamLocation -> ParamOtherSchema
160− stringSchema loc = mempty
154+ stringSchema i = mempty
161− & in_ .~ loc
155+ & paramOtherSchemaIn .~ i
162− & type_ ?~ SwaggerString
156+ & schemaType .~ SwaggerString
163
157
164operationExampleJSON :: Value
158operationExampleJSON :: Value
165operationExampleJSON = [aesonQQ|
159operationExampleJSON = [aesonQQ|
@@ -225,8 +219,8 @@ operationExampleJSON = [aesonQQ|
225
219
226schemaPrimitiveExample :: Schema
220schemaPrimitiveExample :: Schema
227schemaPrimitiveExample = mempty
221schemaPrimitiveExample = mempty
228− & type_ ?~ SwaggerString
222+ & schemaType .~ SwaggerString
229− & format ?~ "email"
223+ & schemaFormat ?~ "email"
230
224
231schemaPrimitiveExampleJSON :: Value
225schemaPrimitiveExampleJSON :: Value
232schemaPrimitiveExampleJSON = [aesonQQ|
226schemaPrimitiveExampleJSON = [aesonQQ|
@@ -238,15 +232,15 @@ schemaPrimitiveExampleJSON = [aesonQQ|
238
232
239schemaSimpleModelExample :: Schema
233schemaSimpleModelExample :: Schema
240schemaSimpleModelExample = mempty
234schemaSimpleModelExample = mempty
241− & type_ ?~ SwaggerObject
235+ & schemaType .~ SwaggerObject
242− & required .~ [ "name" ]
236+ & schemaRequired .~ [ "name" ]
243− & properties .~
237+ & schemaProperties .~
244− [ ("name", Inline (mempty & type_ ?~ SwaggerString))
238+ [ ("name", Inline (mempty & schemaType .~ SwaggerString))
245 , ("address", Ref (Reference "Address"))
239 , ("address", Ref (Reference "Address"))
246 , ("age", Inline $ mempty
240 , ("age", Inline $ mempty
247− & minimum_ ?~ 0
241+ & schemaMinimum ?~ 0
248− & type_ ?~ SwaggerInteger
242+ & schemaType .~ SwaggerInteger
249− & format ?~ "int32" ) ]
243+ & schemaFormat ?~ "int32" ) ]
250
244
251schemaSimpleModelExampleJSON :: Value
245schemaSimpleModelExampleJSON :: Value
252schemaSimpleModelExampleJSON = [aesonQQ|
246schemaSimpleModelExampleJSON = [aesonQQ|
@@ -273,8 +267,8 @@ schemaSimpleModelExampleJSON = [aesonQQ|
273
267
274schemaModelDictExample :: Schema
268schemaModelDictExample :: Schema
275schemaModelDictExample = mempty
269schemaModelDictExample = mempty
276− & type_ ?~ SwaggerObject
270+ & schemaType .~ SwaggerObject
277− & additionalProperties ?~ AdditionalPropertiesSchema (Inline (mempty & type_ ?~ SwaggerString))
271+ & schemaAdditionalProperties ?~ (mempty & schemaType .~ SwaggerString)
278
272
279schemaModelDictExampleJSON :: Value
273schemaModelDictExampleJSON :: Value
280schemaModelDictExampleJSON = [aesonQQ|
274schemaModelDictExampleJSON = [aesonQQ|
@@ -286,35 +280,20 @@ schemaModelDictExampleJSON = [aesonQQ|
286}
280}
287|]
281|]
288
282
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−
302schemaWithExampleExample :: Schema
283schemaWithExampleExample :: Schema
303−schemaWithExampleExample = mempty
284+schemaWithExampleExample = (mempty & schemaType .~ SwaggerObject)
304− & type_ ?~ SwaggerObject
285+ { _schemaProperties =
305− & properties .~
306 [ ("id", Inline $ mempty
286 [ ("id", Inline $ mempty
307− & type_ ?~ SwaggerInteger
287+ & schemaType .~ SwaggerInteger
308− & format ?~ "int64" )
288+ & schemaFormat ?~ "int64" )
309− , ("name", Inline $ mempty
289+ , ("name", Inline (mempty & schemaType .~ SwaggerString)) ]
310− & type_ ?~ SwaggerString) ]
290+ , _schemaRequired = [ "name" ]
311− & required .~ [ "name" ]
291+ , _schemaExample = Just [aesonQQ|
312− & example ?~ [aesonQQ|
313− {
292+ {
314− "name": "Puma",
293+ "name": "Puma",
315− "id": 1
294+ "id": 1
316− }
295+ }
317− |]
296+ |] }
318
297
319schemaWithExampleExampleJSON :: Value
298schemaWithExampleExampleJSON :: Value
320schemaWithExampleExampleJSON = [aesonQQ|
299schemaWithExampleExampleJSON = [aesonQQ|
@@ -346,19 +325,19 @@ schemaWithExampleExampleJSON = [aesonQQ|
346definitionsExample :: HashMap Text Schema
325definitionsExample :: HashMap Text Schema
347definitionsExample =
326definitionsExample =
348 [ ("Category", mempty
327 [ ("Category", mempty
349− & type_ ?~ SwaggerObject
328+ & schemaType .~ SwaggerObject
350− & properties .~
329+ & schemaProperties .~
351 [ ("id", Inline $ mempty
330 [ ("id", Inline $ mempty
352− & type_ ?~ SwaggerInteger
331+ & schemaType .~ SwaggerInteger
353− & format ?~ "int64")
332+ & schemaFormat ?~ "int64")
354− , ("name", Inline (mempty & type_ ?~ SwaggerString)) ] )
333+ , ("name", Inline (mempty & schemaType .~ SwaggerString)) ] )
355 , ("Tag", mempty
334 , ("Tag", mempty
356− & type_ ?~ SwaggerObject
335+ & schemaType .~ SwaggerObject
357− & properties .~
336+ & schemaProperties .~
358 [ ("id", Inline $ mempty
337 [ ("id", Inline $ mempty
359− & type_ ?~ SwaggerInteger
338+ & schemaType .~ SwaggerInteger
360− & format ?~ "int64")
339+ & schemaFormat ?~ "int64")
361− , ("name", Inline (mempty & type_ ?~ SwaggerString)) ] ) ]
340+ , ("name", Inline (mempty & schemaType .~ SwaggerString)) ] ) ]
362
341
363definitionsExampleJSON :: Value
342definitionsExampleJSON :: Value
364definitionsExampleJSON = [aesonQQ|
343definitionsExampleJSON = [aesonQQ|
@@ -397,21 +376,21 @@ definitionsExampleJSON = [aesonQQ|
397paramsDefinitionExample :: HashMap Text Param
376paramsDefinitionExample :: HashMap Text Param
398paramsDefinitionExample =
377paramsDefinitionExample =
399 [ ("skipParam", mempty
378 [ ("skipParam", mempty
400− & name .~ "skip"
379+ { _paramName = "skip"
401− & description ?~ "number of items to skip"
380+ , _paramDescription = Just "number of items to skip"
402− & required ?~ True
381+ , _paramRequired = Just True
403− & schema .~ ParamOther (mempty
382+ , _paramSchema = ParamOther $ mempty
404− & in_ .~ ParamQuery
383+ & paramOtherSchemaIn .~ ParamQuery
405− & type_ ?~ SwaggerInteger
384+ & schemaType .~ SwaggerInteger
406− & format ?~ "int32" ))
385+ & schemaFormat ?~ "int32" })
407 , ("limitParam", mempty
386 , ("limitParam", mempty
408− & name .~ "limit"
387+ { _paramName = "limit"
409− & description ?~ "max records to return"
388+ , _paramDescription = Just "max records to return"
410− & required ?~ True
389+ , _paramRequired = Just True
411− & schema .~ ParamOther (mempty
390+ , _paramSchema = ParamOther $ mempty
412− & in_ .~ ParamQuery
391+ & paramOtherSchemaIn .~ ParamQuery
413− & type_ ?~ SwaggerInteger
392+ & schemaType .~ SwaggerInteger
414− & format ?~ "int32" )) ]
393+ & schemaFormat ?~ "int32" }) ]
415
394
416paramsDefinitionExampleJSON :: Value
395paramsDefinitionExampleJSON :: Value
417paramsDefinitionExampleJSON = [aesonQQ|
396paramsDefinitionExampleJSON = [aesonQQ|
@@ -441,8 +420,8 @@ paramsDefinitionExampleJSON = [aesonQQ|
441
420
442responsesDefinitionExample :: HashMap Text Response
421responsesDefinitionExample :: HashMap Text Response
443responsesDefinitionExample =
422responsesDefinitionExample =
444− [ ("NotFound", mempty & description .~ "Entity not found.")
423+ [ ("NotFound", mempty { _responseDescription = "Entity not found." })
445− , ("IllegalInput", mempty & description .~ "Illegal input for operation.") ]
424+ , ("IllegalInput", mempty { _responseDescription = "Illegal input for operation." }) ]
446
425
447responsesDefinitionExampleJSON :: Value
426responsesDefinitionExampleJSON :: Value
448responsesDefinitionExampleJSON = [aesonQQ|
427responsesDefinitionExampleJSON = [aesonQQ|
@@ -460,8 +439,8 @@ responsesDefinitionExampleJSON = [aesonQQ|
460-- Responses Definition object
439-- Responses Definition object
461-- =======================================================================
440-- =======================================================================
462
441
463−securityDefinitionsExample :: SecurityDefinitions
442+securityDefinitionsExample :: HashMap Text SecurityScheme
464−securityDefinitionsExample = SecurityDefinitions
443+securityDefinitionsExample =
465 [ ("api_key", SecurityScheme
444 [ ("api_key", SecurityScheme
466 { _securitySchemeType = SecuritySchemeApiKey (ApiKeyParams "api_key" ApiKeyHeader)
445 { _securitySchemeType = SecuritySchemeApiKey (ApiKeyParams "api_key" ApiKeyHeader)
467 , _securitySchemeDescription = Nothing })
446 , _securitySchemeDescription = Nothing })
@@ -493,86 +472,51 @@ securityDefinitionsExampleJSON = [aesonQQ|
493}
472}
494|]
473|]
495
474
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−
536-- =======================================================================
475-- =======================================================================
537-- Swagger object
476-- Swagger object
538-- =======================================================================
477-- =======================================================================
539
478
540swaggerExample :: Swagger
479swaggerExample :: Swagger
541swaggerExample = mempty
480swaggerExample = mempty
542− & basePath ?~ "/"
481+ { _basePath = Just "/"
543− & schemes ?~ [Http]
482+ , _schemes = Just [Http]
544− & info .~ (mempty
483+ , _info = mempty
545− & version .~ "1.0"
484+ { _infoVersion = "1.0"
546− & title .~ "Todo API"
485+ , _infoTitle = "Todo API"
547− & license ?~ "MIT"
486+ , _infoLicense = Just License
487+ { _licenseName = "MIT"
548− & license._Just.url ?~ URL "http://mit.com"
488+ , _licenseUrl = Just (URL "http://mit.com") }
549− & description ?~ "This is a an API that tests servant-swagger support for a Todo API")
489+ , _infoDescription = Just "This is a an API that tests servant-swagger support for a Todo API" }
490+ , _paths = mempty
491+ { _pathsMap =
550− & paths.at "/todo/{id}" ?~ (mempty & get ?~ ((mempty :: Operation)
492+ [ ("/todo/{id}", mempty
493+ { _pathItemGet = Just mempty
494+ { _operationResponses = mempty
495+ { _responsesResponses =
551− & at 200 ?~ Inline (mempty
496+ [ (200, Inline mempty
552− & description .~ "OK"
497+ { _responseSchema = Just $ Inline (mempty & schemaType .~ SwaggerObject)
553− & schema ?~ Inline (mempty
498+ { _schemaExample = Just [aesonQQ|
554− & type_ ?~ SwaggerObject
555− & example ?~ [aesonQQ|
556− {
499+ {
557− "created": 100,
500+ "created": 100,
558− "description": "get milk"
501+ "description": "get milk"
559− } |]
502+ } |]
560− & description ?~ "This is some real Todo right here"
503+ , _schemaDescription = Just "This is some real Todo right here"
561− & properties .~
504+ , _schemaProperties =
562− [ ("created", Inline $ mempty
505+ [ ("created", Inline $ mempty
563− & type_ ?~ SwaggerInteger
506+ & schemaType .~ SwaggerInteger
564− & format ?~ "int32")
507+ & schemaFormat ?~ "int32")
565− , ("description", Inline (mempty & type_ ?~ SwaggerString))]))
508+ , ("description", Inline (mempty & schemaType .~ SwaggerString)) ] }
509+ , _responseDescription = "OK" }) ] }
566− & produces ?~ MimeList [ "application/json" ]
510+ , _operationProduces = Just (MimeList [ "application/json" ])
567− & parameters .~
511+ , _operationParameters =
568− [ Inline $ mempty
512+ [ Inline mempty
569− & required ?~ True
513+ { _paramRequired = Just True
570− & name .~ "id"
514+ , _paramName = "id"
571− & description ?~ "TodoId param"
515+ , _paramDescription = Just "TodoId param"
572− & schema .~ ParamOther (mempty
516+ , _paramSchema = ParamOther $ mempty
573− & in_ .~ ParamPath
517+ & paramOtherSchemaIn .~ ParamPath
574− & type_ ?~ SwaggerString ) ]
518+ & schemaType .~ SwaggerString } ]
575− & tags .~ InsOrdHS.fromList [ "todo" ] ))
519+ , _operationTags = [ "todo" ] } }) ] } }
576
520
577swaggerExampleJSON :: Value
521swaggerExampleJSON :: Value
578swaggerExampleJSON = [aesonQQ|
522swaggerExampleJSON = [aesonQQ|
@@ -639,130 +583,130 @@ swaggerExampleJSON = [aesonQQ|
639
583
640petstoreExampleJSON :: Value
584petstoreExampleJSON :: Value
641petstoreExampleJSON = [aesonQQ|
585petstoreExampleJSON = [aesonQQ|
642−{
586+{
643 "swagger":"2.0",
587 "swagger":"2.0",
644− "info":{
588+ "info":{
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.",
589 "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.",
646 "version":"1.0.0",
590 "version":"1.0.0",
647 "title":"Swagger Petstore",
591 "title":"Swagger Petstore",
648 "termsOfService":"http://swagger.io/terms/",
592 "termsOfService":"http://swagger.io/terms/",
649− "contact":{
593+ "contact":{
650 "email":"apiteam@swagger.io"
594 "email":"apiteam@swagger.io"
651 },
595 },
652− "license":{
596+ "license":{
653 "name":"Apache 2.0",
597 "name":"Apache 2.0",
654 "url":"http://www.apache.org/licenses/LICENSE-2.0.html"
598 "url":"http://www.apache.org/licenses/LICENSE-2.0.html"
655 }
599 }
656 },
600 },
657 "host":"petstore.swagger.io",
601 "host":"petstore.swagger.io",
658 "basePath":"/v2",
602 "basePath":"/v2",
659− "tags":[
603+ "tags":[
660− {
604+ {
661 "name":"pet",
605 "name":"pet",
662 "description":"Everything about your Pets",
606 "description":"Everything about your Pets",
663− "externalDocs":{
607+ "externalDocs":{
664 "description":"Find out more",
608 "description":"Find out more",
665 "url":"http://swagger.io"
609 "url":"http://swagger.io"
666 }
610 }
667 },
611 },
668− {
612+ {
669 "name":"store",
613 "name":"store",
670 "description":"Access to Petstore orders"
614 "description":"Access to Petstore orders"
671 },
615 },
672− {
616+ {
673 "name":"user",
617 "name":"user",
674 "description":"Operations about user",
618 "description":"Operations about user",
675− "externalDocs":{
619+ "externalDocs":{
676 "description":"Find out more about our store",
620 "description":"Find out more about our store",
677 "url":"http://swagger.io"
621 "url":"http://swagger.io"
678 }
622 }
679 }
623 }
680 ],
624 ],
681− "schemes":[
625+ "schemes":[
682 "http"
626 "http"
683 ],
627 ],
684− "paths":{
628+ "paths":{
685− "/pet":{
629+ "/pet":{
686− "post":{
630+ "post":{
687− "tags":[
631+ "tags":[
688 "pet"
632 "pet"
689 ],
633 ],
690 "summary":"Add a new pet to the store",
634 "summary":"Add a new pet to the store",
691 "description":"",
635 "description":"",
692 "operationId":"addPet",
636 "operationId":"addPet",
693− "consumes":[
637+ "consumes":[
694 "application/json",
638 "application/json",
695 "application/xml"
639 "application/xml"
696 ],
640 ],
697− "produces":[
641+ "produces":[
698 "application/xml",
642 "application/xml",
699 "application/json"
643 "application/json"
700 ],
644 ],
701− "parameters":[
645+ "parameters":[
702− {
646+ {
703 "in":"body",
647 "in":"body",
704 "name":"body",
648 "name":"body",
705 "description":"Pet object that needs to be added to the store",
649 "description":"Pet object that needs to be added to the store",
706 "required":true,
650 "required":true,
707− "schema":{
651+ "schema":{
708 "$ref":"#/definitions/Pet"
652 "$ref":"#/definitions/Pet"
709 }
653 }
710 }
654 }
711 ],
655 ],
712− "responses":{
656+ "responses":{
713− "405":{
657+ "405":{
714 "description":"Invalid input"
658 "description":"Invalid input"
715 }
659 }
716 },
660 },
717− "security":[
661+ "security":[
718− {
662+ {
719− "petstore_auth":[
663+ "petstore_auth":[
720 "write:pets",
664 "write:pets",
721 "read:pets"
665 "read:pets"
722 ]
666 ]
723 }
667 }
724 ]
668 ]
725 },
669 },
726− "put":{
670+ "put":{
727− "tags":[
671+ "tags":[
728 "pet"
672 "pet"
729 ],
673 ],
730 "summary":"Update an existing pet",
674 "summary":"Update an existing pet",
731 "description":"",
675 "description":"",
732 "operationId":"updatePet",
676 "operationId":"updatePet",
733− "consumes":[
677+ "consumes":[
734 "application/json",
678 "application/json",
735 "application/xml"
679 "application/xml"
736 ],
680 ],
737− "produces":[
681+ "produces":[
738 "application/xml",
682 "application/xml",
739 "application/json"
683 "application/json"
740 ],
684 ],
741− "parameters":[
685+ "parameters":[
742− {
686+ {
743 "in":"body",
687 "in":"body",
744 "name":"body",
688 "name":"body",
745 "description":"Pet object that needs to be added to the store",
689 "description":"Pet object that needs to be added to the store",
746 "required":true,
690 "required":true,
747− "schema":{
691+ "schema":{
748 "$ref":"#/definitions/Pet"
692 "$ref":"#/definitions/Pet"
749 }
693 }
750 }
694 }
751 ],
695 ],
752− "responses":{
696+ "responses":{
753− "400":{
697+ "400":{
754 "description":"Invalid ID supplied"
698 "description":"Invalid ID supplied"
755 },
699 },
756− "404":{
700+ "404":{
757 "description":"Pet not found"
701 "description":"Pet not found"
758 },
702 },
759− "405":{
703+ "405":{
760 "description":"Validation exception"
704 "description":"Validation exception"
761 }
705 }
762 },
706 },
763− "security":[
707+ "security":[
764− {
708+ {
765− "petstore_auth":[
709+ "petstore_auth":[
766 "write:pets",
710 "write:pets",
767 "read:pets"
711 "read:pets"
768 ]
712 ]
@@ -770,28 +714,28 @@ petstoreExampleJSON = [aesonQQ|
770 ]
714 ]
771 }
715 }
772 },
716 },
773− "/pet/findByStatus":{
717+ "/pet/findByStatus":{
774− "get":{
718+ "get":{
775− "tags":[
719+ "tags":[
776 "pet"
720 "pet"
777 ],
721 ],
778 "summary":"Finds Pets by status",
722 "summary":"Finds Pets by status",
779 "description":"Multiple status values can be provided with comma seperated strings",
723 "description":"Multiple status values can be provided with comma seperated strings",
780 "operationId":"findPetsByStatus",
724 "operationId":"findPetsByStatus",
781− "produces":[
725+ "produces":[
782 "application/xml",
726 "application/xml",
783 "application/json"
727 "application/json"
784 ],
728 ],
785− "parameters":[
729+ "parameters":[
786− {
730+ {
787 "name":"status",
731 "name":"status",
788 "in":"query",
732 "in":"query",
789 "description":"Status values that need to be considered for filter",
733 "description":"Status values that need to be considered for filter",
790 "required":true,
734 "required":true,
791 "type":"array",
735 "type":"array",
792− "items":{
736+ "items":{
793 "type":"string",
737 "type":"string",
794− "enum":[
738+ "enum":[
795 "available",
739 "available",
796 "pending",
740 "pending",
797 "sold"
741 "sold"
@@ -801,23 +745,23 @@ petstoreExampleJSON = [aesonQQ|
801 "collectionFormat":"csv"
745 "collectionFormat":"csv"
802 }
746 }
803 ],
747 ],
804− "responses":{
748+ "responses":{
805− "200":{
749+ "200":{
806 "description":"successful operation",
750 "description":"successful operation",
807− "schema":{
751+ "schema":{
808 "type":"array",
752 "type":"array",
809− "items":{
753+ "items":{
810 "$ref":"#/definitions/Pet"
754 "$ref":"#/definitions/Pet"
811 }
755 }
812 }
756 }
813 },
757 },
814− "400":{
758+ "400":{
815 "description":"Invalid status value"
759 "description":"Invalid status value"
816 }
760 }
817 },
761 },
818− "security":[
762+ "security":[
819− {
763+ {
820− "petstore_auth":[
764+ "petstore_auth":[
821 "write:pets",
765 "write:pets",
822 "read:pets"
766 "read:pets"
823 ]
767 ]
@@ -825,48 +769,48 @@ petstoreExampleJSON = [aesonQQ|
825 ]
769 ]
826 }
770 }
827 },
771 },
828− "/pet/findByTags":{
772+ "/pet/findByTags":{
829− "get":{
773+ "get":{
830− "tags":[
774+ "tags":[
831 "pet"
775 "pet"
832 ],
776 ],
833 "summary":"Finds Pets by tags",
777 "summary":"Finds Pets by tags",
834 "description":"Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.",
778 "description":"Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.",
835 "operationId":"findPetsByTags",
779 "operationId":"findPetsByTags",
836− "produces":[
780+ "produces":[
837 "application/xml",
781 "application/xml",
838 "application/json"
782 "application/json"
839 ],
783 ],
840− "parameters":[
784+ "parameters":[
841− {
785+ {
842 "name":"tags",
786 "name":"tags",
843 "in":"query",
787 "in":"query",
844 "description":"Tags to filter by",
788 "description":"Tags to filter by",
845 "required":true,
789 "required":true,
846 "type":"array",
790 "type":"array",
847− "items":{
791+ "items":{
848 "type":"string"
792 "type":"string"
849 },
793 },
850 "collectionFormat":"csv"
794 "collectionFormat":"csv"
851 }
795 }
852 ],
796 ],
853− "responses":{
797+ "responses":{
854− "200":{
798+ "200":{
855 "description":"successful operation",
799 "description":"successful operation",
856− "schema":{
800+ "schema":{
857 "type":"array",
801 "type":"array",
858− "items":{
802+ "items":{
859 "$ref":"#/definitions/Pet"
803 "$ref":"#/definitions/Pet"
860 }
804 }
861 }
805 }
862 },
806 },
863− "400":{
807+ "400":{
864 "description":"Invalid tag value"
808 "description":"Invalid tag value"
865 }
809 }
866 },
810 },
867− "security":[
811+ "security":[
868− {
812+ {
869− "petstore_auth":[
813+ "petstore_auth":[
870 "write:pets",
814 "write:pets",
871 "read:pets"
815 "read:pets"
872 ]
816 ]
@@ -874,20 +818,20 @@ petstoreExampleJSON = [aesonQQ|
874 ]
818 ]
875 }
819 }
876 },
820 },
877− "/pet/{petId}":{
821+ "/pet/{petId}":{
878− "get":{
822+ "get":{
879− "tags":[
823+ "tags":[
880 "pet"
824 "pet"
881 ],
825 ],
882 "summary":"Find pet by ID",
826 "summary":"Find pet by ID",
883 "description":"Returns a single pet",
827 "description":"Returns a single pet",
884 "operationId":"getPetById",
828 "operationId":"getPetById",
885− "produces":[
829+ "produces":[
886 "application/xml",
830 "application/xml",
887 "application/json"
831 "application/json"
888 ],
832 ],
889− "parameters":[
833+ "parameters":[
890− {
834+ {
891 "name":"petId",
835 "name":"petId",
892 "in":"path",
836 "in":"path",
893 "description":"ID of pet to return",
837 "description":"ID of pet to return",
@@ -896,42 +840,43 @@ petstoreExampleJSON = [aesonQQ|
896 "format":"int64"
840 "format":"int64"
897 }
841 }
898 ],
842 ],
899− "responses":{
843+ "responses":{
900− "200":{
844+ "200":{
901 "description":"successful operation",
845 "description":"successful operation",
902− "schema":{
846+ "schema":{
903 "$ref":"#/definitions/Pet"
847 "$ref":"#/definitions/Pet"
904 }
848 }
905 },
849 },
906− "400":{
850+ "400":{
907 "description":"Invalid ID supplied"
851 "description":"Invalid ID supplied"
908 },
852 },
909− "404":{
853+ "404":{
910 "description":"Pet not found"
854 "description":"Pet not found"
911 }
855 }
912 },
856 },
913− "security":[
857+ "security":[
914− {
858+ {
915− "api_key": []
859+ "api_key":[
860+ ]
916 }
861 }
917 ]
862 ]
918 },
863 },
919− "post":{
864+ "post":{
920− "tags":[
865+ "tags":[
921 "pet"
866 "pet"
922 ],
867 ],
923 "summary":"Updates a pet in the store with form data",
868 "summary":"Updates a pet in the store with form data",
924 "description":"",
869 "description":"",
925 "operationId":"updatePetWithForm",
870 "operationId":"updatePetWithForm",
926− "consumes":[
871+ "consumes":[
927 "application/x-www-form-urlencoded"
872 "application/x-www-form-urlencoded"
928 ],
873 ],
929− "produces":[
874+ "produces":[
930 "application/xml",
875 "application/xml",
931 "application/json"
876 "application/json"
932 ],
877 ],
933− "parameters":[
878+ "parameters":[
934− {
879+ {
935 "name":"petId",
880 "name":"petId",
936 "in":"path",
881 "in":"path",
937 "description":"ID of pet that needs to be updated",
882 "description":"ID of pet that needs to be updated",
@@ -939,14 +884,14 @@ petstoreExampleJSON = [aesonQQ|
939 "type":"integer",
884 "type":"integer",
940 "format":"int64"
885 "format":"int64"
941 },
886 },
942− {
887+ {
943 "name":"name",
888 "name":"name",
944 "in":"formData",
889 "in":"formData",
945 "description":"Updated name of the pet",
890 "description":"Updated name of the pet",
946 "required":false,
891 "required":false,
947 "type":"string"
892 "type":"string"
948 },
893 },
949− {
894+ {
950 "name":"status",
895 "name":"status",
951 "in":"formData",
896 "in":"formData",
952 "description":"Updated status of the pet",
897 "description":"Updated status of the pet",
@@ -954,39 +899,39 @@ petstoreExampleJSON = [aesonQQ|
954 "type":"string"
899 "type":"string"
955 }
900 }
956 ],
901 ],
957− "responses":{
902+ "responses":{
958− "405":{
903+ "405":{
959 "description":"Invalid input"
904 "description":"Invalid input"
960 }
905 }
961 },
906 },
962− "security":[
907+ "security":[
963− {
908+ {
964− "petstore_auth":[
909+ "petstore_auth":[
965 "write:pets",
910 "write:pets",
966 "read:pets"
911 "read:pets"
967 ]
912 ]
968 }
913 }
969 ]
914 ]
970 },
915 },
971− "delete":{
916+ "delete":{
972− "tags":[
917+ "tags":[
973 "pet"
918 "pet"
974 ],
919 ],
975 "summary":"Deletes a pet",
920 "summary":"Deletes a pet",
976 "description":"",
921 "description":"",
977 "operationId":"deletePet",
922 "operationId":"deletePet",
978− "produces":[
923+ "produces":[
979 "application/xml",
924 "application/xml",
980 "application/json"
925 "application/json"
981 ],
926 ],
982− "parameters":[
927+ "parameters":[
983− {
928+ {
984 "name":"api_key",
929 "name":"api_key",
985 "in":"header",
930 "in":"header",
986 "required":false,
931 "required":false,
987 "type":"string"
932 "type":"string"
988 },
933 },
989− {
934+ {
990 "name":"petId",
935 "name":"petId",
991 "in":"path",
936 "in":"path",
992 "description":"Pet id to delete",
937 "description":"Pet id to delete",
@@ -995,14 +940,14 @@ petstoreExampleJSON = [aesonQQ|
995 "format":"int64"
940 "format":"int64"
996 }
941 }
997 ],
942 ],
998− "responses":{
943+ "responses":{
999− "400":{
944+ "400":{
1000 "description":"Invalid pet value"
945 "description":"Invalid pet value"
1001 }
946 }
1002 },
947 },
1003− "security":[
948+ "security":[
1004− {
949+ {
1005− "petstore_auth":[
950+ "petstore_auth":[
1006 "write:pets",
951 "write:pets",
1007 "read:pets"
952 "read:pets"
1008 ]
953 ]
@@ -1010,22 +955,22 @@ petstoreExampleJSON = [aesonQQ|
1010 ]
955 ]
1011 }
956 }
1012 },
957 },
1013− "/pet/{petId}/uploadImage":{
958+ "/pet/{petId}/uploadImage":{
1014− "post":{
959+ "post":{
1015− "tags":[
960+ "tags":[
1016 "pet"
961 "pet"
1017 ],
962 ],
1018 "summary":"uploads an image",
963 "summary":"uploads an image",
1019 "description":"",
964 "description":"",
1020 "operationId":"uploadFile",
965 "operationId":"uploadFile",
1021− "consumes":[
966+ "consumes":[
1022 "multipart/form-data"
967 "multipart/form-data"
1023 ],
968 ],
1024− "produces":[
969+ "produces":[
1025 "application/json"
970 "application/json"
1026 ],
971 ],
1027− "parameters":[
972+ "parameters":[
1028− {
973+ {
1029 "name":"petId",
974 "name":"petId",
1030 "in":"path",
975 "in":"path",
1031 "description":"ID of pet to update",
976 "description":"ID of pet to update",
@@ -1033,14 +978,14 @@ petstoreExampleJSON = [aesonQQ|
1033 "type":"integer",
978 "type":"integer",
1034 "format":"int64"
979 "format":"int64"
1035 },
980 },
1036− {
981+ {
1037 "name":"additionalMetadata",
982 "name":"additionalMetadata",
1038 "in":"formData",
983 "in":"formData",
1039 "description":"Additional data to pass to server",
984 "description":"Additional data to pass to server",
1040 "required":false,
985 "required":false,
1041 "type":"string"
986 "type":"string"
1042 },
987 },
1043− {
988+ {
1044 "name":"file",
989 "name":"file",
1045 "in":"formData",
990 "in":"formData",
1046 "description":"file to upload",
991 "description":"file to upload",
@@ -1048,17 +993,17 @@ petstoreExampleJSON = [aesonQQ|
1048 "type":"file"
993 "type":"file"
1049 }
994 }
1050 ],
995 ],
1051− "responses":{
996+ "responses":{
1052− "200":{
997+ "200":{
1053 "description":"successful operation",
998 "description":"successful operation",
1054− "schema":{
999+ "schema":{
1055 "$ref":"#/definitions/ApiResponse"
1000 "$ref":"#/definitions/ApiResponse"
1056 }
1001 }
1057 }
1002 }
1058 },
1003 },
1059− "security":[
1004+ "security":[
1060− {
1005+ {
1061− "petstore_auth":[
1006+ "petstore_auth":[
1062 "write:pets",
1007 "write:pets",
1063 "read:pets"
1008 "read:pets"
1064 ]
1009 ]
@@ -1066,87 +1011,89 @@ petstoreExampleJSON = [aesonQQ|
1066 ]
1011 ]
1067 }
1012 }
1068 },
1013 },
1069− "/store/inventory":{
1014+ "/store/inventory":{
1070− "get":{
1015+ "get":{
1071− "tags":[
1016+ "tags":[
1072 "store"
1017 "store"
1073 ],
1018 ],
1074 "summary":"Returns pet inventories by status",
1019 "summary":"Returns pet inventories by status",
1075 "description":"Returns a map of status codes to quantities",
1020 "description":"Returns a map of status codes to quantities",
1076 "operationId":"getInventory",
1021 "operationId":"getInventory",
1077− "produces":[
1022+ "produces":[
1078 "application/json"
1023 "application/json"
1079 ],
1024 ],
1080− "parameters": [],
1025+ "parameters":[
1026+ ],
1081− "responses":{
1027+ "responses":{
1082− "200":{
1028+ "200":{
1083 "description":"successful operation",
1029 "description":"successful operation",
1084− "schema":{
1030+ "schema":{
1085 "type":"object",
1031 "type":"object",
1086− "additionalProperties":{
1032+ "additionalProperties":{
1087 "type":"integer",
1033 "type":"integer",
1088 "format":"int32"
1034 "format":"int32"
1089 }
1035 }
1090 }
1036 }
1091 }
1037 }
1092 },
1038 },
1093− "security":[
1039+ "security":[
1094− {
1040+ {
1095− "api_key": []
1041+ "api_key":[
1042+ ]
1096 }
1043 }
1097 ]
1044 ]
1098 }
1045 }
1099 },
1046 },
1100− "/store/order":{
1047+ "/store/order":{
1101− "post":{
1048+ "post":{
1102− "tags":[
1049+ "tags":[
1103 "store"
1050 "store"
1104 ],
1051 ],
1105 "summary":"Place an order for a pet",
1052 "summary":"Place an order for a pet",
1106 "description":"",
1053 "description":"",
1107 "operationId":"placeOrder",
1054 "operationId":"placeOrder",
1108− "produces":[
1055+ "produces":[
1109 "application/xml",
1056 "application/xml",
1110 "application/json"
1057 "application/json"
1111 ],
1058 ],
1112− "parameters":[
1059+ "parameters":[
1113− {
1060+ {
1114 "in":"body",
1061 "in":"body",
1115 "name":"body",
1062 "name":"body",
1116 "description":"order placed for purchasing the pet",
1063 "description":"order placed for purchasing the pet",
1117 "required":true,
1064 "required":true,
1118− "schema":{
1065+ "schema":{
1119 "$ref":"#/definitions/Order"
1066 "$ref":"#/definitions/Order"
1120 }
1067 }
1121 }
1068 }
1122 ],
1069 ],
1123− "responses":{
1070+ "responses":{
1124− "200":{
1071+ "200":{
1125 "description":"successful operation",
1072 "description":"successful operation",
1126− "schema":{
1073+ "schema":{
1127 "$ref":"#/definitions/Order"
1074 "$ref":"#/definitions/Order"
1128 }
1075 }
1129 },
1076 },
1130− "400":{
1077+ "400":{
1131 "description":"Invalid Order"
1078 "description":"Invalid Order"
1132 }
1079 }
1133 }
1080 }
1134 }
1081 }
1135 },
1082 },
1136− "/store/order/{orderId}":{
1083+ "/store/order/{orderId}":{
1137− "get":{
1084+ "get":{
1138− "tags":[
1085+ "tags":[
1139 "store"
1086 "store"
1140 ],
1087 ],
1141 "summary":"Find purchase order by ID",
1088 "summary":"Find purchase order by ID",
1142 "description":"For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions",
1089 "description":"For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions",
1143 "operationId":"getOrderById",
1090 "operationId":"getOrderById",
1144− "produces":[
1091+ "produces":[
1145 "application/xml",
1092 "application/xml",
1146 "application/json"
1093 "application/json"
1147 ],
1094 ],
1148− "parameters":[
1095+ "parameters":[
1149− {
1096+ {
1150 "name":"orderId",
1097 "name":"orderId",
1151 "in":"path",
1098 "in":"path",
1152 "description":"ID of pet that needs to be fetched",
1099 "description":"ID of pet that needs to be fetched",
@@ -1157,34 +1104,34 @@ petstoreExampleJSON = [aesonQQ|
1157 "format":"int64"
1104 "format":"int64"
1158 }
1105 }
1159 ],
1106 ],
1160− "responses":{
1107+ "responses":{
1161− "200":{
1108+ "200":{
1162 "description":"successful operation",
1109 "description":"successful operation",
1163− "schema":{
1110+ "schema":{
1164 "$ref":"#/definitions/Order"
1111 "$ref":"#/definitions/Order"
1165 }
1112 }
1166 },
1113 },
1167− "400":{
1114+ "400":{
1168 "description":"Invalid ID supplied"
1115 "description":"Invalid ID supplied"
1169 },
1116 },
1170− "404":{
1117+ "404":{
1171 "description":"Order not found"
1118 "description":"Order not found"
1172 }
1119 }
1173 }
1120 }
1174 },
1121 },
1175− "delete":{
1122+ "delete":{
1176− "tags":[
1123+ "tags":[
1177 "store"
1124 "store"
1178 ],
1125 ],
1179 "summary":"Delete purchase order by ID",
1126 "summary":"Delete purchase order by ID",
1180 "description":"For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors",
1127 "description":"For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors",
1181 "operationId":"deleteOrder",
1128 "operationId":"deleteOrder",
1182− "produces":[
1129+ "produces":[
1183 "application/xml",
1130 "application/xml",
1184 "application/json"
1131 "application/json"
1185 ],
1132 ],
1186− "parameters":[
1133+ "parameters":[
1187− {
1134+ {
1188 "name":"orderId",
1135 "name":"orderId",
1189 "in":"path",
1136 "in":"path",
1190 "description":"ID of the order that needs to be deleted",
1137 "description":"ID of the order that needs to be deleted",
@@ -1193,133 +1140,133 @@ petstoreExampleJSON = [aesonQQ|
1193 "minimum":1.0
1140 "minimum":1.0
1194 }
1141 }
1195 ],
1142 ],
1196− "responses":{
1143+ "responses":{
1197− "400":{
1144+ "400":{
1198 "description":"Invalid ID supplied"
1145 "description":"Invalid ID supplied"
1199 },
1146 },
1200− "404":{
1147+ "404":{
1201 "description":"Order not found"
1148 "description":"Order not found"
1202 }
1149 }
1203 }
1150 }
1204 }
1151 }
1205 },
1152 },
1206− "/user":{
1153+ "/user":{
1207− "post":{
1154+ "post":{
1208− "tags":[
1155+ "tags":[
1209 "user"
1156 "user"
1210 ],
1157 ],
1211 "summary":"Create user",
1158 "summary":"Create user",
1212 "description":"This can only be done by the logged in user.",
1159 "description":"This can only be done by the logged in user.",
1213 "operationId":"createUser",
1160 "operationId":"createUser",
1214− "produces":[
1161+ "produces":[
1215 "application/xml",
1162 "application/xml",
1216 "application/json"
1163 "application/json"
1217 ],
1164 ],
1218− "parameters":[
1165+ "parameters":[
1219− {
1166+ {
1220 "in":"body",
1167 "in":"body",
1221 "name":"body",
1168 "name":"body",
1222 "description":"Created user object",
1169 "description":"Created user object",
1223 "required":true,
1170 "required":true,
1224− "schema":{
1171+ "schema":{
1225 "$ref":"#/definitions/User"
1172 "$ref":"#/definitions/User"
1226 }
1173 }
1227 }
1174 }
1228 ],
1175 ],
1229− "responses":{
1176+ "responses":{
1230− "default":{
1177+ "default":{
1231 "description":"successful operation"
1178 "description":"successful operation"
1232 }
1179 }
1233 }
1180 }
1234 }
1181 }
1235 },
1182 },
1236− "/user/createWithArray":{
1183+ "/user/createWithArray":{
1237− "post":{
1184+ "post":{
1238− "tags":[
1185+ "tags":[
1239 "user"
1186 "user"
1240 ],
1187 ],
1241 "summary":"Creates list of users with given input array",
1188 "summary":"Creates list of users with given input array",
1242 "description":"",
1189 "description":"",
1243 "operationId":"createUsersWithArrayInput",
1190 "operationId":"createUsersWithArrayInput",
1244− "produces":[
1191+ "produces":[
1245 "application/xml",
1192 "application/xml",
1246 "application/json"
1193 "application/json"
1247 ],
1194 ],
1248− "parameters":[
1195+ "parameters":[
1249− {
1196+ {
1250 "in":"body",
1197 "in":"body",
1251 "name":"body",
1198 "name":"body",
1252 "description":"List of user object",
1199 "description":"List of user object",
1253 "required":true,
1200 "required":true,
1254− "schema":{
1201+ "schema":{
1255 "type":"array",
1202 "type":"array",
1256− "items":{
1203+ "items":{
1257 "$ref":"#/definitions/User"
1204 "$ref":"#/definitions/User"
1258 }
1205 }
1259 }
1206 }
1260 }
1207 }
1261 ],
1208 ],
1262− "responses":{
1209+ "responses":{
1263− "default":{
1210+ "default":{
1264 "description":"successful operation"
1211 "description":"successful operation"
1265 }
1212 }
1266 }
1213 }
1267 }
1214 }
1268 },
1215 },
1269− "/user/createWithList":{
1216+ "/user/createWithList":{
1270− "post":{
1217+ "post":{
1271− "tags":[
1218+ "tags":[
1272 "user"
1219 "user"
1273 ],
1220 ],
1274 "summary":"Creates list of users with given input array",
1221 "summary":"Creates list of users with given input array",
1275 "description":"",
1222 "description":"",
1276 "operationId":"createUsersWithListInput",
1223 "operationId":"createUsersWithListInput",
1277− "produces":[
1224+ "produces":[
1278 "application/xml",
1225 "application/xml",
1279 "application/json"
1226 "application/json"
1280 ],
1227 ],
1281− "parameters":[
1228+ "parameters":[
1282− {
1229+ {
1283 "in":"body",
1230 "in":"body",
1284 "name":"body",
1231 "name":"body",
1285 "description":"List of user object",
1232 "description":"List of user object",
1286 "required":true,
1233 "required":true,
1287− "schema":{
1234+ "schema":{
1288 "type":"array",
1235 "type":"array",
1289− "items":{
1236+ "items":{
1290 "$ref":"#/definitions/User"
1237 "$ref":"#/definitions/User"
1291 }
1238 }
1292 }
1239 }
1293 }
1240 }
1294 ],
1241 ],
1295− "responses":{
1242+ "responses":{
1296− "default":{
1243+ "default":{
1297 "description":"successful operation"
1244 "description":"successful operation"
1298 }
1245 }
1299 }
1246 }
1300 }
1247 }
1301 },
1248 },
1302− "/user/login":{
1249+ "/user/login":{
1303− "get":{
1250+ "get":{
1304− "tags":[
1251+ "tags":[
1305 "user"
1252 "user"
1306 ],
1253 ],
1307 "summary":"Logs user into the system",
1254 "summary":"Logs user into the system",
1308 "description":"",
1255 "description":"",
1309 "operationId":"loginUser",
1256 "operationId":"loginUser",
1310− "produces":[
1257+ "produces":[
1311 "application/xml",
1258 "application/xml",
1312 "application/json"
1259 "application/json"
1313 ],
1260 ],
1314− "parameters":[
1261+ "parameters":[
1315− {
1262+ {
1316 "name":"username",
1263 "name":"username",
1317 "in":"query",
1264 "in":"query",
1318 "description":"The user name for login",
1265 "description":"The user name for login",
1319 "required":true,
1266 "required":true,
1320 "type":"string"
1267 "type":"string"
1321 },
1268 },
1322− {
1269+ {
1323 "name":"password",
1270 "name":"password",
1324 "in":"query",
1271 "in":"query",
1325 "description":"The password for login in clear text",
1272 "description":"The password for login in clear text",
@@ -1327,65 +1274,66 @@ petstoreExampleJSON = [aesonQQ|
1327 "type":"string"
1274 "type":"string"
1328 }
1275 }
1329 ],
1276 ],
1330− "responses":{
1277+ "responses":{
1331− "200":{
1278+ "200":{
1332 "description":"successful operation",
1279 "description":"successful operation",
1333− "schema":{
1280+ "schema":{
1334 "type":"string"
1281 "type":"string"
1335 },
1282 },
1336− "headers":{
1283+ "headers":{
1337− "X-Rate-Limit":{
1284+ "X-Rate-Limit":{
1338 "type":"integer",
1285 "type":"integer",
1339 "format":"int32",
1286 "format":"int32",
1340 "description":"calls per hour allowed by the user"
1287 "description":"calls per hour allowed by the user"
1341 },
1288 },
1342− "X-Expires-After":{
1289+ "X-Expires-After":{
1343 "type":"string",
1290 "type":"string",
1344 "format":"date-time",
1291 "format":"date-time",
1345 "description":"date in UTC when toekn expires"
1292 "description":"date in UTC when toekn expires"
1346 }
1293 }
1347 }
1294 }
1348 },
1295 },
1349− "400":{
1296+ "400":{
1350 "description":"Invalid username/password supplied"
1297 "description":"Invalid username/password supplied"
1351 }
1298 }
1352 }
1299 }
1353 }
1300 }
1354 },
1301 },
1355− "/user/logout":{
1302+ "/user/logout":{
1356− "get":{
1303+ "get":{
1357− "tags":[
1304+ "tags":[
1358 "user"
1305 "user"
1359 ],
1306 ],
1360 "summary":"Logs out current logged in user session",
1307 "summary":"Logs out current logged in user session",
1361 "description":"",
1308 "description":"",
1362 "operationId":"logoutUser",
1309 "operationId":"logoutUser",
1363− "produces":[
1310+ "produces":[
1364 "application/xml",
1311 "application/xml",
1365 "application/json"
1312 "application/json"
1366 ],
1313 ],
1367− "parameters": [],
1314+ "parameters":[
1315+ ],
1368− "responses":{
1316+ "responses":{
1369− "default":{
1317+ "default":{
1370 "description":"successful operation"
1318 "description":"successful operation"
1371 }
1319 }
1372 }
1320 }
1373 }
1321 }
1374 },
1322 },
1375− "/user/{username}":{
1323+ "/user/{username}":{
1376− "get":{
1324+ "get":{
1377− "tags":[
1325+ "tags":[
1378 "user"
1326 "user"
1379 ],
1327 ],
1380 "summary":"Get user by user name",
1328 "summary":"Get user by user name",
1381 "description":"",
1329 "description":"",
1382 "operationId":"getUserByName",
1330 "operationId":"getUserByName",
1383− "produces":[
1331+ "produces":[
1384 "application/xml",
1332 "application/xml",
1385 "application/json"
1333 "application/json"
1386 ],
1334 ],
1387− "parameters":[
1335+ "parameters":[
1388− {
1336+ {
1389 "name":"username",
1337 "name":"username",
1390 "in":"path",
1338 "in":"path",
1391 "description":"The name that needs to be fetched. Use user1 for testing. ",
1339 "description":"The name that needs to be fetched. Use user1 for testing. ",
@@ -1393,72 +1341,72 @@ petstoreExampleJSON = [aesonQQ|
1393 "type":"string"
1341 "type":"string"
1394 }
1342 }
1395 ],
1343 ],
1396− "responses":{
1344+ "responses":{
1397− "200":{
1345+ "200":{
1398 "description":"successful operation",
1346 "description":"successful operation",
1399− "schema":{
1347+ "schema":{
1400 "$ref":"#/definitions/User"
1348 "$ref":"#/definitions/User"
1401 }
1349 }
1402 },
1350 },
1403− "400":{
1351+ "400":{
1404 "description":"Invalid username supplied"
1352 "description":"Invalid username supplied"
1405 },
1353 },
1406− "404":{
1354+ "404":{
1407 "description":"User not found"
1355 "description":"User not found"
1408 }
1356 }
1409 }
1357 }
1410 },
1358 },
1411− "put":{
1359+ "put":{
1412− "tags":[
1360+ "tags":[
1413 "user"
1361 "user"
1414 ],
1362 ],
1415 "summary":"Updated user",
1363 "summary":"Updated user",
1416 "description":"This can only be done by the logged in user.",
1364 "description":"This can only be done by the logged in user.",
1417 "operationId":"updateUser",
1365 "operationId":"updateUser",
1418− "produces":[
1366+ "produces":[
1419 "application/xml",
1367 "application/xml",
1420 "application/json"
1368 "application/json"
1421 ],
1369 ],
1422− "parameters":[
1370+ "parameters":[
1423− {
1371+ {
1424 "name":"username",
1372 "name":"username",
1425 "in":"path",
1373 "in":"path",
1426 "description":"name that need to be deleted",
1374 "description":"name that need to be deleted",
1427 "required":true,
1375 "required":true,
1428 "type":"string"
1376 "type":"string"
1429 },
1377 },
1430− {
1378+ {
1431 "in":"body",
1379 "in":"body",
1432 "name":"body",
1380 "name":"body",
1433 "description":"Updated user object",
1381 "description":"Updated user object",
1434 "required":true,
1382 "required":true,
1435− "schema":{
1383+ "schema":{
1436 "$ref":"#/definitions/User"
1384 "$ref":"#/definitions/User"
1437 }
1385 }
1438 }
1386 }
1439 ],
1387 ],
1440− "responses":{
1388+ "responses":{
1441− "400":{
1389+ "400":{
1442 "description":"Invalid user supplied"
1390 "description":"Invalid user supplied"
1443 },
1391 },
1444− "404":{
1392+ "404":{
1445 "description":"User not found"
1393 "description":"User not found"
1446 }
1394 }
1447 }
1395 }
1448 },
1396 },
1449− "delete":{
1397+ "delete":{
1450− "tags":[
1398+ "tags":[
1451 "user"
1399 "user"
1452 ],
1400 ],
1453 "summary":"Delete user",
1401 "summary":"Delete user",
1454 "description":"This can only be done by the logged in user.",
1402 "description":"This can only be done by the logged in user.",
1455 "operationId":"deleteUser",
1403 "operationId":"deleteUser",
1456− "produces":[
1404+ "produces":[
1457 "application/xml",
1405 "application/xml",
1458 "application/json"
1406 "application/json"
1459 ],
1407 ],
1460− "parameters":[
1408+ "parameters":[
1461− {
1409+ {
1462 "name":"username",
1410 "name":"username",
1463 "in":"path",
1411 "in":"path",
1464 "description":"The name that needs to be deleted",
1412 "description":"The name that needs to be deleted",
@@ -1466,237 +1414,207 @@ petstoreExampleJSON = [aesonQQ|
1466 "type":"string"
1414 "type":"string"
1467 }
1415 }
1468 ],
1416 ],
1469− "responses":{
1417+ "responses":{
1470− "400":{
1418+ "400":{
1471 "description":"Invalid username supplied"
1419 "description":"Invalid username supplied"
1472 },
1420 },
1473− "404":{
1421+ "404":{
1474 "description":"User not found"
1422 "description":"User not found"
1475 }
1423 }
1476 }
1424 }
1477 }
1425 }
1478 }
1426 }
1479 },
1427 },
1480− "securityDefinitions":{
1428+ "securityDefinitions":{
1481− "petstore_auth":{
1429+ "petstore_auth":{
1482 "type":"oauth2",
1430 "type":"oauth2",
1483 "authorizationUrl":"http://petstore.swagger.io/api/oauth/dialog",
1431 "authorizationUrl":"http://petstore.swagger.io/api/oauth/dialog",
1484 "flow":"implicit",
1432 "flow":"implicit",
1485− "scopes":{
1433+ "scopes":{
1486 "write:pets":"modify pets in your account",
1434 "write:pets":"modify pets in your account",
1487 "read:pets":"read your pets"
1435 "read:pets":"read your pets"
1488 }
1436 }
1489 },
1437 },
1490− "api_key":{
1438+ "api_key":{
1491 "type":"apiKey",
1439 "type":"apiKey",
1492 "name":"api_key",
1440 "name":"api_key",
1493 "in":"header"
1441 "in":"header"
1494 }
1442 }
1495 },
1443 },
1496− "definitions":{
1444+ "definitions":{
1497− "Order":{
1445+ "Order":{
1498 "type":"object",
1446 "type":"object",
1499− "properties":{
1447+ "properties":{
1500− "id":{
1448+ "id":{
1501 "type":"integer",
1449 "type":"integer",
1502 "format":"int64"
1450 "format":"int64"
1503 },
1451 },
1504− "petId":{
1452+ "petId":{
1505 "type":"integer",
1453 "type":"integer",
1506 "format":"int64"
1454 "format":"int64"
1507 },
1455 },
1508− "quantity":{
1456+ "quantity":{
1509 "type":"integer",
1457 "type":"integer",
1510 "format":"int32"
1458 "format":"int32"
1511 },
1459 },
1512− "shipDate":{
1460+ "shipDate":{
1513 "type":"string",
1461 "type":"string",
1514 "format":"date-time"
1462 "format":"date-time"
1515 },
1463 },
1516− "status":{
1464+ "status":{
1517 "type":"string",
1465 "type":"string",
1518 "description":"Order Status",
1466 "description":"Order Status",
1519− "enum":[
1467+ "enum":[
1520 "placed",
1468 "placed",
1521 "approved",
1469 "approved",
1522 "delivered"
1470 "delivered"
1523 ]
1471 ]
1524 },
1472 },
1525− "complete":{
1473+ "complete":{
1526 "type":"boolean",
1474 "type":"boolean",
1527 "default":false
1475 "default":false
1528 }
1476 }
1529 },
1477 },
1530− "xml":{
1478+ "xml":{
1531 "name":"Order"
1479 "name":"Order"
1532 }
1480 }
1533 },
1481 },
1534− "Category":{
1482+ "Category":{
1535 "type":"object",
1483 "type":"object",
1536− "properties":{
1484+ "properties":{
1537− "id":{
1485+ "id":{
1538 "type":"integer",
1486 "type":"integer",
1539 "format":"int64"
1487 "format":"int64"
1540 },
1488 },
1541− "name":{
1489+ "name":{
1542 "type":"string"
1490 "type":"string"
1543 }
1491 }
1544 },
1492 },
1545− "xml":{
1493+ "xml":{
1546 "name":"Category"
1494 "name":"Category"
1547 }
1495 }
1548 },
1496 },
1549− "User":{
1497+ "User":{
1550 "type":"object",
1498 "type":"object",
1551− "properties":{
1499+ "properties":{
1552− "id":{
1500+ "id":{
1553 "type":"integer",
1501 "type":"integer",
1554 "format":"int64"
1502 "format":"int64"
1555 },
1503 },
1556− "username":{
1504+ "username":{
1557 "type":"string"
1505 "type":"string"
1558 },
1506 },
1559− "firstName":{
1507+ "firstName":{
1560 "type":"string"
1508 "type":"string"
1561 },
1509 },
1562− "lastName":{
1510+ "lastName":{
1563 "type":"string"
1511 "type":"string"
1564 },
1512 },
1565− "email":{
1513+ "email":{
1566 "type":"string"
1514 "type":"string"
1567 },
1515 },
1568− "password":{
1516+ "password":{
1569 "type":"string"
1517 "type":"string"
1570 },
1518 },
1571− "phone":{
1519+ "phone":{
1572 "type":"string"
1520 "type":"string"
1573 },
1521 },
1574− "userStatus":{
1522+ "userStatus":{
1575 "type":"integer",
1523 "type":"integer",
1576 "format":"int32",
1524 "format":"int32",
1577 "description":"User Status"
1525 "description":"User Status"
1578 }
1526 }
1579 },
1527 },
1580− "xml":{
1528+ "xml":{
1581 "name":"User"
1529 "name":"User"
1582 }
1530 }
1583 },
1531 },
1584− "Tag":{
1532+ "Tag":{
1585 "type":"object",
1533 "type":"object",
1586− "properties":{
1534+ "properties":{
1587− "id":{
1535+ "id":{
1588 "type":"integer",
1536 "type":"integer",
1589 "format":"int64"
1537 "format":"int64"
1590 },
1538 },
1591− "name":{
1539+ "name":{
1592 "type":"string"
1540 "type":"string"
1593 }
1541 }
1594 },
1542 },
1595− "xml":{
1543+ "xml":{
1596 "name":"Tag"
1544 "name":"Tag"
1597 }
1545 }
1598 },
1546 },
1599− "Pet":{
1547+ "Pet":{
1600 "type":"object",
1548 "type":"object",
1601− "required":[
1549+ "required":[
1602 "name",
1550 "name",
1603 "photoUrls"
1551 "photoUrls"
1604 ],
1552 ],
1605− "properties":{
1553+ "properties":{
1606− "id":{
1554+ "id":{
1607 "type":"integer",
1555 "type":"integer",
1608 "format":"int64"
1556 "format":"int64"
1609 },
1557 },
1610− "category":{
1558+ "category":{
1611 "$ref":"#/definitions/Category"
1559 "$ref":"#/definitions/Category"
1612 },
1560 },
1613− "name":{
1561+ "name":{
1614 "type":"string",
1562 "type":"string",
1615 "example":"doggie"
1563 "example":"doggie"
1616 },
1564 },
1617− "photoUrls":{
1565+ "photoUrls":{
1618 "type":"array",
1566 "type":"array",
1619− "xml":{
1567+ "xml":{
1620 "name":"photoUrl",
1568 "name":"photoUrl",
1621 "wrapped":true
1569 "wrapped":true
1622 },
1570 },
1623− "items":{
1571+ "items":{
1624 "type":"string"
1572 "type":"string"
1625 }
1573 }
1626 },
1574 },
1627− "tags":{
1575+ "tags":{
1628 "type":"array",
1576 "type":"array",
1629− "xml":{
1577+ "xml":{
1630 "name":"tag",
1578 "name":"tag",
1631 "wrapped":true
1579 "wrapped":true
1632 },
1580 },
1633− "items":{
1581+ "items":{
1634 "$ref":"#/definitions/Tag"
1582 "$ref":"#/definitions/Tag"
1635 }
1583 }
1636 },
1584 },
1637− "status":{
1585+ "status":{
1638 "type":"string",
1586 "type":"string",
1639 "description":"pet status in the store",
1587 "description":"pet status in the store",
1640− "enum":[
1588+ "enum":[
1641 "available",
1589 "available",
1642 "pending",
1590 "pending",
1643 "sold"
1591 "sold"
1644 ]
1592 ]
1645 }
1593 }
1646 },
1594 },
1647− "xml":{
1595+ "xml":{
1648 "name":"Pet"
1596 "name":"Pet"
1649 }
1597 }
1650 },
1598 },
1651− "ApiResponse":{
1599+ "ApiResponse":{
1652 "type":"object",
1600 "type":"object",
1653− "properties":{
1601+ "properties":{
1654− "code":{
1602+ "code":{
1655 "type":"integer",
1603 "type":"integer",
1656 "format":"int32"
1604 "format":"int32"
1657 },
1605 },
1658− "type":{
1606+ "type":{
1659 "type":"string"
1607 "type":"string"
1660 },
1608 },
1661− "message":{
1609+ "message":{
1662 "type":"string"
1610 "type":"string"
1663 }
1611 }
1664 }
1612 }
1665 }
1613 }
1666 },
1614 },
1667− "externalDocs":{
1615+ "externalDocs":{
1668 "description":"Find out more about Swagger",
1616 "description":"Find out more about Swagger",
1669 "url":"http://swagger.io"
1617 "url":"http://swagger.io"
1670 }
1618 }
1671}
1619}
1672|]
1620|]
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.hsnew file+7
@@ -0,0 +1,7 @@
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
test/SpecCommon.hs+2−7
@@ -1,7 +1,6 @@
1module SpecCommon where
1module SpecCommon where
2
2
3import Data.Aeson
3import Data.Aeson
4−import Data.ByteString.Builder (toLazyByteString)
5import qualified Data.Foldable as F
4import qualified Data.Foldable as F
6import qualified Data.HashMap.Strict as HashMap
5import qualified Data.HashMap.Strict as HashMap
7import qualified Data.Vector as Vector
6import qualified Data.Vector as Vector
@@ -22,9 +21,5 @@ x <=> js = do
22 toJSON x `shouldBe` js
21 toJSON x `shouldBe` js
23 it "decodes correctly" $ do
22 it "decodes correctly" $ do
24 fromJSON js `shouldBe` Success x
23 fromJSON js `shouldBe` Success x
25− it "roundtrips: eitherDecode . encode" $ do
24+
26− eitherDecode (encode x) `shouldBe` Right x
25+
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.hsdeleted−12
@@ -1,12 +0,0 @@
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