git.iko.soy/typeable/openapi3
on 867ff82 help sign in
34 files changed+744−1767
since splitsnapshots
unifiedsplit
.github/workflows/haskell-ci.yml−243 .travis.yml+149 CHANGELOG.md−47 README.md+2−2 cabal.haskell-ci−11 cabal.project−2 examples/hackage.hs+11−11 openapi3.cabal+40−44 src/Data/OpenApi/Aeson/Compat.hs−76 src/Data/OpenApi.hs → src/Data/Swagger.hs+47−168 src/Data/OpenApi/Declare.hs → src/Data/Swagger/Declare.hs+2−2 src/Data/OpenApi/Internal.hs → src/Data/Swagger/Internal.hs+81−147 src/Data/OpenApi/Internal/AesonUtils.hs → src/Data/Swagger/Internal/AesonUtils.hs+13−12 src/Data/OpenApi/Internal/ParamSchema.hs → src/Data/Swagger/Internal/ParamSchema.hs+37−55 src/Data/OpenApi/Internal/Schema.hs → src/Data/Swagger/Internal/Schema.hs+118−380 src/Data/OpenApi/Internal/Schema/Validation.hs → src/Data/Swagger/Internal/Schema/Validation.hs+62−74 src/Data/OpenApi/Internal/TypeShape.hs → src/Data/Swagger/Internal/TypeShape.hs+1−1 src/Data/OpenApi/Internal/Utils.hs → src/Data/Swagger/Internal/Utils.hs+1−6 src/Data/OpenApi/Lens.hs → src/Data/Swagger/Lens.hs+20−20 src/Data/OpenApi/Operation.hs → src/Data/Swagger/Operation.hs+29−136 src/Data/OpenApi/Optics.hs → src/Data/Swagger/Optics.hs+29−74 src/Data/OpenApi/ParamSchema.hs → src/Data/Swagger/ParamSchema.hs+4−4 src/Data/OpenApi/Schema.hs → src/Data/Swagger/Schema.hs+4−4 src/Data/OpenApi/Schema/Generator.hs → src/Data/Swagger/Schema/Generator.hs+14−16 src/Data/OpenApi/Schema/Validation.hs → src/Data/Swagger/Schema/Validation.hs+7−7 src/Data/OpenApi/SchemaOptions.hs → src/Data/Swagger/SchemaOptions.hs+2−2 stack.yaml+1−1 test/Data/OpenApi/CommonTestTypes.hs → test/Data/Swagger/CommonTestTypes.hs+2−125 test/Data/OpenApi/ParamSchemaSpec.hs → test/Data/Swagger/ParamSchemaSpec.hs+3−3 test/Data/OpenApi/Schema/GeneratorSpec.hs → test/Data/Swagger/Schema/GeneratorSpec.hs+7−7 test/Data/OpenApi/Schema/ValidationSpec.hs → test/Data/Swagger/Schema/ValidationSpec.hs+10−27 test/Data/OpenApi/SchemaSpec.hs → test/Data/Swagger/SchemaSpec.hs+4−8 test/Data/OpenApiSpec.hs → test/Data/SwaggerSpec.hs+36−52 test/SpecCommon.hs+8
.github/workflows/haskell-ci.ymldeleted−243
@@ -1,243 +0,0 @@
1−# This GitHub workflow config has been generated by a script via
2−#
3−# haskell-ci 'github' 'cabal.project'
4−#
5−# To regenerate the script (for example after adjusting tested-with) run
6−#
7−# haskell-ci regenerate
8−#
9−# For more information, see https://github.com/haskell-CI/haskell-ci
10−#
11−# version: 0.14.3
12−#
13−# REGENDATA ("0.14.3",["github","cabal.project"])
14−#
15−name: Haskell-CI
16−on:
17− push:
18− branches:
19− - master
20− pull_request:
21− branches:
22− - master
23−jobs:
24− linux:
25− name: Haskell-CI - Linux - ${{ matrix.compiler }}
26− runs-on: ubuntu-18.04
27− timeout-minutes:
28− 60
29− container:
30− image: buildpack-deps:focal
31− continue-on-error: ${{ matrix.allow-failure }}
32− strategy:
33− matrix:
34− include:
35− - compiler: ghc-9.2.2
36− compilerKind: ghc
37− compilerVersion: 9.2.2
38− setup-method: ghcup
39− allow-failure: true
40− - compiler: ghc-9.0.2
41− compilerKind: ghc
42− compilerVersion: 9.0.2
43− setup-method: ghcup
44− allow-failure: false
45− - compiler: ghc-8.10.7
46− compilerKind: ghc
47− compilerVersion: 8.10.7
48− setup-method: ghcup
49− allow-failure: false
50− - compiler: ghc-8.8.4
51− compilerKind: ghc
52− compilerVersion: 8.8.4
53− setup-method: hvr-ppa
54− allow-failure: false
55− - compiler: ghc-8.6.5
56− compilerKind: ghc
57− compilerVersion: 8.6.5
58− setup-method: hvr-ppa
59− allow-failure: false
60− - compiler: ghc-8.4.4
61− compilerKind: ghc
62− compilerVersion: 8.4.4
63− setup-method: hvr-ppa
64− allow-failure: false
65− fail-fast: false
66− steps:
67− - name: apt
68− run: |
69− apt-get update
70− apt-get install -y --no-install-recommends gnupg ca-certificates dirmngr curl git software-properties-common libtinfo5
71− if [ "${{ matrix.setup-method }}" = ghcup ]; then
72− mkdir -p "$HOME/.ghcup/bin"
73− curl -sL https://downloads.haskell.org/ghcup/0.1.17.5/x86_64-linux-ghcup-0.1.17.5 > "$HOME/.ghcup/bin/ghcup"
74− chmod a+x "$HOME/.ghcup/bin/ghcup"
75− "$HOME/.ghcup/bin/ghcup" install ghc "$HCVER"
76− "$HOME/.ghcup/bin/ghcup" install cabal 3.6.2.0
77− else
78− apt-add-repository -y 'ppa:hvr/ghc'
79− apt-get update
80− apt-get install -y "$HCNAME"
81− mkdir -p "$HOME/.ghcup/bin"
82− curl -sL https://downloads.haskell.org/ghcup/0.1.17.5/x86_64-linux-ghcup-0.1.17.5 > "$HOME/.ghcup/bin/ghcup"
83− chmod a+x "$HOME/.ghcup/bin/ghcup"
84− "$HOME/.ghcup/bin/ghcup" install cabal 3.6.2.0
85− fi
86− env:
87− HCKIND: ${{ matrix.compilerKind }}
88− HCNAME: ${{ matrix.compiler }}
89− HCVER: ${{ matrix.compilerVersion }}
90− - name: Set PATH and environment variables
91− run: |
92− echo "$HOME/.cabal/bin" >> $GITHUB_PATH
93− echo "LANG=C.UTF-8" >> "$GITHUB_ENV"
94− echo "CABAL_DIR=$HOME/.cabal" >> "$GITHUB_ENV"
95− echo "CABAL_CONFIG=$HOME/.cabal/config" >> "$GITHUB_ENV"
96− HCDIR=/opt/$HCKIND/$HCVER
97− if [ "${{ matrix.setup-method }}" = ghcup ]; then
98− HC=$HOME/.ghcup/bin/$HCKIND-$HCVER
99− echo "HC=$HC" >> "$GITHUB_ENV"
100− echo "HCPKG=$HOME/.ghcup/bin/$HCKIND-pkg-$HCVER" >> "$GITHUB_ENV"
101− echo "HADDOCK=$HOME/.ghcup/bin/haddock-$HCVER" >> "$GITHUB_ENV"
102− echo "CABAL=$HOME/.ghcup/bin/cabal-3.6.2.0 -vnormal+nowrap" >> "$GITHUB_ENV"
103− else
104− HC=$HCDIR/bin/$HCKIND
105− echo "HC=$HC" >> "$GITHUB_ENV"
106− echo "HCPKG=$HCDIR/bin/$HCKIND-pkg" >> "$GITHUB_ENV"
107− echo "HADDOCK=$HCDIR/bin/haddock" >> "$GITHUB_ENV"
108− echo "CABAL=$HOME/.ghcup/bin/cabal-3.6.2.0 -vnormal+nowrap" >> "$GITHUB_ENV"
109− fi
110−
111− HCNUMVER=$(${HC} --numeric-version|perl -ne '/^(\d+)\.(\d+)\.(\d+)(\.(\d+))?$/; print(10000 * $1 + 100 * $2 + ($3 == 0 ? $5 != 1 : $3))')
112− echo "HCNUMVER=$HCNUMVER" >> "$GITHUB_ENV"
113− echo "ARG_TESTS=--enable-tests" >> "$GITHUB_ENV"
114− echo "ARG_BENCH=--enable-benchmarks" >> "$GITHUB_ENV"
115− echo "HEADHACKAGE=false" >> "$GITHUB_ENV"
116− echo "ARG_COMPILER=--$HCKIND --with-compiler=$HC" >> "$GITHUB_ENV"
117− echo "GHCJSARITH=0" >> "$GITHUB_ENV"
118− env:
119− HCKIND: ${{ matrix.compilerKind }}
120− HCNAME: ${{ matrix.compiler }}
121− HCVER: ${{ matrix.compilerVersion }}
122− - name: env
123− run: |
124− env
125− - name: write cabal config
126− run: |
127− mkdir -p $CABAL_DIR
128− cat >> $CABAL_CONFIG <<EOF
129− remote-build-reporting: anonymous
130− write-ghc-environment-files: never
131− remote-repo-cache: $CABAL_DIR/packages
132− logs-dir: $CABAL_DIR/logs
133− world-file: $CABAL_DIR/world
134− extra-prog-path: $CABAL_DIR/bin
135− symlink-bindir: $CABAL_DIR/bin
136− installdir: $CABAL_DIR/bin
137− build-summary: $CABAL_DIR/logs/build.log
138− store-dir: $CABAL_DIR/store
139− install-dirs user
140− prefix: $CABAL_DIR
141− repository hackage.haskell.org
142− url: http://hackage.haskell.org/
143− EOF
144− cat >> $CABAL_CONFIG <<EOF
145− program-default-options
146− ghc-options: $GHCJOBS +RTS -M3G -RTS
147− EOF
148− cat $CABAL_CONFIG
149− - name: versions
150− run: |
151− $HC --version || true
152− $HC --print-project-git-commit-id || true
153− $CABAL --version || true
154− - name: update cabal index
155− run: |
156− $CABAL v2-update -v
157− - name: install cabal-plan
158− run: |
159− mkdir -p $HOME/.cabal/bin
160− curl -sL https://github.com/haskell-hvr/cabal-plan/releases/download/v0.6.2.0/cabal-plan-0.6.2.0-x86_64-linux.xz > cabal-plan.xz
161− echo 'de73600b1836d3f55e32d80385acc055fd97f60eaa0ab68a755302685f5d81bc cabal-plan.xz' | sha256sum -c -
162− xz -d < cabal-plan.xz > $HOME/.cabal/bin/cabal-plan
163− rm -f cabal-plan.xz
164− chmod a+x $HOME/.cabal/bin/cabal-plan
165− cabal-plan --version
166− - name: checkout
167− uses: actions/checkout@v2
168− with:
169− path: source
170− - name: initial cabal.project for sdist
171− run: |
172− touch cabal.project
173− echo "packages: $GITHUB_WORKSPACE/source/." >> cabal.project
174− cat cabal.project
175− - name: sdist
176− run: |
177− mkdir -p sdist
178− $CABAL sdist all --output-dir $GITHUB_WORKSPACE/sdist
179− - name: unpack
180− run: |
181− mkdir -p unpacked
182− find sdist -maxdepth 1 -type f -name '*.tar.gz' -exec tar -C $GITHUB_WORKSPACE/unpacked -xzvf {} \;
183− - name: generate cabal.project
184− run: |
185− PKGDIR_openapi3="$(find "$GITHUB_WORKSPACE/unpacked" -maxdepth 1 -type d -regex '.*/openapi3-[0-9.]*')"
186− echo "PKGDIR_openapi3=${PKGDIR_openapi3}" >> "$GITHUB_ENV"
187− rm -f cabal.project cabal.project.local
188− touch cabal.project
189− touch cabal.project.local
190− echo "packages: ${PKGDIR_openapi3}" >> cabal.project
191− echo "package openapi3" >> cabal.project
192− echo " ghc-options: -Werror=missing-methods" >> cabal.project
193− cat >> cabal.project <<EOF
194− allow-newer: http-media:base
195− EOF
196− $HCPKG list --simple-output --names-only | perl -ne 'for (split /\s+/) { print "constraints: $_ installed\n" unless /^(openapi3)$/; }' >> cabal.project.local
197− cat cabal.project
198− cat cabal.project.local
199− - name: dump install plan
200− run: |
201− $CABAL v2-build $ARG_COMPILER $ARG_TESTS $ARG_BENCH --dry-run all
202− cabal-plan
203− - name: cache
204− uses: actions/cache@v2
205− with:
206− key: ${{ runner.os }}-${{ matrix.compiler }}-${{ github.sha }}
207− path: ~/.cabal/store
208− restore-keys: ${{ runner.os }}-${{ matrix.compiler }}-
209− - name: install dependencies
210− run: |
211− $CABAL v2-build $ARG_COMPILER --disable-tests --disable-benchmarks --dependencies-only -j2 all
212− $CABAL v2-build $ARG_COMPILER $ARG_TESTS $ARG_BENCH --dependencies-only -j2 all
213− - name: build w/o tests
214− run: |
215− $CABAL v2-build $ARG_COMPILER --disable-tests --disable-benchmarks all
216− - name: build
217− run: |
218− $CABAL v2-build $ARG_COMPILER $ARG_TESTS $ARG_BENCH all --write-ghc-environment-files=always
219− - name: tests
220− run: |
221− $CABAL v2-test $ARG_COMPILER $ARG_TESTS $ARG_BENCH all --test-show-details=direct
222− - name: cabal check
223− run: |
224− cd ${PKGDIR_openapi3} || false
225− ${CABAL} -vnormal check
226− - name: haddock
227− run: |
228− $CABAL v2-haddock $ARG_COMPILER --with-haddock $HADDOCK $ARG_TESTS $ARG_BENCH all
229− - name: unconstrained build
230− run: |
231− rm -f cabal.project.local
232− $CABAL v2-build $ARG_COMPILER --disable-tests --disable-benchmarks all
233− - name: prepare for constraint sets
234− run: |
235− rm -f cabal.project.local
236− - name: constraint set aeson-2
237− run: |
238− $CABAL v2-build $ARG_COMPILER --disable-tests --disable-benchmarks --constraint='aeson >=2.0' --dependencies-only -j2 all
239− $CABAL v2-build $ARG_COMPILER --disable-tests --disable-benchmarks --constraint='aeson >=2.0' all
240− - name: constraint set aeson-1
241− run: |
242− if [ $((HCNUMVER < 90200)) -ne 0 ] ; then $CABAL v2-build $ARG_COMPILER --disable-tests --disable-benchmarks --constraint='aeson <2.0' --dependencies-only -j2 all ; fi
243− if [ $((HCNUMVER < 90200)) -ne 0 ] ; then $CABAL v2-build $ARG_COMPILER --disable-tests --disable-benchmarks --constraint='aeson <2.0' all ; fi
.travis.ymlnew file+149
@@ -0,0 +1,149 @@
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' 'openapi3.cabal'
4+#
5+# To regenerate the script (for example after adjusting tested-with) run
6+#
7+# haskell-ci regenerate
8+#
9+# For more information, see https://github.com/haskell-CI/haskell-ci
10+#
11+# version: 0.10.1
12+#
13+version: ~> 1.0
14+language: c
15+os: linux
16+dist: xenial
17+git:
18+ # whether to recursively clone submodules
19+ submodules: false
20+branches:
21+ only:
22+ - master
23+cache:
24+ directories:
25+ - $HOME/.cabal/packages
26+ - $HOME/.cabal/store
27+ - $HOME/.hlint
28+before_cache:
29+ - rm -fv $CABALHOME/packages/hackage.haskell.org/build-reports.log
30+ # remove files that are regenerated by 'cabal update'
31+ - rm -fv $CABALHOME/packages/hackage.haskell.org/00-index.*
32+ - rm -fv $CABALHOME/packages/hackage.haskell.org/*.json
33+ - rm -fv $CABALHOME/packages/hackage.haskell.org/01-index.cache
34+ - rm -fv $CABALHOME/packages/hackage.haskell.org/01-index.tar
35+ - rm -fv $CABALHOME/packages/hackage.haskell.org/01-index.tar.idx
36+ - rm -rfv $CABALHOME/packages/head.hackage
37+jobs:
38+ include:
39+ - compiler: ghc-8.10.1
40+ addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-8.10.1","cabal-install-3.2"]}}
41+ os: linux
42+ - compiler: ghc-8.8.3
43+ addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-8.8.3","cabal-install-3.2"]}}
44+ os: linux
45+ - compiler: ghc-8.6.5
46+ addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-8.6.5","cabal-install-3.2"]}}
47+ os: linux
48+ - compiler: ghc-8.4.4
49+ addons: {"apt":{"sources":[{"sourceline":"deb http://ppa.launchpad.net/hvr/ghc/ubuntu xenial main","key_url":"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x063dab2bdc0b3f9fcebc378bff3aeacef6f88286"}],"packages":["ghc-8.4.4","cabal-install-3.2"]}}
50+ os: linux
51+before_install:
52+ - HC=$(echo "/opt/$CC/bin/ghc" | sed 's/-/\//')
53+ - WITHCOMPILER="-w $HC"
54+ - HADDOCK=$(echo "/opt/$CC/bin/haddock" | sed 's/-/\//')
55+ - HCPKG="$HC-pkg"
56+ - unset CC
57+ - CABAL=/opt/ghc/bin/cabal
58+ - CABALHOME=$HOME/.cabal
59+ - export PATH="$CABALHOME/bin:$PATH"
60+ - TOP=$(pwd)
61+ - "HCNUMVER=$(${HC} --numeric-version|perl -ne '/^(\\d+)\\.(\\d+)\\.(\\d+)(\\.(\\d+))?$/; print(10000 * $1 + 100 * $2 + ($3 == 0 ? $5 != 1 : $3))')"
62+ - echo $HCNUMVER
63+ - CABAL="$CABAL -vnormal+nowrap"
64+ - set -o pipefail
65+ - TEST=--enable-tests
66+ - BENCH=--enable-benchmarks
67+ - HEADHACKAGE=false
68+ - rm -f $CABALHOME/config
69+ - |
70+ echo "verbose: normal +nowrap +markoutput" >> $CABALHOME/config
71+ echo "remote-build-reporting: anonymous" >> $CABALHOME/config
72+ echo "write-ghc-environment-files: always" >> $CABALHOME/config
73+ echo "remote-repo-cache: $CABALHOME/packages" >> $CABALHOME/config
74+ echo "logs-dir: $CABALHOME/logs" >> $CABALHOME/config
75+ echo "world-file: $CABALHOME/world" >> $CABALHOME/config
76+ echo "extra-prog-path: $CABALHOME/bin" >> $CABALHOME/config
77+ echo "symlink-bindir: $CABALHOME/bin" >> $CABALHOME/config
78+ echo "installdir: $CABALHOME/bin" >> $CABALHOME/config
79+ echo "build-summary: $CABALHOME/logs/build.log" >> $CABALHOME/config
80+ echo "store-dir: $CABALHOME/store" >> $CABALHOME/config
81+ echo "install-dirs user" >> $CABALHOME/config
82+ echo " prefix: $CABALHOME" >> $CABALHOME/config
83+ echo "repository hackage.haskell.org" >> $CABALHOME/config
84+ echo " url: http://hackage.haskell.org/" >> $CABALHOME/config
85+install:
86+ - ${CABAL} --version
87+ - echo "$(${HC} --version) [$(${HC} --print-project-git-commit-id 2> /dev/null || echo '?')]"
88+ - |
89+ echo "program-default-options" >> $CABALHOME/config
90+ echo " ghc-options: $GHCJOBS +RTS -M6G -RTS" >> $CABALHOME/config
91+ - cat $CABALHOME/config
92+ - rm -fv cabal.project cabal.project.local cabal.project.freeze
93+ - travis_retry ${CABAL} v2-update -v
94+ # Generate cabal.project
95+ - rm -rf cabal.project cabal.project.local cabal.project.freeze
96+ - touch cabal.project
97+ - |
98+ echo "packages: ." >> cabal.project
99+ - echo 'package openapi3' >> cabal.project
100+ - "echo ' ghc-options: -Werror=missing-methods' >> cabal.project"
101+ - |
102+ - "for pkg in $($HCPKG list --simple-output); do echo $pkg | sed 's/-[^-]*$//' | (grep -vE -- '^(openapi3)$' || true) | sed 's/^/constraints: /' | sed 's/$/ installed/' >> cabal.project.local; done"
103+ - cat cabal.project || true
104+ - cat cabal.project.local || true
105+ - if [ -f "./configure.ac" ]; then (cd "." && autoreconf -i); fi
106+ - ${CABAL} v2-freeze $WITHCOMPILER ${TEST} ${BENCH}
107+ - "cat cabal.project.freeze | sed -E 's/^(constraints: *| *)//' | sed 's/any.//'"
108+ - rm cabal.project.freeze
109+ - travis_wait 40 ${CABAL} v2-build $WITHCOMPILER ${TEST} ${BENCH} --dep -j2 all
110+ - travis_wait 40 ${CABAL} v2-build $WITHCOMPILER --disable-tests --disable-benchmarks --dep -j2 all
111+script:
112+ - DISTDIR=$(mktemp -d /tmp/dist-test.XXXX)
113+ # Packaging...
114+ - ${CABAL} v2-sdist all
115+ # Unpacking...
116+ - mv dist-newstyle/sdist/*.tar.gz ${DISTDIR}/
117+ - cd ${DISTDIR} || false
118+ - find . -maxdepth 1 -type f -name '*.tar.gz' -exec tar -xvf '{}' \;
119+ - find . -maxdepth 1 -type f -name '*.tar.gz' -exec rm '{}' \;
120+ - PKGDIR_openapi3="$(find . -maxdepth 1 -type d -regex '.*/openapi3-[0-9.]*')"
121+ # Generate cabal.project
122+ - rm -rf cabal.project cabal.project.local cabal.project.freeze
123+ - touch cabal.project
124+ - |
125+ echo "packages: ${PKGDIR_openapi3}" >> cabal.project
126+ - echo 'package openapi3' >> cabal.project
127+ - "echo ' ghc-options: -Werror=missing-methods' >> cabal.project"
128+ - |
129+ - "for pkg in $($HCPKG list --simple-output); do echo $pkg | sed 's/-[^-]*$//' | (grep -vE -- '^(openapi3)$' || true) | sed 's/^/constraints: /' | sed 's/$/ installed/' >> cabal.project.local; done"
130+ - cat cabal.project || true
131+ - cat cabal.project.local || true
132+ # Building...
133+ # this builds all libraries and executables (without tests/benchmarks)
134+ - ${CABAL} v2-build $WITHCOMPILER --disable-tests --disable-benchmarks all
135+ # Building with tests and benchmarks...
136+ # build & run tests, build benchmarks
137+ - ${CABAL} v2-build $WITHCOMPILER ${TEST} ${BENCH} all
138+ # Testing...
139+ - ${CABAL} v2-test $WITHCOMPILER ${TEST} ${BENCH} all
140+ # cabal check...
141+ - (cd ${PKGDIR_openapi3} && ${CABAL} -vnormal check)
142+ # haddock...
143+ - ${CABAL} v2-haddock $WITHCOMPILER --with-haddock $HADDOCK ${TEST} ${BENCH} all
144+ # Building without installed constraints for packages in global-db...
145+ - rm -f cabal.project.local
146+ - ${CABAL} v2-build $WITHCOMPILER --disable-tests --disable-benchmarks all
147+
148+# REGENDATA ("0.10.1",["--branches","master","--haddock-jobs=>=8.4","--output",".travis.yml","openapi3.cabal"])
149+# EOF
CHANGELOG.md−47
@@ -1,50 +1,3 @@
1−Unreleased
2−----------
3−
4−3.2.2
5−-----
6−
7−- Fix bug with infinite recursion in GToSchema [#37](https://github.com/biocad/openapi3/pull/37).
8−
9−3.2.1
10−-----
11−
12−- Support aeson-2.0.3.
13−- Support GHC-9.2 (doctests still fail).
14−
15−3.2.0
16−-----
17−
18−- Support aeson-2 [#34](https://github.com/biocad/openapi3/pull/34).
19−- Use `SecurityDefinitions` type for `_componentsSecuritySchemes`
20− [#32](https://github.com/biocad/openapi3/pull/32).
21−
22−3.1.0
23−-----
24−
25−- Use `format: date-time` for `ToParamSchema ZonedTime` instance (see
26− [#20](https://github.com/biocad/openapi3/pull/20)).
27−- Support generating schema for any polymorphic types via `Typeable` (see
28− [#19](https://github.com/biocad/openapi3/pull/19)).
29−- Allow `hashable-1.3.1`, prettify doctests (see [#18](https://github.com/biocad/openapi3/pull/18)).
30−
31−3.0.2.0
32−-------
33−
34−- Fix definition for HTTP security scheme (see [#10](https://github.com/biocad/openapi3/pull/10));
35−- Fix error message in `exclusiveMaximum` / `exclusiveMinimum` validation (see
36− [#15](https://github.com/biocad/openapi3/pull/15));
37−
38−3.0.1.0
39−-------
40−
41−- Support polymorphic types in schema generator.
42−
43−3.0.0
44−-----
45−
46−- Switch to OpenAPI 3.0 specification.
47−
4812.6.1
492-----
503
README.md+2−2
@@ -1,4 +1,4 @@
1−# OpenApi 3
1+# swagger2
22
33[![Hackage](https://img.shields.io/hackage/v/openapi3.svg)](http://hackage.haskell.org/package/openapi3)
44[![Build Status](https://travis-ci.org/biocad/openapi3.svg?branch=master)](https://travis-ci.org/biocad/openapi3)
@@ -14,7 +14,7 @@ https://github.com/GetShopTV/swagger2.
1414
1515## Usage
1616
17−This library is intended to be used for decoding and encoding OpenApi 3.0.3 specifications as well as manipulating them.
17+This library is intended to be used for decoding and encoding Swagger 2.0 API specifications as well as manipulating them.
1818
1919Please refer to [haddock documentation](http://hackage.haskell.org/package/openapi3).
2020
cabal.haskell-cideleted−11
@@ -1,11 +0,0 @@
1−branches: master
2−
3−distribution: focal
4−allow-failures: >=9.2
5−
6−constraint-set aeson-1
7− constraints: aeson <2.0
8− ghc: <9.2
9−
10−constraint-set aeson-2
11− constraints: aeson >=2.0
cabal.project−2
@@ -1,4 +1,2 @@
11packages: .
22tests: true
3−
4−allow-newer: http-media:base
examples/hackage.hs+11−11
@@ -10,10 +10,10 @@ import Data.Proxy
1010import Data.Text (Text)
1111import GHC.Generics
1212
13−import Data.OpenApi
14−import Data.OpenApi.Declare
15−import Data.OpenApi.Lens
16−import Data.OpenApi.Operation
13+import Data.Swagger
14+import Data.Swagger.Declare
15+import Data.Swagger.Lens
16+import Data.Swagger.Operation
1717
1818type Username = Text
1919
@@ -27,7 +27,7 @@ instance ToSchema UserSummary where
2727 usernameSchema <- declareSchemaRef (Proxy :: Proxy Username)
2828 useridSchema <- declareSchemaRef (Proxy :: Proxy Int)
2929 return $ NamedSchema (Just "UserSummary") $ mempty
30− & type_ ?~ OpenApiObject
30+ & type_ ?~ SwaggerObject
3131 & properties .~
3232 [ ("summaryUsername", usernameSchema )
3333 , ("summaryUserid" , useridSchema )
@@ -47,13 +47,13 @@ data UserDetailed = UserDetailed
4747newtype Package = Package { packageName :: Text }
4848 deriving (Generic, ToSchema)
4949
50−hackageOpenApi :: OpenApi
51−hackageOpenApi = spec & components.schemas .~ defs
50+hackageSwagger :: Swagger
51+hackageSwagger = spec & components.schemas .~ defs
5252 where
53− (defs, spec) = runDeclare declareHackageOpenApi mempty
53+ (defs, spec) = runDeclare declareHackageSwagger mempty
5454
55−declareHackageOpenApi :: Declare (Definitions Schema) OpenApi
56−declareHackageOpenApi = do
55+declareHackageSwagger :: Declare (Definitions Schema) Swagger
56+declareHackageSwagger = do
5757 -- param schemas
5858 let usernameParamSchema = toParamSchema (Proxy :: Proxy Username)
5959
@@ -78,5 +78,5 @@ declareHackageOpenApi = do
7878 ]
7979
8080main :: IO ()
81−main = putStrLn . read . show . encode $ hackageOpenApi
81+main = putStrLn . read . show . encode $ hackageSwagger
8282
openapi3.cabal+40−44
@@ -1,9 +1,9 @@
11cabal-version: >=1.10
22name: openapi3
3−version: 3.2.2
3+version: 3.0.0
44
55synopsis: OpenAPI 3.0 data model
6−category: Web, Swagger, OpenApi
6+category: Web, Swagger
77description:
88 This library is intended to be used for decoding and encoding OpenAPI 3.0 API
99 specifications as well as manipulating them.
@@ -25,10 +25,8 @@ extra-source-files:
2525tested-with:
2626 GHC ==8.4.4
2727 || ==8.6.5
28− || ==8.8.4
29− || ==8.10.7
30− || ==9.0.2
31− || ==9.2.2
28+ || ==8.8.3
29+ || ==8.10.1
3230
3331custom-setup
3432 setup-depends:
@@ -37,56 +35,54 @@ custom-setup
3735library
3836 hs-source-dirs: src
3937 exposed-modules:
40− Data.OpenApi
41− Data.OpenApi.Declare
42− Data.OpenApi.Lens
43− Data.OpenApi.Operation
44− Data.OpenApi.Optics
45− Data.OpenApi.ParamSchema
46− Data.OpenApi.Schema
47− Data.OpenApi.Schema.Generator
48− Data.OpenApi.Schema.Validation
49− Data.OpenApi.SchemaOptions
38+ Data.Swagger
39+ Data.Swagger.Declare
40+ Data.Swagger.Lens
41+ Data.Swagger.Operation
42+ Data.Swagger.Optics
43+ Data.Swagger.ParamSchema
44+ Data.Swagger.Schema
45+ Data.Swagger.Schema.Generator
46+ Data.Swagger.Schema.Validation
47+ Data.Swagger.SchemaOptions
5048
5149 -- internal modules
52− Data.OpenApi.Internal
53− Data.OpenApi.Internal.Schema
54− Data.OpenApi.Internal.Schema.Validation
55− Data.OpenApi.Internal.ParamSchema
56− Data.OpenApi.Internal.Utils
57− Data.OpenApi.Internal.AesonUtils
58− Data.OpenApi.Internal.TypeShape
59−
60− Data.OpenApi.Aeson.Compat
50+ Data.Swagger.Internal
51+ Data.Swagger.Internal.Schema
52+ Data.Swagger.Internal.Schema.Validation
53+ Data.Swagger.Internal.ParamSchema
54+ Data.Swagger.Internal.Utils
55+ Data.Swagger.Internal.AesonUtils
56+ Data.Swagger.Internal.TypeShape
6157
6258 -- GHC boot libraries
6359 build-depends:
64− base >=4.11.1.0 && <4.17
65− , bytestring >=0.10.8.2 && <0.12
60+ base >=4.11.1.0 && <4.15
61+ , bytestring >=0.10.8.2 && <0.11
6662 , containers >=0.5.11.0 && <0.7
67− , template-haskell >=2.13.0.0 && <2.19
68− , time >=1.8.0.2 && <1.14
63+ , template-haskell >=2.13.0.0 && <2.17
64+ , time >=1.8.0.2 && <1.10
6965 , transformers >=0.5.5.0 && <0.6
7066
7167 build-depends:
7268 mtl >=2.2.2 && <2.3
73− , text >=1.2.3.1 && <2.1
69+ , text >=1.2.3.1 && <1.3
7470
7571 -- other dependencies
7672 build-depends:
77− base-compat-batteries >=0.11.1 && <0.13
78− , aeson >=1.4.2.0 && <1.6 || >=2.0.1.0 && < 2.1
73+ base-compat-batteries >=0.11.1 && <0.12
74+ , aeson >=1.4.2.0 && <1.6
7975 , aeson-pretty >=0.8.7 && <0.9
8076 -- cookie 0.4.3 is needed by GHC 7.8 due to time>=1.4 constraint
8177 , cookie >=0.4.3 && <0.5
8278 , generics-sop >=0.5.1.0 && <0.6
83− , hashable >=1.2.7.0 && <1.5
79+ , hashable >=1.2.7.0 && <1.4
8480 , http-media >=0.8.0.0 && <0.9
8581 , insert-ordered-containers >=0.2.3 && <0.3
86− , lens >=4.16.1 && <5.2
82+ , lens >=4.16.1 && <4.20
8783 , network >=2.6.3.5 && <3.2
88− , optics-core >=0.2 && <0.5
89− , optics-th >=0.2 && <0.5
84+ , optics-core >=0.2 && <0.4
85+ , optics-th >=0.2 && <0.4
9086 , scientific >=0.3.6.2 && <0.4
9187 , unordered-containers >=0.2.9.0 && <0.3
9288 , uuid-types >=1.0.3 && <1.1
@@ -122,23 +118,23 @@ test-suite spec
122118
123119 -- test-suite only dependencies
124120 build-depends:
125− hspec >=2.5.5 && <2.10
121+ hspec >=2.5.5 && <2.8
126122 , HUnit >=1.6.0.0 && <1.7
127123 , quickcheck-instances >=0.3.19 && <0.14
128124 , utf8-string >=1.0.1.1 && <1.1
129125
130126 -- https://github.com/haskell/cabal/issues/3708
131127 build-tool-depends:
132− hspec-discover:hspec-discover >=2.5.5 && <2.10
128+ hspec-discover:hspec-discover >=2.5.5 && <2.8
133129
134130 other-modules:
135131 SpecCommon
136− Data.OpenApiSpec
137− Data.OpenApi.CommonTestTypes
138− Data.OpenApi.ParamSchemaSpec
139− Data.OpenApi.SchemaSpec
140− Data.OpenApi.Schema.ValidationSpec
141− Data.OpenApi.Schema.GeneratorSpec
132+ Data.SwaggerSpec
133+ Data.Swagger.CommonTestTypes
134+ Data.Swagger.ParamSchemaSpec
135+ Data.Swagger.SchemaSpec
136+ Data.Swagger.Schema.ValidationSpec
137+ Data.Swagger.Schema.GeneratorSpec
142138 default-language: Haskell2010
143139
144140test-suite doctests
src/Data/OpenApi/Aeson/Compat.hsdeleted−76
@@ -1,76 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−
3−module Data.OpenApi.Aeson.Compat where
4−
5−#if MIN_VERSION_aeson(2,0,0)
6−import Data.Aeson (Key)
7−import qualified Data.Aeson.Key as Key
8−import qualified Data.Aeson.KeyMap as KeyMap
9−#else
10−import qualified Data.HashMap.Strict as HM
11−#endif
12−import Data.Bifunctor (first)
13−import qualified Data.HashMap.Strict.InsOrd as InsOrdHashMap
14−import qualified Data.Text as T
15−
16−#if MIN_VERSION_aeson(2,0,0)
17−deleteKey :: Key -> KeyMap.KeyMap v -> KeyMap.KeyMap v
18−deleteKey = KeyMap.delete
19−
20−objectToList :: KeyMap.KeyMap v -> [(Key, v)]
21−objectToList = KeyMap.toList
22−
23−objectKeys :: KeyMap.KeyMap v -> [T.Text]
24−objectKeys = map Key.toText . KeyMap.keys
25−
26−stringToKey :: String -> Key
27−stringToKey = Key.fromString
28−
29−keyToString :: Key -> String
30−keyToString = Key.toString
31−
32−keyToText :: Key -> T.Text
33−keyToText = Key.toText
34−
35−toInsOrdHashMap :: KeyMap.KeyMap v -> InsOrdHashMap.InsOrdHashMap T.Text v
36−toInsOrdHashMap = InsOrdHashMap.fromList . fmap (first Key.toText) . KeyMap.toList
37−
38−fromInsOrdHashMap :: InsOrdHashMap.InsOrdHashMap T.Text v -> KeyMap.KeyMap v
39−fromInsOrdHashMap = KeyMap.fromList . fmap (first Key.fromText) . InsOrdHashMap.toList
40−
41−lookupKey :: T.Text -> KeyMap.KeyMap v -> Maybe v
42−lookupKey = KeyMap.lookup . Key.fromText
43−
44−hasKey :: T.Text -> KeyMap.KeyMap a -> Bool
45−hasKey = KeyMap.member . Key.fromText
46−#else
47−deleteKey :: T.Text -> HM.HashMap T.Text v -> HM.HashMap T.Text v
48−deleteKey = HM.delete
49−
50−objectToList :: HM.HashMap T.Text v -> [(T.Text, v)]
51−objectToList = HM.toList
52−
53−objectKeys :: HM.HashMap T.Text v -> [T.Text]
54−objectKeys = HM.keys
55−
56−stringToKey :: String -> T.Text
57−stringToKey = T.pack
58−
59−keyToString :: T.Text -> String
60−keyToString = T.unpack
61−
62−keyToText :: T.Text -> T.Text
63−keyToText = id
64−
65−toInsOrdHashMap :: HM.HashMap T.Text v -> InsOrdHashMap.InsOrdHashMap T.Text v
66−toInsOrdHashMap = InsOrdHashMap.fromHashMap
67−
68−fromInsOrdHashMap :: InsOrdHashMap.InsOrdHashMap T.Text v -> HM.HashMap T.Text v
69−fromInsOrdHashMap = InsOrdHashMap.toHashMap
70−
71−lookupKey :: T.Text -> HM.HashMap T.Text v -> Maybe v
72−lookupKey = HM.lookup
73−
74−hasKey :: T.Text -> HM.HashMap T.Text a -> Bool
75−hasKey = HM.member
76−#endif
src/Data/OpenApi.hs → src/Data/Swagger.hsrenamed+47−168
@@ -1,5 +1,5 @@
11-- |
2−-- Module: Data.OpenApi
2+-- Module: Data.Swagger
33-- Maintainer: Nickolay Kudasov <nickolay@getshoptv.com>
44-- Stability: experimental
55--
@@ -9,7 +9,7 @@
99-- These files can then be used by the Swagger-UI project to display the API
1010-- and Swagger-Codegen to generate clients in various languages.
1111-- Additional utilities can also take advantage of the resulting files, such as testing tools.
12−module Data.OpenApi (
12+module Data.Swagger (
1313 -- * How to use this library
1414 -- $howto
1515
@@ -29,15 +29,15 @@ module Data.OpenApi (
2929 -- $validation
3030
3131 -- * Re-exports
32− module Data.OpenApi.Lens,
33− module Data.OpenApi.Optics,
34− module Data.OpenApi.Operation,
35− module Data.OpenApi.ParamSchema,
36− module Data.OpenApi.Schema,
37− module Data.OpenApi.Schema.Validation,
32+ module Data.Swagger.Lens,
33+ module Data.Swagger.Optics,
34+ module Data.Swagger.Operation,
35+ module Data.Swagger.ParamSchema,
36+ module Data.Swagger.Schema,
37+ module Data.Swagger.Schema.Validation,
3838
3939 -- * Swagger specification
40− OpenApi(..),
40+ Swagger(..),
4141 Server(..),
4242 ServerVariable(..),
4343 Components(..),
@@ -56,7 +56,7 @@ module Data.OpenApi (
5656 TagName,
5757
5858 -- ** Types and formats
59− OpenApiType(..),
59+ SwaggerType(..),
6060 Format,
6161 Definitions,
6262 Style(..),
@@ -75,7 +75,7 @@ module Data.OpenApi (
7575 -- ** Schemas
7676 Schema(..),
7777 NamedSchema(..),
78− OpenApiItems(..),
78+ SwaggerItems(..),
7979 Xml(..),
8080 Pattern,
8181 AdditionalProperties(..),
@@ -91,7 +91,6 @@ module Data.OpenApi (
9191 -- ** Security
9292 SecurityScheme(..),
9393 SecuritySchemeType(..),
94− HttpSchemeType(..),
9594 SecurityDefinitions(..),
9695 SecurityRequirement(..),
9796
@@ -121,14 +120,14 @@ module Data.OpenApi (
121120 URL(..),
122121) where
123122
124−import Data.OpenApi.Lens
125−import Data.OpenApi.Optics ()
126−import Data.OpenApi.Operation
127−import Data.OpenApi.ParamSchema
128−import Data.OpenApi.Schema
129−import Data.OpenApi.Schema.Validation
123+import Data.Swagger.Lens
124+import Data.Swagger.Optics ()
125+import Data.Swagger.Operation
126+import Data.Swagger.ParamSchema
127+import Data.Swagger.Schema
128+import Data.Swagger.Schema.Validation
130129
131−import Data.OpenApi.Internal
130+import Data.Swagger.Internal
132131
133132-- $setup
134133-- >>> import Control.Lens
@@ -137,7 +136,6 @@ import Data.OpenApi.Internal
137136-- >>> import Data.Proxy
138137-- >>> import GHC.Generics
139138-- >>> import qualified Data.ByteString.Lazy.Char8 as BSL
140−-- >>> import Data.OpenApi.Internal.Utils
141139-- >>> :set -XDeriveGeneric
142140-- >>> :set -XOverloadedStrings
143141-- >>> :set -XOverloadedLists
@@ -154,16 +152,8 @@ import Data.OpenApi.Internal
154152--
155153-- In this library you can use @'mempty'@ for a default/empty value. For instance:
156154--
157−-- >>> BSL.putStrLn $ encodePretty (mempty :: OpenApi)
158−-- {
159−-- "components": {},
160−-- "info": {
161−-- "title": "",
162−-- "version": ""
163−-- },
164−-- "openapi": "3.0.0",
165−-- "paths": {}
166−-- }
155+-- >>> BSL.putStrLn $ encode (mempty :: Swagger)
156+-- {"openapi":"3.0.0","info":{"version":"","title":""},"components":{}}
167157--
168158-- As you can see some spec properties (e.g. @"version"@) are there even when the spec is empty.
169159-- That is because these properties are actually required ones.
@@ -171,87 +161,46 @@ import Data.OpenApi.Internal
171161-- You /should/ always override the default (empty) value for these properties,
172162-- although it is not strictly necessary:
173163--
174−-- >>> BSL.putStrLn $ encodePretty mempty { _infoTitle = "Todo API", _infoVersion = "1.0" }
175−-- {
176−-- "title": "Todo API",
177−-- "version": "1.0"
178−-- }
164+-- >>> BSL.putStrLn $ encode mempty { _infoTitle = "Todo API", _infoVersion = "1.0" }
165+-- {"version":"1.0","title":"Todo API"}
179166--
180167-- You can merge two values using @'mappend'@ or its infix version @('<>')@:
181168--
182−-- >>> BSL.putStrLn $ encodePretty $ mempty { _infoTitle = "Todo API" } <> mempty { _infoVersion = "1.0" }
183−-- {
184−-- "title": "Todo API",
185−-- "version": "1.0"
186−-- }
187−
169+-- >>> BSL.putStrLn $ encode $ mempty { _infoTitle = "Todo API" } <> mempty { _infoVersion = "1.0" }
170+-- {"version":"1.0","title":"Todo API"}
188171--
189172-- This can be useful for combining specifications of endpoints into a whole API specification:
190173--
191174-- @
192175-- \-\- /account subAPI specification
193−-- accountAPI :: OpenApi
176+-- accountAPI :: Swagger
194177--
195178-- \-\- /task subAPI specification
196−-- taskAPI :: OpenApi
179+-- taskAPI :: Swagger
197180--
198181-- \-\- while API specification is just a combination
199182-- \-\- of subAPIs' specifications
200−-- api :: OpenApi
183+-- api :: Swagger
201184-- api = accountAPI <> taskAPI
202185-- @
203186
204187-- $lens
205188--
206−-- Note: if you're working with the <https://hackage.haskell.org/package/optics optics> library, take a look at "Data.OpenApi.Optics".
189+-- Note: if you're working with the <https://hackage.haskell.org/package/optics optics> library, take a look at "Data.Swagger.Optics".
207190--
208191-- Since @'Swagger'@ has a fairly complex structure, lenses and prisms are used
209192-- to work comfortably with it. In combination with @'Monoid'@ instances, lenses
210193-- make it fairly simple to construct/modify any part of the specification:
211194--
212195-- >>> :{
213−-- BSL.putStrLn $ encodePretty $ (mempty :: OpenApi)
214−-- & components . schemas .~ [ ("User", mempty & type_ ?~ OpenApiString) ]
196+-- BSL.putStrLn $ encode $ (mempty :: Swagger)
197+-- & components . schemas .~ [ ("User", mempty & type_ ?~ SwaggerString) ]
215198-- & paths .~
216199-- [ ("/user", mempty & get ?~ (mempty
217200-- & at 200 ?~ ("OK" & _Inline.content.at "application/json" ?~ (mempty & schema ?~ Ref (Reference "User")))
218201-- & at 404 ?~ "User info not found")) ]
219202-- :}
220−-- {
221−-- "components": {
222−-- "schemas": {
223−-- "User": {
224−-- "type": "string"
225−-- }
226−-- }
227−-- },
228−-- "info": {
229−-- "title": "",
230−-- "version": ""
231−-- },
232−-- "openapi": "3.0.0",
233−-- "paths": {
234−-- "/user": {
235−-- "get": {
236−-- "responses": {
237−-- "200": {
238−-- "content": {
239−-- "application/json": {
240−-- "schema": {
241−-- "$ref": "#/components/schemas/User"
242−-- }
243−-- }
244−-- },
245−-- "description": "OK"
246−-- },
247−-- "404": {
248−-- "description": "User info not found"
249−-- }
250−-- }
251−-- }
252−-- }
253−-- }
254−-- }
203+-- {"openapi":"3.0.0","info":{"version":"","title":""},"paths":{"/user":{"get":{"responses":{"404":{"description":"User info not found"},"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/User"}}},"description":"OK"}}}}},"components":{"schemas":{"User":{"type":"string"}}}}
255204--
256205-- In the snippet above we declare an API with a single path @/user@. This path provides method @GET@
257206-- which produces @application/json@ output. It should respond with code @200@ and body specified
@@ -263,34 +212,23 @@ import Data.OpenApi.Internal
263212-- common field is @'description'@. Many components of a Swagger specification
264213-- can have descriptions, and you can use the same name for them:
265214--
266−-- >>> BSL.putStrLn $ encodePretty $ (mempty :: Response) & description .~ "No content"
267−-- {
268−-- "description": "No content"
269−-- }
215+-- >>> BSL.putStrLn $ encode $ (mempty :: Response) & description .~ "No content"
216+-- {"description":"No content"}
270217-- >>> :{
271−-- BSL.putStrLn $ encodePretty $ (mempty :: Schema)
272−-- & type_ ?~ OpenApiBoolean
218+-- BSL.putStrLn $ encode $ (mempty :: Schema)
219+-- & type_ ?~ SwaggerBoolean
273220-- & description ?~ "To be or not to be"
274221-- :}
275−-- {
276−-- "description": "To be or not to be",
277−-- "type": "boolean"
278−-- }
222+-- {"type":"boolean","description":"To be or not to be"}
279223--
280224-- Additionally, to simplify working with @'Response'@, both @'Operation'@ and @'Responses'@
281225-- have direct access to it via @'at' code@. Example:
282226--
283227-- >>> :{
284−-- BSL.putStrLn $ encodePretty $ (mempty :: Operation)
228+-- BSL.putStrLn $ encode $ (mempty :: Operation)
285229-- & at 404 ?~ "Not found"
286230-- :}
287−-- {
288−-- "responses": {
289−-- "404": {
290−-- "description": "Not found"
291−-- }
292−-- }
293−-- }
231+-- {"responses":{"404":{"description":"Not found"}}}
294232--
295233-- You might've noticed that @'type_'@ has an extra underscore in its name
296234-- compared to, say, @'description'@ field accessor.
@@ -306,7 +244,7 @@ import Data.OpenApi.Internal
306244-- @'ParamSchema'@ and @'Schema'@ are the two core types for data model specification.
307245--
308246-- @'ParamSchema' t@ specifies all the common properties, available for every data schema.
309−-- The @t@ parameter imposes some restrictions on @type@ and @items@ properties (see @'OpenApiType'@ and @'OpenApiItems'@).
247+-- The @t@ parameter imposes some restrictions on @type@ and @items@ properties (see @'SwaggerType'@ and @'SwaggerItems'@).
310248--
311249-- @'Schema'@ is used for request and response bodies and allows specifying objects
312250-- with properties in addition to what @'ParamSchema'@ provides.
@@ -337,27 +275,10 @@ import Data.OpenApi.Internal
337275-- >>> data Person = Person { name :: String, age :: Integer } deriving Generic
338276-- >>> instance ToJSON Person
339277-- >>> instance ToSchema Person
340−-- >>> BSL.putStrLn $ encodePretty (Person "David" 28)
341−-- {
342−-- "age": 28,
343−-- "name": "David"
344−-- }
345−-- >>> BSL.putStrLn $ encodePretty $ toSchema (Proxy :: Proxy Person)
346−-- {
347−-- "properties": {
348−-- "age": {
349−-- "type": "integer"
350−-- },
351−-- "name": {
352−-- "type": "string"
353−-- }
354−-- },
355−-- "required": [
356−-- "name",
357−-- "age"
358−-- ],
359−-- "type": "object"
360−-- }
278+-- >>> BSL.putStrLn $ encode (Person "David" 28)
279+-- {"age":28,"name":"David"}
280+-- >>> BSL.putStrLn $ encode $ toSchema (Proxy :: Proxy Person)
281+-- {"required":["name","age"],"type":"object","properties":{"age":{"type":"integer"},"name":{"type":"string"}}}
361282--
362283-- This package implements OpenAPI 3.0 spec, which supports @oneOf@ in schemas, allowing any sum types
363284-- to be faithfully represented. All sum encodings supported by @aeson@ are supported here as well, with
@@ -368,50 +289,8 @@ import Data.OpenApi.Internal
368289-- >>> data Error = ErrorNoUser { userId :: Int } | ErrorAccessDenied { requiredPermission :: String } deriving Generic
369290-- >>> instance ToJSON Error
370291-- >>> instance ToSchema Error
371−-- >>> BSL.putStrLn $ encodePretty $ toSchema (Proxy :: Proxy Error)
372−-- {
373−-- "oneOf": [
374−-- {
375−-- "properties": {
376−-- "tag": {
377−-- "enum": [
378−-- "ErrorNoUser"
379−-- ],
380−-- "type": "string"
381−-- },
382−-- "userId": {
383−-- "maximum": 9223372036854775807,
384−-- "minimum": -9223372036854775808,
385−-- "type": "integer"
386−-- }
387−-- },
388−-- "required": [
389−-- "userId",
390−-- "tag"
391−-- ],
392−-- "type": "object"
393−-- },
394−-- {
395−-- "properties": {
396−-- "requiredPermission": {
397−-- "type": "string"
398−-- },
399−-- "tag": {
400−-- "enum": [
401−-- "ErrorAccessDenied"
402−-- ],
403−-- "type": "string"
404−-- }
405−-- },
406−-- "required": [
407−-- "requiredPermission",
408−-- "tag"
409−-- ],
410−-- "type": "object"
411−-- }
412−-- ],
413−-- "type": "object"
414−-- }
292+-- >>> BSL.putStrLn $ encode $ toSchema (Proxy :: Proxy Error)
293+-- {"oneOf":[{"required":["userId","tag"],"type":"object","properties":{"tag":{"type":"string","enum":["ErrorNoUser"]},"userId":{"maximum":9223372036854775807,"minimum":-9223372036854775808,"type":"integer"}}},{"required":["requiredPermission","tag"],"type":"object","properties":{"tag":{"type":"string","enum":["ErrorAccessDenied"]},"requiredPermission":{"type":"string"}}}],"type":"object"}
415294
416295-- $manipulation
417296-- Sometimes you have to work with an imported or generated @'Swagger'@.
@@ -419,10 +298,10 @@ import Data.OpenApi.Internal
419298-- for a type-level servant API.
420299--
421300-- Lenses and prisms can be used to manipulate such specification to add additional information, tags, extra responses, etc.
422−-- To facilitate common needs, @"Data.OpenApi.Operation"@ module provides useful helpers.
301+-- To facilitate common needs, @"Data.Swagger.Operation"@ module provides useful helpers.
423302
424303-- $validation
425304-- While @'ToParamSchema'@ and @'ToSchema'@ provide means to easily obtain schemas for Haskell types,
426305-- there is no static mechanism to ensure those instances correspond to the @'ToHttpApiData'@ or @'ToJSON'@ instances.
427306--
428−-- @"Data.OpenApi.Schema.Validation"@ addresses @'ToJSON'@/@'ToSchema'@ validation.
307+-- @"Data.Swagger.Schema.Validation"@ addresses @'ToJSON'@/@'ToSchema'@ validation.
src/Data/OpenApi/Declare.hs → src/Data/Swagger/Declare.hsrenamed+2−2
@@ -4,12 +4,12 @@
44{-# LANGUAGE MultiParamTypeClasses #-}
55{-# LANGUAGE UndecidableInstances #-}
66-- |
7−-- Module: Data.OpenApi.Declare
7+-- Module: Data.Swagger.Declare
88-- Maintainer: Nickolay Kudasov <nickolay@getshoptv.com>
99-- Stability: experimental
1010--
1111-- Declare monad transformer and associated functions.
12−module Data.OpenApi.Declare where
12+module Data.Swagger.Declare where
1313
1414import Prelude ()
1515import Prelude.Compat
src/Data/OpenApi/Internal.hs → src/Data/Swagger/Internal.hsrenamed+81−147
@@ -1,6 +1,6 @@
1−{-# LANGUAGE CPP #-}
21{-# LANGUAGE DataKinds #-}
32{-# LANGUAGE DeriveDataTypeable #-}
3+{-# LANGUAGE DeriveFunctor #-}
44{-# LANGUAGE DeriveGeneric #-}
55{-# LANGUAGE DeriveTraversable #-}
66{-# LANGUAGE FlexibleContexts #-}
@@ -14,7 +14,7 @@
1414{-# LANGUAGE TemplateHaskell #-}
1515{-# LANGUAGE TypeFamilies #-}
1616{-# LANGUAGE UndecidableInstances #-}
17−module Data.OpenApi.Internal where
17+module Data.Swagger.Internal where
1818
1919import Prelude ()
2020import Prelude.Compat
@@ -22,9 +22,6 @@ import Prelude.Compat
2222import Control.Applicative
2323import Control.Lens ((&), (.~), (?~))
2424import Data.Aeson hiding (Encoding)
25−#if MIN_VERSION_aeson(2,0,0)
26−import qualified Data.Aeson.KeyMap as KeyMap
27−#endif
2825import qualified Data.Aeson.Types as JSON
2926import Data.Data (Constr, Data (..), DataType, Fixity (..), Typeable,
3027 constrIndex, mkConstr, mkDataType)
@@ -49,56 +46,58 @@ import Text.Read (readMaybe)
4946import Data.HashMap.Strict.InsOrd (InsOrdHashMap)
5047import qualified Data.HashMap.Strict.InsOrd as InsOrdHashMap
5148
52−import Data.OpenApi.Aeson.Compat (deleteKey)
53−import Data.OpenApi.Internal.AesonUtils (AesonDefaultValue (..), HasSwaggerAesonOptions (..),
54− mkSwaggerAesonOptions, saoAdditionalPairs, saoSubObject,
55− sopSwaggerGenericParseJSON, sopSwaggerGenericToEncoding,
56− sopSwaggerGenericToJSON, sopSwaggerGenericToJSONWithOpts)
57−import Data.OpenApi.Internal.Utils
5849import Generics.SOP.TH (deriveGeneric)
50+import Data.Swagger.Internal.AesonUtils (sopSwaggerGenericToJSON
51+ ,sopSwaggerGenericToJSONWithOpts
52+ ,sopSwaggerGenericParseJSON
53+ ,HasSwaggerAesonOptions(..)
54+ ,AesonDefaultValue(..)
55+ ,mkSwaggerAesonOptions
56+ ,saoAdditionalPairs
57+ ,saoSubObject)
58+import Data.Swagger.Internal.Utils
59+import Data.Swagger.Internal.AesonUtils (sopSwaggerGenericToEncoding)
5960
6061-- $setup
6162-- >>> :seti -XDataKinds
6263-- >>> import Data.Aeson
63−-- >>> import Data.ByteString.Lazy.Char8 as BSL
64−-- >>> import Data.OpenApi.Internal.Utils
6564
6665-- | A list of definitions that can be used in references.
6766type Definitions = InsOrdHashMap Text
6867
6968-- | This is the root document object for the API specification.
70−data OpenApi = OpenApi
69+data Swagger = Swagger
7170 { -- | Provides metadata about the API.
7271 -- The metadata can be used by the clients if needed.
73− _openApiInfo :: Info
72+ _swaggerInfo :: Info
7473
7574 -- | An array of Server Objects, which provide connectivity information
7675 -- to a target server. If the servers property is not provided, or is an empty array,
7776 -- the default value would be a 'Server' object with a url value of @/@.
78− , _openApiServers :: [Server]
77+ , _swaggerServers :: [Server]
7978
8079 -- | The available paths and operations for the API.
81− , _openApiPaths :: InsOrdHashMap FilePath PathItem
80+ , _swaggerPaths :: InsOrdHashMap FilePath PathItem
8281
8382 -- | An element to hold various schemas for the specification.
84− , _openApiComponents :: Components
83+ , _swaggerComponents :: Components
8584
8685 -- | A declaration of which security mechanisms can be used across the API.
8786 -- The list of values includes alternative security requirement objects that can be used.
8887 -- Only one of the security requirement objects need to be satisfied to authorize a request.
8988 -- Individual operations can override this definition.
9089 -- To make security optional, an empty security requirement can be included in the array.
91− , _openApiSecurity :: [SecurityRequirement]
90+ , _swaggerSecurity :: [SecurityRequirement]
9291
9392 -- | A list of tags used by the specification with additional metadata.
9493 -- The order of the tags can be used to reflect on their order by the parsing tools.
9594 -- Not all tags that are used by the 'Operation' Object must be declared.
9695 -- The tags that are not declared MAY be organized randomly or based on the tools' logic.
9796 -- Each tag name in the list MUST be unique.
98− , _openApiTags :: InsOrdHashSet Tag
97+ , _swaggerTags :: InsOrdHashSet Tag
9998
10099 -- | Additional external documentation.
101− , _openApiExternalDocs :: Maybe ExternalDocs
100+ , _swaggerExternalDocs :: Maybe ExternalDocs
102101 } deriving (Eq, Show, Generic, Data, Typeable)
103102
104103-- | The object provides metadata about the API.
@@ -196,7 +195,7 @@ data Components = Components
196195 , _componentsExamples :: Definitions Example
197196 , _componentsRequestBodies :: Definitions RequestBody
198197 , _componentsHeaders :: Definitions Header
199− , _componentsSecuritySchemes :: SecurityDefinitions
198+ , _componentsSecuritySchemes :: Definitions SecurityScheme
200199 , _componentsLinks :: Definitions Link
201200 , _componentsCallbacks :: Definitions Callback
202201 } deriving (Eq, Show, Generic, Data, Typeable)
@@ -337,7 +336,7 @@ data RequestBody = RequestBody
337336 -- | The content of the request body.
338337 -- The key is a media type or media type range and the value describes it.
339338 -- For requests that match multiple keys, only the most specific key is applicable.
340− -- e.g. @text/plain@ overrides @text/\*@
339+ -- e.g. @text/plain@ overrides @text/*@
341340 , _requestBodyContent :: InsOrdHashMap MediaType MediaTypeObject
342341
343342 -- | Determines if the request body is required in the request.
@@ -394,7 +393,7 @@ data Encoding = Encoding
394393 -- for other primitive types – @text/plain@; for object - @application/json@;
395394 -- for array – the default is defined based on the inner type.
396395 -- The value can be a specific media type (e.g. @application/json@),
397− -- a wildcard media type (e.g. @image/\*@), or a comma-separated list of the two types.
396+ -- a wildcard media type (e.g. @image/*@), or a comma-separated list of the two types.
398397 _encodingContentType :: Maybe MediaType
399398
400399 -- | A map allowing additional information to be provided as headers,
@@ -434,11 +433,11 @@ mimeListConstr :: Constr
434433mimeListConstr = mkConstr mimeListDataType "MimeList" ["getMimeList"] Prefix
435434
436435mimeListDataType :: DataType
437−mimeListDataType = mkDataType "Data.OpenApi.MimeList" [mimeListConstr]
436+mimeListDataType = mkDataType "Data.Swagger.MimeList" [mimeListConstr]
438437
439438instance Data MimeList where
440439 gunfold k z c = case constrIndex c of
441− 1 -> k (z (MimeList . map fromString))
440+ 1 -> k (z (\xs -> MimeList (map fromString xs)))
442441 _ -> error $ "Data.Data.gunfold: Constructor " ++ show c ++ " is not of type MimeList."
443442 toConstr (MimeList _) = mimeListConstr
444443 dataTypeOf _ = mimeListDataType
@@ -573,27 +572,27 @@ data Link = Link
573572 , _linkServer :: Maybe Server
574573 } deriving (Eq, Show, Generic, Typeable, Data)
575574
576−-- | Items for @'OpenApiArray'@ schemas.
575+-- | Items for @'SwaggerArray'@ schemas.
577576--
578577-- __Warning__: OpenAPI 3.0 does not support tuple arrays. However, OpenAPI 3.1 will, as
579578-- it will incorporate Json Schema mostly verbatim.
580579--
581−-- @'OpenApiItemsObject'@ should be used to specify homogenous array @'Schema'@s.
580+-- @'SwaggerItemsObject'@ should be used to specify homogenous array @'Schema'@s.
582581--
583−-- @'OpenApiItemsArray'@ should be used to specify tuple @'Schema'@s.
584−data OpenApiItems where
585− OpenApiItemsObject :: Referenced Schema -> OpenApiItems
586− OpenApiItemsArray :: [Referenced Schema] -> OpenApiItems
582+-- @'SwaggerItemsArray'@ should be used to specify tuple @'Schema'@s.
583+data SwaggerItems where
584+ SwaggerItemsObject :: Referenced Schema -> SwaggerItems
585+ SwaggerItemsArray :: [Referenced Schema] -> SwaggerItems
587586 deriving (Eq, Show, Typeable, Data)
588587
589−data OpenApiType where
590− OpenApiString :: OpenApiType
591− OpenApiNumber :: OpenApiType
592− OpenApiInteger :: OpenApiType
593− OpenApiBoolean :: OpenApiType
594− OpenApiArray :: OpenApiType
595− OpenApiNull :: OpenApiType
596− OpenApiObject :: OpenApiType
588+data SwaggerType where
589+ SwaggerString :: SwaggerType
590+ SwaggerNumber :: SwaggerType
591+ SwaggerInteger :: SwaggerType
592+ SwaggerBoolean :: SwaggerType
593+ SwaggerArray :: SwaggerType
594+ SwaggerNull :: SwaggerType
595+ SwaggerObject :: SwaggerType
597596 deriving (Eq, Show, Typeable, Generic, Data)
598597
599598data ParamLocation
@@ -645,9 +644,9 @@ data Schema = Schema
645644 -- Unlike JSON Schema this value MUST conform to the defined type for this parameter.
646645 _schemaDefault :: Maybe Value
647646
648− , _schemaType :: Maybe OpenApiType
647+ , _schemaType :: Maybe SwaggerType
649648 , _schemaFormat :: Maybe Format
650− , _schemaItems :: Maybe OpenApiItems
649+ , _schemaItems :: Maybe SwaggerItems
651650 , _schemaMaximum :: Maybe Scientific
652651 , _schemaExclusiveMaximum :: Maybe Bool
653652 , _schemaMinimum :: Maybe Scientific
@@ -682,7 +681,7 @@ data NamedSchema = NamedSchema
682681
683682data Xml = Xml
684683 { -- | Replaces the name of the element/attribute used for the described schema property.
685− -- When defined within the @'OpenApiItems'@ (items), it will affect the name of the individual XML elements within the list.
684+ -- When defined within the @'SwaggerItems'@ (items), it will affect the name of the individual XML elements within the list.
686685 -- When defined alongside type being array (outside the items),
687686 -- it will affect the wrapping element and only if wrapped is true.
688687 -- If wrapped is false, it will be ignored.
@@ -734,7 +733,7 @@ data Response = Response
734733 -- | A map containing descriptions of potential response payloads.
735734 -- The key is a media type or media type range and the value describes it.
736735 -- For responses that match multiple keys, only the most specific key is applicable.
737− -- e.g. @text/plain@ overrides @text/\*@.
736+ -- e.g. @text/plain@ overrides @text/*@.
738737 , _responseContent :: InsOrdHashMap MediaType MediaTypeObject
739738
740739 -- | Maps a header name to its definition.
@@ -797,17 +796,17 @@ type AuthorizationURL = Text
797796-- | The token URL to be used for OAuth2 flow. This SHOULD be in the form of a URL.
798797type TokenURL = Text
799798
800−newtype OAuth2ImplicitFlow
801− = OAuth2ImplicitFlow {_oAuth2ImplicitFlowAuthorizationUrl :: AuthorizationURL}
802− deriving (Eq, Show, Generic, Data, Typeable)
799+data OAuth2ImplicitFlow = OAuth2ImplicitFlow
800+ { _oAuth2ImplicitFlowAuthorizationUrl :: AuthorizationURL
801+ } deriving (Eq, Show, Generic, Data, Typeable)
803802
804−newtype OAuth2PasswordFlow
805− = OAuth2PasswordFlow {_oAuth2PasswordFlowTokenUrl :: TokenURL}
806− deriving (Eq, Show, Generic, Data, Typeable)
803+data OAuth2PasswordFlow = OAuth2PasswordFlow
804+ { _oAuth2PasswordFlowTokenUrl :: TokenURL
805+ } deriving (Eq, Show, Generic, Data, Typeable)
807806
808−newtype OAuth2ClientCredentialsFlow
809− = OAuth2ClientCredentialsFlow {_oAuth2ClientCredentialsFlowTokenUrl :: TokenURL}
810− deriving (Eq, Show, Generic, Data, Typeable)
807+data OAuth2ClientCredentialsFlow = OAuth2ClientCredentialsFlow
808+ { _oAuth2ClientCredentialsFlowTokenUrl :: TokenURL
809+ } deriving (Eq, Show, Generic, Data, Typeable)
811810
812811data OAuth2AuthorizationCodeFlow = OAuth2AuthorizationCodeFlow
813812 { _oAuth2AuthorizationCodeFlowAuthorizationUrl :: AuthorizationURL
@@ -840,50 +839,8 @@ data OAuth2Flows = OAuth2Flows
840839 , _oAuth2FlowsAuthorizationCode :: Maybe (OAuth2Flow OAuth2AuthorizationCodeFlow)
841840 } deriving (Eq, Show, Generic, Data, Typeable)
842841
843−type BearerFormat = Text
844−
845−data HttpSchemeType
846− = HttpSchemeBearer (Maybe BearerFormat)
847− | HttpSchemeBasic
848− | HttpSchemeCustom Text
849− deriving (Eq, Show, Generic, Data, Typeable)
850−
851−-- |
852−--
853−-- >>> BSL.putStrLn $ encodePretty (SecuritySchemeHttp (HttpSchemeBearer Nothing))
854−-- {
855−-- "scheme": "bearer",
856−-- "type": "http"
857−-- }
858−--
859−-- >>> BSL.putStrLn $ encodePretty (SecuritySchemeHttp (HttpSchemeBearer (Just "jwt")))
860−-- {
861−-- "bearerFormat": "jwt",
862−-- "scheme": "bearer",
863−-- "type": "http"
864−-- }
865−--
866−-- >>> BSL.putStrLn $ encodePretty (SecuritySchemeHttp HttpSchemeBasic)
867−-- {
868−-- "scheme": "basic",
869−-- "type": "http"
870−-- }
871−--
872−-- >>> BSL.putStrLn $ encodePretty (SecuritySchemeHttp (HttpSchemeCustom "CANARY"))
873−-- {
874−-- "scheme": "CANARY",
875−-- "type": "http"
876−-- }
877−--
878−-- >>> BSL.putStrLn $ encodePretty (SecuritySchemeApiKey (ApiKeyParams "id" ApiKeyCookie))
879−-- {
880−-- "in": "cookie",
881−-- "name": "id",
882−-- "type": "apiKey"
883−-- }
884−--
885842data SecuritySchemeType
886− = SecuritySchemeHttp HttpSchemeType
843+ = SecuritySchemeHttp
887844 | SecuritySchemeApiKey ApiKeyParams
888845 | SecuritySchemeOAuth2 OAuth2Flows
889846 | SecuritySchemeOpenIdConnect URL
@@ -980,7 +937,7 @@ deriveGeneric ''MediaTypeObject
980937deriveGeneric ''Responses
981938deriveGeneric ''SecurityScheme
982939deriveGeneric ''Schema
983−deriveGeneric ''OpenApi
940+deriveGeneric ''Swagger
984941deriveGeneric ''Example
985942deriveGeneric ''Encoding
986943deriveGeneric ''Link
@@ -989,9 +946,9 @@ deriveGeneric ''Link
989946-- Monoid instances
990947-- =======================================================================
991948
992−instance Semigroup OpenApi where
949+instance Semigroup Swagger where
993950 (<>) = genericMappend
994−instance Monoid OpenApi where
951+instance Monoid Swagger where
995952 mempty = genericMempty
996953 mappend = (<>)
997954
@@ -1125,13 +1082,12 @@ instance SwaggerMonoid Response
11251082instance SwaggerMonoid ExternalDocs
11261083instance SwaggerMonoid Operation
11271084instance (Eq a, Hashable a) => SwaggerMonoid (InsOrdHashSet a)
1128−instance SwaggerMonoid SecurityDefinitions
11291085
11301086instance SwaggerMonoid MimeList
11311087deriving instance SwaggerMonoid URL
11321088
1133−instance SwaggerMonoid OpenApiType where
1134− swaggerMempty = OpenApiString
1089+instance SwaggerMonoid SwaggerType where
1090+ swaggerMempty = SwaggerString
11351091 swaggerMappend _ y = y
11361092
11371093instance SwaggerMonoid ParamLocation where
@@ -1154,7 +1110,7 @@ instance Monoid a => SwaggerMonoid (Referenced a) where
11541110instance ToJSON Style where
11551111 toJSON = genericToJSON (jsonPrefix "Style")
11561112
1157−instance ToJSON OpenApiType where
1113+instance ToJSON SwaggerType where
11581114 toJSON = genericToJSON (jsonPrefix "Swagger")
11591115
11601116instance ToJSON ParamLocation where
@@ -1209,7 +1165,7 @@ instance ToJSON OAuth2AuthorizationCodeFlow where
12091165instance FromJSON Style where
12101166 parseJSON = genericParseJSON (jsonPrefix "Style")
12111167
1212−instance FromJSON OpenApiType where
1168+instance FromJSON SwaggerType where
12131169 parseJSON = genericParseJSON (jsonPrefix "Swagger")
12141170
12151171instance FromJSON ParamLocation where
@@ -1274,19 +1230,8 @@ instance ToJSON OAuth2Flows where
12741230 toEncoding = sopSwaggerGenericToEncoding
12751231
12761232instance ToJSON SecuritySchemeType where
1277− toJSON (SecuritySchemeHttp ty) = case ty of
1278− HttpSchemeBearer mFmt ->
1279− object $ [ "type" .= ("http" :: Text)
1280− , "scheme" .= ("bearer" :: Text)
1281− ] <> maybe [] (\t -> ["bearerFormat" .= t]) mFmt
1282− HttpSchemeBasic ->
1283− object [ "type" .= ("http" :: Text)
1284− , "scheme" .= ("basic" :: Text)
1285− ]
1286− HttpSchemeCustom t ->
1287− object [ "type" .= ("http" :: Text)
1288− , "scheme" .= t
1289− ]
1233+ toJSON SecuritySchemeHttp
1234+ = object [ "type" .= ("http" :: Text) ]
12901235 toJSON (SecuritySchemeApiKey params)
12911236 = toJSON params
12921237 <+> object [ "type" .= ("apiKey" :: Text) ]
@@ -1299,9 +1244,9 @@ instance ToJSON SecuritySchemeType where
12991244 , "openIdConnectUrl" .= url
13001245 ]
13011246
1302−instance ToJSON OpenApi where
1247+instance ToJSON Swagger where
13031248 toJSON a = sopSwaggerGenericToJSON a &
1304− if InsOrdHashMap.null (_openApiPaths a)
1249+ if InsOrdHashMap.null (_swaggerPaths a)
13051250 then (<+> object ["paths" .= object []])
13061251 else id
13071252 toEncoding = sopSwaggerGenericToEncoding
@@ -1325,21 +1270,17 @@ instance ToJSON Header where
13251270-- | As for nullary schema for 0-arity type constructors, see
13261271-- <https://github.com/GetShopTV/swagger2/issues/167>.
13271272--
1328−-- >>> BSL.putStrLn $ encodePretty (OpenApiItemsArray [])
1329−-- {
1330−-- "example": [],
1331−-- "items": {},
1332−-- "maxItems": 0
1333−-- }
1273+-- >>> encode (SwaggerItemsArray [])
1274+-- "{\"example\":[],\"items\":{},\"maxItems\":0}"
13341275--
1335−instance ToJSON OpenApiItems where
1336− toJSON (OpenApiItemsObject x) = object [ "items" .= x ]
1337− toJSON (OpenApiItemsArray []) = object
1276+instance ToJSON SwaggerItems where
1277+ toJSON (SwaggerItemsObject x) = object [ "items" .= x ]
1278+ toJSON (SwaggerItemsArray []) = object
13381279 [ "items" .= object []
13391280 , "maxItems" .= (0 :: Int)
13401281 , "example" .= Array mempty
13411282 ]
1342− toJSON (OpenApiItemsArray x) = object [ "items" .= x ]
1283+ toJSON (SwaggerItemsArray x) = object [ "items" .= x ]
13431284
13441285instance ToJSON Components where
13451286 toJSON = sopSwaggerGenericToJSON
@@ -1439,19 +1380,14 @@ instance FromJSON SecuritySchemeType where
14391380 parseJSON js@(Object o) = do
14401381 (t :: Text) <- o .: "type"
14411382 case t of
1442− "http" -> do
1443− scheme <- o .: "scheme"
1444− SecuritySchemeHttp <$> case scheme of
1445− "bearer" -> HttpSchemeBearer <$> (o .:! "bearerFormat")
1446− "basic" -> pure HttpSchemeBasic
1447− t -> pure $ HttpSchemeCustom t
1383+ "http" -> pure SecuritySchemeHttp
14481384 "apiKey" -> SecuritySchemeApiKey <$> parseJSON js
14491385 "oauth2" -> SecuritySchemeOAuth2 <$> (o .: "flows")
14501386 "openIdConnect" -> SecuritySchemeOpenIdConnect <$> (o .: "openIdConnectUrl")
14511387 _ -> empty
14521388 parseJSON _ = empty
14531389
1454−instance FromJSON OpenApi where
1390+instance FromJSON Swagger where
14551391 parseJSON = sopSwaggerGenericParseJSON
14561392
14571393instance FromJSON Server where
@@ -1464,7 +1400,7 @@ instance FromJSON Schema where
14641400 parseJSON = fmap nullaryCleanup . sopSwaggerGenericParseJSON
14651401 where nullaryCleanup :: Schema -> Schema
14661402 nullaryCleanup s =
1467− if _schemaItems s == Just (OpenApiItemsArray [])
1403+ if _schemaItems s == Just (SwaggerItemsArray [])
14681404 then s { _schemaExample = Nothing
14691405 , _schemaMaxItems = Nothing
14701406 }
@@ -1473,18 +1409,18 @@ instance FromJSON Schema where
14731409instance FromJSON Header where
14741410 parseJSON = sopSwaggerGenericParseJSON
14751411
1476−instance FromJSON OpenApiItems where
1412+instance FromJSON SwaggerItems where
14771413 parseJSON js@(Object obj)
1478− | null obj = pure $ OpenApiItemsArray [] -- Nullary schema.
1479− | otherwise = OpenApiItemsObject <$> parseJSON js
1480− parseJSON js@(Array _) = OpenApiItemsArray <$> parseJSON js
1414+ | null obj = pure $ SwaggerItemsArray [] -- Nullary schema.
1415+ | otherwise = SwaggerItemsObject <$> parseJSON js
1416+ parseJSON js@(Array _) = SwaggerItemsArray <$> parseJSON js
14811417 parseJSON _ = empty
14821418
14831419instance FromJSON Components where
14841420 parseJSON = sopSwaggerGenericParseJSON
14851421
14861422instance FromJSON MimeList where
1487− parseJSON js = MimeList . map fromString <$> parseJSON js
1423+ parseJSON js = (MimeList . map fromString) <$> parseJSON js
14881424
14891425instance FromJSON Param where
14901426 parseJSON = sopSwaggerGenericParseJSON
@@ -1492,7 +1428,7 @@ instance FromJSON Param where
14921428instance FromJSON Responses where
14931429 parseJSON (Object o) = Responses
14941430 <$> o .:? "default"
1495− <*> parseJSON (Object (deleteKey "default" o))
1431+ <*> (parseJSON (Object (HashMap.delete "default" o)))
14961432 parseJSON _ = empty
14971433
14981434instance FromJSON Example where
@@ -1591,7 +1527,7 @@ instance HasSwaggerAesonOptions SecurityScheme where
15911527 swaggerAesonOptions _ = mkSwaggerAesonOptions "securityScheme" & saoSubObject ?~ "type"
15921528instance HasSwaggerAesonOptions Schema where
15931529 swaggerAesonOptions _ = mkSwaggerAesonOptions "schema" & saoSubObject ?~ "paramSchema"
1594−instance HasSwaggerAesonOptions OpenApi where
1530+instance HasSwaggerAesonOptions Swagger where
15951531 swaggerAesonOptions _ = mkSwaggerAesonOptions "swagger" & saoAdditionalPairs .~ [("openapi", "3.0.0")]
15961532instance HasSwaggerAesonOptions Example where
15971533 swaggerAesonOptions _ = mkSwaggerAesonOptions "example"
@@ -1610,10 +1546,8 @@ instance AesonDefaultValue OAuth2AuthorizationCodeFlow
16101546instance AesonDefaultValue p => AesonDefaultValue (OAuth2Flow p)
16111547instance AesonDefaultValue Responses
16121548instance AesonDefaultValue SecuritySchemeType
1613−instance AesonDefaultValue OpenApiType
1549+instance AesonDefaultValue SwaggerType
16141550instance AesonDefaultValue MimeList where defaultValue = Just mempty
16151551instance AesonDefaultValue Info
16161552instance AesonDefaultValue ParamLocation
16171553instance AesonDefaultValue Link
1618−instance AesonDefaultValue SecurityDefinitions where
1619− defaultValue = Just mempty
src/Data/OpenApi/Internal/AesonUtils.hs → src/Data/Swagger/Internal/AesonUtils.hsrenamed+13−12
@@ -5,7 +5,7 @@
55{-# LANGUAGE ExplicitForAll #-}
66{-# LANGUAGE TemplateHaskell #-}
77{-# LANGUAGE UndecidableSuperClasses #-}
8−module Data.OpenApi.Internal.AesonUtils (
8+module Data.Swagger.Internal.AesonUtils (
99 -- * Generic functions
1010 AesonDefaultValue(..),
1111 sopSwaggerGenericToJSON,
@@ -27,7 +27,7 @@ import Prelude.Compat
2727import Control.Applicative ((<|>))
2828import Control.Lens (makeLenses, (^.))
2929import Control.Monad (unless)
30−import Data.Aeson (ToJSON(..), FromJSON(..), Value(..), Object, object, (.:), (.:?), (.!=), withObject, Encoding, pairs, (.=), Series)
30+import Data.Aeson (ToJSON(..), FromJSON(..), Value(..), Object, object, (.:), (.:?), (.!=), withObject)
3131import Data.Aeson.Types (Parser, Pair)
3232import Data.Char (toLower, isUpper)
3333import Data.Foldable (traverse_)
@@ -36,11 +36,12 @@ import Data.Text (Text)
3636import Generics.SOP
3737
3838import qualified Data.Text as T
39+import qualified Data.HashMap.Strict as HM
3940import qualified Data.Set as Set
4041import qualified Data.HashMap.Strict.InsOrd as InsOrd
4142import qualified Data.HashSet.InsOrd as InsOrdHS
4243
43−import Data.OpenApi.Aeson.Compat (keyToString, objectToList, stringToKey)
44+import Data.Aeson (Encoding, pairs, (.=), Series)
4445
4546-------------------------------------------------------------------------------
4647-- SwaggerAesonOptions
@@ -48,7 +49,7 @@ import Data.OpenApi.Aeson.Compat (keyToString, objectToList, stringToKey)
4849
4950data SwaggerAesonOptions = SwaggerAesonOptions
5051 { _saoPrefix :: String
51− , _saoAdditionalPairs :: [Pair]
52+ , _saoAdditionalPairs :: [(Text, Value)]
5253 , _saoSubObject :: Maybe String
5354 }
5455
@@ -155,14 +156,14 @@ sopSwaggerGenericToJSON'' (SwaggerAesonOptions prefix _ sub) = go
155156 go Nil Nil Nil = []
156157 go (I x :* xs) (FieldInfo name :* names) (def :* defs)
157158 | Just name' == sub = case json of
158− Object m -> objectToList m ++ rest
159+ Object m -> HM.toList m ++ rest
159160 Null -> rest
160161 _ -> error $ "sopSwaggerGenericToJSON: subjson is not an object: " ++ show json
161162 -- If default value: omit it.
162163 | Just x == def =
163164 rest
164165 | otherwise =
165− (stringToKey name', json) : rest
166+ (T.pack name', json) : rest
166167 where
167168 json = toJSON x
168169 name' = fieldNameModifier name
@@ -196,11 +197,11 @@ sopSwaggerGenericParseJSON = withObject "Swagger Record Object" $ \obj ->
196197 proxy = Proxy :: Proxy a
197198 opts = swaggerAesonOptions proxy
198199
199− parseAdditionalField :: Object -> Pair -> Parser ()
200+ parseAdditionalField :: Object -> (Text, Value) -> Parser ()
200201 parseAdditionalField obj (k, v) = do
201202 v' <- obj .: k
202203 unless (v == v') $ fail $
203− "Additonal field don't match for key " ++ keyToString k
204+ "Additonal field don't match for key " ++ T.unpack k
204205 ++ ": " ++ show v
205206 ++ " /= " ++ show v'
206207
@@ -231,8 +232,8 @@ sopSwaggerGenericParseJSON'' (SwaggerAesonOptions prefix _ sub) obj = go
231232 -- Note: we might strip fields of outer structure.
232233 cons <$> (withDef $ parseJSON $ Object obj) <*> rest
233234 | otherwise = case def of
234− Just def' -> cons <$> obj .:? stringToKey name' .!= def' <*> rest
235− Nothing -> cons <$> obj .: stringToKey name' <*> rest
235+ Just def' -> cons <$> obj .:? T.pack name' .!= def' <*> rest
236+ Nothing -> cons <$> obj .: T.pack name' <*> rest
236237 where
237238 cons h t = I h :* t
238239 name' = fieldNameModifier name
@@ -295,14 +296,14 @@ sopSwaggerGenericToEncoding'' (SwaggerAesonOptions prefix _ sub) = go
295296 go Nil Nil Nil = mempty
296297 go (I x :* xs) (FieldInfo name :* names) (def :* defs)
297298 | Just name' == sub = case toJSON x of
298− Object m -> pairsToSeries (objectToList m) <> rest
299+ Object m -> pairsToSeries (HM.toList m) <> rest
299300 Null -> rest
300301 _ -> error $ "sopSwaggerGenericToJSON: subjson is not an object: " ++ show (toJSON x)
301302 -- If default value: omit it.
302303 | Just x == def =
303304 rest
304305 | otherwise =
305− (stringToKey name' .= x) <> rest
306+ (T.pack name' .= x) <> rest
306307 where
307308 name' = fieldNameModifier name
308309 rest = go xs names defs
src/Data/OpenApi/Internal/ParamSchema.hs → src/Data/Swagger/Internal/ParamSchema.hsrenamed+37−55
@@ -15,7 +15,7 @@
1515{-# OPTIONS_GHC -Wno-redundant-constraints #-}
1616-- For TypeErrors
1717{-# OPTIONS_GHC -Wno-unticked-promoted-constructors #-}
18−module Data.OpenApi.Internal.ParamSchema where
18+module Data.Swagger.Internal.ParamSchema where
1919
2020import Control.Lens
2121import Data.Aeson (ToJSON (..))
@@ -41,31 +41,31 @@ import Data.Word
4141import Data.UUID.Types (UUID)
4242import Web.Cookie (SetCookie)
4343
44−import Data.OpenApi.Internal
45−import Data.OpenApi.Lens
46−import Data.OpenApi.SchemaOptions
44+import Data.Swagger.Internal
45+import Data.Swagger.Lens
46+import Data.Swagger.SchemaOptions
4747
4848import qualified Data.ByteString as BS
49−import qualified Data.ByteString.Lazy.Char8 as BSL
49+import qualified Data.ByteString.Lazy as BSL
5050import GHC.TypeLits (TypeError, ErrorMessage(..))
5151
5252-- | Default schema for binary data (any sequence of octets).
5353binarySchema :: Schema
5454binarySchema = mempty
55− & type_ ?~ OpenApiString
55+ & type_ ?~ SwaggerString
5656 & format ?~ "binary"
5757
5858-- | Default schema for binary data (base64 encoded).
5959byteSchema :: Schema
6060byteSchema = mempty
61− & type_ ?~ OpenApiString
61+ & type_ ?~ SwaggerString
6262 & format ?~ "byte"
6363
6464-- | Default schema for password string.
6565-- @"password"@ format is used to hint UIs the input needs to be obscured.
6666passwordSchema :: Schema
6767passwordSchema = mempty
68− & type_ ?~ OpenApiString
68+ & type_ ?~ SwaggerString
6969 & format ?~ "password"
7070
7171-- | Convert a type into a plain @'Schema'@.
@@ -87,7 +87,7 @@ passwordSchema = mempty
8787--
8888-- instance ToParamSchema Direction where
8989-- toParamSchema _ = mempty
90−-- & type_ ?~ OpenApiString
90+-- & type_ ?~ SwaggerString
9191-- & enum_ ?~ [ \"Up\", \"Down\" ]
9292-- @
9393--
@@ -112,26 +112,24 @@ passwordSchema = mempty
112112class ToParamSchema a where
113113 -- | Convert a type into a plain parameter schema.
114114 --
115− -- >>> BSL.putStrLn $ encodePretty $ toParamSchema (Proxy :: Proxy Integer)
116− -- {
117− -- "type": "integer"
118− -- }
115+ -- >>> encode $ toParamSchema (Proxy :: Proxy Integer)
116+ -- "{\"type\":\"integer\"}"
119117 toParamSchema :: Proxy a -> Schema
120118 default toParamSchema :: (Generic a, GToParamSchema (Rep a)) => Proxy a -> Schema
121119 toParamSchema = genericToParamSchema defaultSchemaOptions
122120
123121instance {-# OVERLAPPING #-} ToParamSchema String where
124− toParamSchema _ = mempty & type_ ?~ OpenApiString
122+ toParamSchema _ = mempty & type_ ?~ SwaggerString
125123
126124instance ToParamSchema Bool where
127− toParamSchema _ = mempty & type_ ?~ OpenApiBoolean
125+ toParamSchema _ = mempty & type_ ?~ SwaggerBoolean
128126
129127instance ToParamSchema Integer where
130− toParamSchema _ = mempty & type_ ?~ OpenApiInteger
128+ toParamSchema _ = mempty & type_ ?~ SwaggerInteger
131129
132130instance ToParamSchema Natural where
133131 toParamSchema _ = mempty
134− & type_ ?~ OpenApiInteger
132+ & type_ ?~ SwaggerInteger
135133 & minimum_ ?~ 0
136134 & exclusiveMinimum ?~ False
137135
@@ -157,45 +155,41 @@ instance ToParamSchema Word64 where
157155
158156-- | Default plain schema for @'Bounded'@, @'Integral'@ types.
159157--
160−-- >>> BSL.putStrLn $ encodePretty $ toParamSchemaBoundedIntegral (Proxy :: Proxy Int8)
161−-- {
162−-- "maximum": 127,
163−-- "minimum": -128,
164−-- "type": "integer"
165−-- }
158+-- >>> encode $ toParamSchemaBoundedIntegral (Proxy :: Proxy Int8)
159+-- "{\"maximum\":127,\"minimum\":-128,\"type\":\"integer\"}"
166160toParamSchemaBoundedIntegral :: forall a t. (Bounded a, Integral a) => Proxy a -> Schema
167161toParamSchemaBoundedIntegral _ = mempty
168− & type_ ?~ OpenApiInteger
162+ & type_ ?~ SwaggerInteger
169163 & minimum_ ?~ fromInteger (toInteger (minBound :: a))
170164 & maximum_ ?~ fromInteger (toInteger (maxBound :: a))
171165
172166instance ToParamSchema Char where
173167 toParamSchema _ = mempty
174− & type_ ?~ OpenApiString
168+ & type_ ?~ SwaggerString
175169 & maxLength ?~ 1
176170 & minLength ?~ 1
177171
178172instance ToParamSchema Scientific where
179− toParamSchema _ = mempty & type_ ?~ OpenApiNumber
173+ toParamSchema _ = mempty & type_ ?~ SwaggerNumber
180174
181175instance HasResolution a => ToParamSchema (Fixed a) where
182176 toParamSchema _ = mempty
183− & type_ ?~ OpenApiNumber
177+ & type_ ?~ SwaggerNumber
184178 & multipleOf ?~ (recip . fromInteger $ resolution (Proxy :: Proxy a))
185179
186180instance ToParamSchema Double where
187181 toParamSchema _ = mempty
188− & type_ ?~ OpenApiNumber
182+ & type_ ?~ SwaggerNumber
189183 & format ?~ "double"
190184
191185instance ToParamSchema Float where
192186 toParamSchema _ = mempty
193− & type_ ?~ OpenApiNumber
187+ & type_ ?~ SwaggerNumber
194188 & format ?~ "float"
195189
196190timeParamSchema :: String -> Schema
197191timeParamSchema fmt = mempty
198− & type_ ?~ OpenApiString
192+ & type_ ?~ SwaggerString
199193 & format ?~ T.pack fmt
200194
201195-- | Format @"date"@ corresponds to @yyyy-mm-dd@ format.
@@ -216,9 +210,9 @@ instance ToParamSchema LocalTime where
216210
217211-- |
218212-- >>> toParamSchema (Proxy :: Proxy ZonedTime) ^. format
219−-- Just "date-time"
213+-- Just "yyyy-mm-ddThh:MM:ss+hhMM"
220214instance ToParamSchema ZonedTime where
221− toParamSchema _ = timeParamSchema "date-time"
215+ toParamSchema _ = timeParamSchema "yyyy-mm-ddThh:MM:ss+hhMM"
222216
223217-- |
224218-- >>> toParamSchema (Proxy :: Proxy UTCTime) ^. format
@@ -237,12 +231,12 @@ instance ToParamSchema TL.Text where
237231
238232instance ToParamSchema Version where
239233 toParamSchema _ = mempty
240− & type_ ?~ OpenApiString
234+ & type_ ?~ SwaggerString
241235 & pattern ?~ "^\\d+(\\.\\d+)*$"
242236
243237instance ToParamSchema SetCookie where
244238 toParamSchema _ = mempty
245− & type_ ?~ OpenApiString
239+ & type_ ?~ SwaggerString
246240
247241type family ToParamSchemaByteStringError bs where
248242 ToParamSchemaByteStringError bs = TypeError
@@ -265,8 +259,8 @@ instance ToParamSchema a => ToParamSchema (Identity a) where toParamSchema _ = t
265259
266260instance ToParamSchema a => ToParamSchema [a] where
267261 toParamSchema _ = mempty
268− & type_ ?~ OpenApiArray
269− & items ?~ OpenApiItemsObject (Inline $ toParamSchema (Proxy :: Proxy a))
262+ & type_ ?~ SwaggerArray
263+ & items ?~ SwaggerItemsObject (Inline $ toParamSchema (Proxy :: Proxy a))
270264
271265instance ToParamSchema a => ToParamSchema (V.Vector a) where toParamSchema _ = toParamSchema (Proxy :: Proxy [a])
272266instance ToParamSchema a => ToParamSchema (VP.Vector a) where toParamSchema _ = toParamSchema (Proxy :: Proxy [a])
@@ -281,35 +275,24 @@ instance ToParamSchema a => ToParamSchema (HashSet a) where
281275 toParamSchema _ = toParamSchema (Proxy :: Proxy (Set a))
282276
283277-- |
284−-- >>> BSL.putStrLn $ encodePretty $ toParamSchema (Proxy :: Proxy ())
285−-- {
286−-- "enum": [
287−-- "_"
288−-- ],
289−-- "type": "string"
290−-- }
278+-- >>> encode $ toParamSchema (Proxy :: Proxy ())
279+-- "{\"type\":\"string\",\"enum\":[\"_\"]}"
291280instance ToParamSchema () where
292281 toParamSchema _ = mempty
293− & type_ ?~ OpenApiString
282+ & type_ ?~ SwaggerString
294283 & enum_ ?~ ["_"]
295284
296285instance ToParamSchema UUID where
297286 toParamSchema _ = mempty
298− & type_ ?~ OpenApiString
287+ & type_ ?~ SwaggerString
299288 & format ?~ "uuid"
300289
301290-- | A configurable generic @'Schema'@ creator.
302291--
303292-- >>> :set -XDeriveGeneric
304293-- >>> data Color = Red | Blue deriving Generic
305−-- >>> BSL.putStrLn $ encodePretty $ genericToParamSchema defaultSchemaOptions (Proxy :: Proxy Color)
306−-- {
307−-- "enum": [
308−-- "Red",
309−-- "Blue"
310−-- ],
311−-- "type": "string"
312−-- }
294+-- >>> encode $ genericToParamSchema defaultSchemaOptions (Proxy :: Proxy Color)
295+-- "{\"type\":\"string\",\"enum\":[\"Red\",\"Blue\"]}"
313296genericToParamSchema :: forall a t. (Generic a, GToParamSchema (Rep a)) => SchemaOptions -> Proxy a -> Schema
314297genericToParamSchema opts _ = gtoParamSchema opts (Proxy :: Proxy (Rep a)) mempty
315298
@@ -339,7 +322,7 @@ instance (GEnumParamSchema f, GEnumParamSchema g) => GEnumParamSchema (f :+: g)
339322
340323instance Constructor c => GEnumParamSchema (C1 c U1) where
341324 genumParamSchema opts _ s = s
342− & type_ ?~ OpenApiString
325+ & type_ ?~ SwaggerString
343326 & enum_ %~ addEnumValue tag
344327 where
345328 tag = toJSON (constructorTagModifier opts (conName (Proxy3 :: Proxy3 c f p)))
@@ -351,4 +334,3 @@ data Proxy3 a b c = Proxy3
351334
352335-- $setup
353336-- >>> import Data.Aeson (encode)
354−-- >>> import Data.OpenApi.Internal.Utils
src/Data/OpenApi/Internal/Schema.hs → src/Data/Swagger/Internal/Schema.hsrenamed+118−380
@@ -1,17 +1,15 @@
1−{-# LANGUAGE CPP #-}
21{-# LANGUAGE ConstraintKinds #-}
3−{-# LANGUAGE DataKinds #-}
42{-# LANGUAGE DefaultSignatures #-}
53{-# LANGUAGE FlexibleContexts #-}
64{-# LANGUAGE FlexibleInstances #-}
75{-# LANGUAGE KindSignatures #-}
6+{-# LANGUAGE DataKinds #-}
87{-# LANGUAGE OverloadedLists #-}
98{-# LANGUAGE OverloadedStrings #-}
109{-# LANGUAGE PackageImports #-}
1110{-# LANGUAGE PolyKinds #-}
1211{-# LANGUAGE ScopedTypeVariables #-}
1312{-# LANGUAGE TupleSections #-}
14−{-# LANGUAGE TypeApplications #-}
1513{-# LANGUAGE TypeFamilies #-}
1614{-# LANGUAGE TypeOperators #-}
1715{-# LANGUAGE TypeSynonymInstances #-}
@@ -19,7 +17,7 @@
1917{-# OPTIONS_GHC -Wno-redundant-constraints #-}
2018-- For TypeErrors
2119{-# OPTIONS_GHC -Wno-unticked-promoted-constructors #-}
22−module Data.OpenApi.Internal.Schema where
20+module Data.Swagger.Internal.Schema where
2321
2422import Prelude ()
2523import Prelude.Compat
@@ -42,7 +40,6 @@ import qualified Data.HashMap.Strict.InsOrd as InsOrdHashMap
4240import Data.Int
4341import Data.IntSet (IntSet)
4442import Data.IntMap (IntMap)
45−import Data.List (sort)
4643import Data.List.NonEmpty.Compat (NonEmpty)
4744import Data.Map (Map)
4845import Data.Maybe (fromMaybe)
@@ -62,16 +59,14 @@ import Numeric.Natural.Compat (Natural)
6259import Data.Word
6360import GHC.Generics
6461import qualified Data.UUID.Types as UUID
65−import Type.Reflection (Typeable, typeRep)
6662
67−import Data.OpenApi.Aeson.Compat (keyToText, objectKeys, toInsOrdHashMap)
68−import Data.OpenApi.Declare
69−import Data.OpenApi.Internal
70−import Data.OpenApi.Internal.ParamSchema (ToParamSchema (..))
71−import Data.OpenApi.Internal.TypeShape
72−import Data.OpenApi.Lens hiding (name, schema)
73−import qualified Data.OpenApi.Lens as Swagger
74−import Data.OpenApi.SchemaOptions
63+import Data.Swagger.Declare
64+import Data.Swagger.Internal
65+import Data.Swagger.Internal.ParamSchema (ToParamSchema(..))
66+import Data.Swagger.Lens hiding (name, schema)
67+import qualified Data.Swagger.Lens as Swagger
68+import Data.Swagger.SchemaOptions
69+import Data.Swagger.Internal.TypeShape
7570
7671import qualified Data.ByteString as BS
7772import qualified Data.ByteString.Lazy.Char8 as BSL
@@ -102,7 +97,7 @@ rename name (NamedSchema _ schema) = NamedSchema name schema
10297--
10398-- import Control.Lens
10499-- import Data.Proxy
105−-- import Data.OpenApi
100+-- import Data.Swagger
106101--
107102-- data Coord = Coord { x :: Double, y :: Double }
108103--
@@ -110,7 +105,7 @@ rename name (NamedSchema _ schema) = NamedSchema name schema
110105-- declareNamedSchema _ = do
111106-- doubleSchema <- declareSchemaRef (Proxy :: Proxy Double)
112107-- return $ NamedSchema (Just \"Coord\") $ mempty
113−-- & type_ ?~ OpenApiObject
108+-- & type_ ?~ SwaggerObject
114109-- & properties .~
115110-- [ (\"x\", doubleSchema)
116111-- , (\"y\", doubleSchema)
@@ -136,7 +131,7 @@ rename name (NamedSchema _ schema) = NamedSchema name schema
136131--
137132-- instance ToSchema Coord
138133-- @
139−class Typeable a => ToSchema a where
134+class ToSchema a where
140135 -- | Convert a type into an optionally named schema
141136 -- together with all used definitions.
142137 -- Note that the schema itself is included in definitions
@@ -158,19 +153,13 @@ declareSchema = fmap _namedSchemaSchema . declareNamedSchema
158153--
159154-- >>> toNamedSchema (Proxy :: Proxy String) ^. name
160155-- Nothing
161−-- >>> BSL.putStrLn $ encodePretty (toNamedSchema (Proxy :: Proxy String) ^. schema)
162−-- {
163−-- "type": "string"
164−-- }
156+-- >>> BSL.putStrLn $ encode (toNamedSchema (Proxy :: Proxy String) ^. schema)
157+-- {"type":"string"}
165158--
166159-- >>> toNamedSchema (Proxy :: Proxy Day) ^. name
167160-- Just "Day"
168−-- >>> BSL.putStrLn $ encodePretty (toNamedSchema (Proxy :: Proxy Day) ^. schema)
169−-- {
170−-- "example": "2016-07-22",
171−-- "format": "date",
172−-- "type": "string"
173−-- }
161+-- >>> BSL.putStrLn $ encode (toNamedSchema (Proxy :: Proxy Day) ^. schema)
162+-- {"example":"2016-07-22","format":"date","type":"string"}
174163toNamedSchema :: ToSchema a => Proxy a -> NamedSchema
175164toNamedSchema = undeclare . declareNamedSchema
176165
@@ -186,35 +175,22 @@ schemaName = _namedSchemaName . toNamedSchema
186175
187176-- | Convert a type into a schema.
188177--
189−-- >>> BSL.putStrLn $ encodePretty $ toSchema (Proxy :: Proxy Int8)
190−-- {
191−-- "maximum": 127,
192−-- "minimum": -128,
193−-- "type": "integer"
194−-- }
178+-- >>> BSL.putStrLn $ encode $ toSchema (Proxy :: Proxy Int8)
179+-- {"maximum":127,"minimum":-128,"type":"integer"}
195180--
196−-- >>> BSL.putStrLn $ encodePretty $ toSchema (Proxy :: Proxy [Day])
197−-- {
198−-- "items": {
199−-- "$ref": "#/components/schemas/Day"
200−-- },
201−-- "type": "array"
202−-- }
181+-- >>> BSL.putStrLn $ encode $ toSchema (Proxy :: Proxy [Day])
182+-- {"items":{"$ref":"#/components/schemas/Day"},"type":"array"}
203183toSchema :: ToSchema a => Proxy a -> Schema
204184toSchema = _namedSchemaSchema . toNamedSchema
205185
206186-- | Convert a type into a referenced schema if possible.
207187-- Only named schemas can be referenced, nameless schemas are inlined.
208188--
209−-- >>> BSL.putStrLn $ encodePretty $ toSchemaRef (Proxy :: Proxy Integer)
210−-- {
211−-- "type": "integer"
212−-- }
189+-- >>> BSL.putStrLn $ encode $ toSchemaRef (Proxy :: Proxy Integer)
190+-- {"type":"integer"}
213191--
214−-- >>> BSL.putStrLn $ encodePretty $ toSchemaRef (Proxy :: Proxy Day)
215−-- {
216−-- "$ref": "#/components/schemas/Day"
217−-- }
192+-- >>> BSL.putStrLn $ encode $ toSchemaRef (Proxy :: Proxy Day)
193+-- {"$ref":"#/components/schemas/Day"}
218194toSchemaRef :: ToSchema a => Proxy a -> Referenced Schema
219195toSchemaRef = undeclare . declareSchemaRef
220196
@@ -282,15 +258,8 @@ inlineAllSchemas = inlineSchemasWhen (const True)
282258
283259-- | Convert a type into a schema without references.
284260--
285−-- >>> BSL.putStrLn $ encodePretty $ toInlinedSchema (Proxy :: Proxy [Day])
286−-- {
287−-- "items": {
288−-- "example": "2016-07-22",
289−-- "format": "date",
290−-- "type": "string"
291−-- },
292−-- "type": "array"
293−-- }
261+-- >>> BSL.putStrLn $ encode $ toInlinedSchema (Proxy :: Proxy [Day])
262+-- {"items":{"example":"2016-07-22","format":"date","type":"string"},"type":"array"}
294263--
295264-- __WARNING:__ @'toInlinedSchema'@ will produce infinite schema
296265-- when inlining recursive schemas.
@@ -323,64 +292,19 @@ inlineNonRecursiveSchemas defs = inlineSchemasWhen nonRecursive defs
323292-- | Make an unrestrictive sketch of a @'Schema'@ based on a @'ToJSON'@ instance.
324293-- Produced schema can be used for further refinement.
325294--
326−-- >>> BSL.putStrLn $ encodePretty $ sketchSchema "hello"
327−-- {
328−-- "example": "hello",
329−-- "type": "string"
330−-- }
295+-- >>> BSL.putStrLn $ encode $ sketchSchema "hello"
296+-- {"example":"hello","type":"string"}
331297--
332−-- >>> BSL.putStrLn $ encodePretty $ sketchSchema (1, 2, 3)
333−-- {
334−-- "example": [
335−-- 1,
336−-- 2,
337−-- 3
338−-- ],
339−-- "items": {
340−-- "type": "number"
341−-- },
342−-- "type": "array"
343−-- }
298+-- >>> BSL.putStrLn $ encode $ sketchSchema (1, 2, 3)
299+-- {"example":[1,2,3],"items":{"type":"number"},"type":"array"}
344300--
345−-- >>> BSL.putStrLn $ encodePretty $ sketchSchema ("Jack", 25)
346−-- {
347−-- "example": [
348−-- "Jack",
349−-- 25
350−-- ],
351−-- "items": [
352−-- {
353−-- "type": "string"
354−-- },
355−-- {
356−-- "type": "number"
357−-- }
358−-- ],
359−-- "type": "array"
360−-- }
301+-- >>> BSL.putStrLn $ encode $ sketchSchema ("Jack", 25)
302+-- {"example":["Jack",25],"items":[{"type":"string"},{"type":"number"}],"type":"array"}
361303--
362304-- >>> data Person = Person { name :: String, age :: Int } deriving (Generic)
363305-- >>> instance ToJSON Person
364−-- >>> BSL.putStrLn $ encodePretty $ sketchSchema (Person "Jack" 25)
365−-- {
366−-- "example": {
367−-- "age": 25,
368−-- "name": "Jack"
369−-- },
370−-- "properties": {
371−-- "age": {
372−-- "type": "number"
373−-- },
374−-- "name": {
375−-- "type": "string"
376−-- }
377−-- },
378−-- "required": [
379−-- "age",
380−-- "name"
381−-- ],
382−-- "type": "object"
383−-- }
306+-- >>> BSL.putStrLn $ encode $ sketchSchema (Person "Jack" 25)
307+-- {"example":{"age":25,"name":"Jack"},"required":["age","name"],"type":"object","properties":{"age":{"type":"number"},"name":{"type":"string"}}}
384308sketchSchema :: ToJSON a => a -> Schema
385309sketchSchema = sketch . toJSON
386310 where
@@ -388,15 +312,15 @@ sketchSchema = sketch . toJSON
388312 sketch js@(Bool _) = go js
389313 sketch js = go js & example ?~ js
390314
391− go Null = mempty & type_ ?~ OpenApiNull
392− go (Bool _) = mempty & type_ ?~ OpenApiBoolean
393− go (String _) = mempty & type_ ?~ OpenApiString
394− go (Number _) = mempty & type_ ?~ OpenApiNumber
315+ go Null = mempty & type_ ?~ SwaggerNull
316+ go (Bool _) = mempty & type_ ?~ SwaggerBoolean
317+ go (String _) = mempty & type_ ?~ SwaggerString
318+ go (Number _) = mempty & type_ ?~ SwaggerNumber
395319 go (Array xs) = mempty
396− & type_ ?~ OpenApiArray
320+ & type_ ?~ SwaggerArray
397321 & items ?~ case ischema of
398− Just s -> OpenApiItemsObject (Inline s)
399− _ -> OpenApiItemsArray (map Inline ys)
322+ Just s -> SwaggerItemsObject (Inline s)
323+ _ -> SwaggerItemsArray (map Inline ys)
400324 where
401325 ys = map go (V.toList xs)
402326 allSame = and ((zipWith (==)) ys (tail ys))
@@ -405,178 +329,64 @@ sketchSchema = sketch . toJSON
405329 (z:_) | allSame -> Just z
406330 _ -> Nothing
407331 go (Object o) = mempty
408− & type_ ?~ OpenApiObject
409− & required .~ sort (objectKeys o)
410− & properties .~ fmap (Inline . go) (toInsOrdHashMap o)
332+ & type_ ?~ SwaggerObject
333+ & required .~ HashMap.keys o
334+ & properties .~ fmap (Inline . go) (InsOrdHashMap.fromHashMap o)
411335
412336-- | Make a restrictive sketch of a @'Schema'@ based on a @'ToJSON'@ instance.
413337-- Produced schema uses as much constraints as possible.
414338--
415−-- >>> BSL.putStrLn $ encodePretty $ sketchStrictSchema "hello"
416−-- {
417−-- "enum": [
418−-- "hello"
419−-- ],
420−-- "maxLength": 5,
421−-- "minLength": 5,
422−-- "pattern": "hello",
423−-- "type": "string"
424−-- }
339+-- >>> BSL.putStrLn $ encode $ sketchStrictSchema "hello"
340+-- {"maxLength":5,"pattern":"hello","minLength":5,"type":"string","enum":["hello"]}
425341--
426−-- >>> BSL.putStrLn $ encodePretty $ sketchStrictSchema (1, 2, 3)
427−-- {
428−-- "enum": [
429−-- [
430−-- 1,
431−-- 2,
432−-- 3
433−-- ]
434−-- ],
435−-- "items": [
436−-- {
437−-- "enum": [
438−-- 1
439−-- ],
440−-- "maximum": 1,
441−-- "minimum": 1,
442−-- "multipleOf": 1,
443−-- "type": "number"
444−-- },
445−-- {
446−-- "enum": [
447−-- 2
448−-- ],
449−-- "maximum": 2,
450−-- "minimum": 2,
451−-- "multipleOf": 2,
452−-- "type": "number"
453−-- },
454−-- {
455−-- "enum": [
456−-- 3
457−-- ],
458−-- "maximum": 3,
459−-- "minimum": 3,
460−-- "multipleOf": 3,
461−-- "type": "number"
462−-- }
463−-- ],
464−-- "maxItems": 3,
465−-- "minItems": 3,
466−-- "type": "array",
467−-- "uniqueItems": true
468−-- }
342+-- >>> BSL.putStrLn $ encode $ sketchStrictSchema (1, 2, 3)
343+-- {"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]]}
469344--
470−-- >>> BSL.putStrLn $ encodePretty $ sketchStrictSchema ("Jack", 25)
471−-- {
472−-- "enum": [
473−-- [
474−-- "Jack",
475−-- 25
476−-- ]
477−-- ],
478−-- "items": [
479−-- {
480−-- "enum": [
481−-- "Jack"
482−-- ],
483−-- "maxLength": 4,
484−-- "minLength": 4,
485−-- "pattern": "Jack",
486−-- "type": "string"
487−-- },
488−-- {
489−-- "enum": [
490−-- 25
491−-- ],
492−-- "maximum": 25,
493−-- "minimum": 25,
494−-- "multipleOf": 25,
495−-- "type": "number"
496−-- }
497−-- ],
498−-- "maxItems": 2,
499−-- "minItems": 2,
500−-- "type": "array",
501−-- "uniqueItems": true
502−-- }
345+-- >>> BSL.putStrLn $ encode $ sketchStrictSchema ("Jack", 25)
346+-- {"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]]}
503347--
504348-- >>> data Person = Person { name :: String, age :: Int } deriving (Generic)
505349-- >>> instance ToJSON Person
506−-- >>> BSL.putStrLn $ encodePretty $ sketchStrictSchema (Person "Jack" 25)
507−-- {
508−-- "enum": [
509−-- {
510−-- "age": 25,
511−-- "name": "Jack"
512−-- }
513−-- ],
514−-- "maxProperties": 2,
515−-- "minProperties": 2,
516−-- "properties": {
517−-- "age": {
518−-- "enum": [
519−-- 25
520−-- ],
521−-- "maximum": 25,
522−-- "minimum": 25,
523−-- "multipleOf": 25,
524−-- "type": "number"
525−-- },
526−-- "name": {
527−-- "enum": [
528−-- "Jack"
529−-- ],
530−-- "maxLength": 4,
531−-- "minLength": 4,
532−-- "pattern": "Jack",
533−-- "type": "string"
534−-- }
535−-- },
536−-- "required": [
537−-- "age",
538−-- "name"
539−-- ],
540−-- "type": "object"
541−-- }
350+-- >>> BSL.putStrLn $ encode $ sketchStrictSchema (Person "Jack" 25)
351+-- {"minProperties":2,"required":["age","name"],"maxProperties":2,"type":"object","enum":[{"age":25,"name":"Jack"}],"properties":{"age":{"maximum":25,"minimum":25,"multipleOf":25,"type":"number","enum":[25]},"name":{"maxLength":4,"pattern":"Jack","minLength":4,"type":"string","enum":["Jack"]}}}
542352sketchStrictSchema :: ToJSON a => a -> Schema
543353sketchStrictSchema = go . toJSON
544354 where
545− go Null = mempty & type_ ?~ OpenApiNull
355+ go Null = mempty & type_ ?~ SwaggerNull
546356 go js@(Bool _) = mempty
547− & type_ ?~ OpenApiBoolean
357+ & type_ ?~ SwaggerBoolean
548358 & enum_ ?~ [js]
549359 go js@(String s) = mempty
550− & type_ ?~ OpenApiString
360+ & type_ ?~ SwaggerString
551361 & maxLength ?~ fromIntegral (T.length s)
552362 & minLength ?~ fromIntegral (T.length s)
553363 & pattern ?~ s
554364 & enum_ ?~ [js]
555365 go js@(Number n) = mempty
556− & type_ ?~ OpenApiNumber
366+ & type_ ?~ SwaggerNumber
557367 & maximum_ ?~ n
558368 & minimum_ ?~ n
559369 & multipleOf ?~ n
560370 & enum_ ?~ [js]
561371 go js@(Array xs) = mempty
562− & type_ ?~ OpenApiArray
372+ & type_ ?~ SwaggerArray
563373 & maxItems ?~ fromIntegral sz
564374 & minItems ?~ fromIntegral sz
565− & items ?~ OpenApiItemsArray (map (Inline . go) (V.toList xs))
375+ & items ?~ SwaggerItemsArray (map (Inline . go) (V.toList xs))
566376 & uniqueItems ?~ allUnique
567377 & enum_ ?~ [js]
568378 where
569379 sz = length xs
570380 allUnique = sz == HashSet.size (HashSet.fromList (V.toList xs))
571381 go js@(Object o) = mempty
572− & type_ ?~ OpenApiObject
573− & required .~ sort names
574− & properties .~ fmap (Inline . go) (toInsOrdHashMap o)
382+ & type_ ?~ SwaggerObject
383+ & required .~ names
384+ & properties .~ fmap (Inline . go) (InsOrdHashMap.fromHashMap o)
575385 & maxProperties ?~ fromIntegral (length names)
576386 & minProperties ?~ fromIntegral (length names)
577387 & enum_ ?~ [js]
578388 where
579− names = objectKeys o
389+ names = HashMap.keys o
580390
581391class GToSchema (f :: * -> *) where
582392 gdeclareNamedSchema :: SchemaOptions -> Proxy f -> Schema -> Declare (Definitions Schema) NamedSchema
@@ -585,8 +395,8 @@ instance {-# OVERLAPPABLE #-} ToSchema a => ToSchema [a] where
585395 declareNamedSchema _ = do
586396 ref <- declareSchemaRef (Proxy :: Proxy a)
587397 return $ unnamed $ mempty
588− & type_ ?~ OpenApiArray
589− & items ?~ OpenApiItemsObject ref
398+ & type_ ?~ SwaggerArray
399+ & items ?~ SwaggerItemsObject ref
590400
591401instance {-# OVERLAPPING #-} ToSchema String where declareNamedSchema = plain . paramSchemaToSchema
592402instance ToSchema Bool where declareNamedSchema = plain . paramSchemaToSchema
@@ -611,7 +421,7 @@ instance ToSchema Scientific where declareNamedSchema = plain . paramSchemaToSc
611421instance ToSchema Double where declareNamedSchema = plain . paramSchemaToSchema
612422instance ToSchema Float where declareNamedSchema = plain . paramSchemaToSchema
613423
614−instance (Typeable (Fixed a), HasResolution a) => ToSchema (Fixed a) where declareNamedSchema = plain . paramSchemaToSchema
424+instance HasResolution a => ToSchema (Fixed a) where declareNamedSchema = plain . paramSchemaToSchema
615425
616426instance ToSchema a => ToSchema (Maybe a) where
617427 declareNamedSchema _ = declareNamedSchema (Proxy :: Proxy a)
@@ -628,22 +438,16 @@ instance ToSchema UUID.UUID where
628438 declareNamedSchema p = pure $ named "UUID" $ paramSchemaToSchema p
629439 & example ?~ toJSON (UUID.toText UUID.nil)
630440
631−instance (ToSchema a, ToSchema b) => ToSchema (a, b) where
632− declareNamedSchema = fmap unname . genericDeclareNamedSchema defaultSchemaOptions
633−instance (ToSchema a, ToSchema b, ToSchema c) => ToSchema (a, b, c) where
634− declareNamedSchema = fmap unname . genericDeclareNamedSchema defaultSchemaOptions
635−instance (ToSchema a, ToSchema b, ToSchema c, ToSchema d) => ToSchema (a, b, c, d) where
636− declareNamedSchema = fmap unname . genericDeclareNamedSchema defaultSchemaOptions
637−instance (ToSchema a, ToSchema b, ToSchema c, ToSchema d, ToSchema e) => ToSchema (a, b, c, d, e) where
638− declareNamedSchema = fmap unname . genericDeclareNamedSchema defaultSchemaOptions
639−instance (ToSchema a, ToSchema b, ToSchema c, ToSchema d, ToSchema e, ToSchema f) => ToSchema (a, b, c, d, e, f) where
640− declareNamedSchema = fmap unname . genericDeclareNamedSchema defaultSchemaOptions
641−instance (ToSchema a, ToSchema b, ToSchema c, ToSchema d, ToSchema e, ToSchema f, ToSchema g) => ToSchema (a, b, c, d, e, f, g) where
642− declareNamedSchema = fmap unname . genericDeclareNamedSchema defaultSchemaOptions
441+instance (ToSchema a, ToSchema b) => ToSchema (a, b)
442+instance (ToSchema a, ToSchema b, ToSchema c) => ToSchema (a, b, c)
443+instance (ToSchema a, ToSchema b, ToSchema c, ToSchema d) => ToSchema (a, b, c, d)
444+instance (ToSchema a, ToSchema b, ToSchema c, ToSchema d, ToSchema e) => ToSchema (a, b, c, d, e)
445+instance (ToSchema a, ToSchema b, ToSchema c, ToSchema d, ToSchema e, ToSchema f) => ToSchema (a, b, c, d, e, f)
446+instance (ToSchema a, ToSchema b, ToSchema c, ToSchema d, ToSchema e, ToSchema f, ToSchema g) => ToSchema (a, b, c, d, e, f, g)
643447
644448timeSchema :: T.Text -> Schema
645449timeSchema fmt = mempty
646− & type_ ?~ OpenApiString
450+ & type_ ?~ SwaggerString
647451 & format ?~ fmt
648452
649453-- | Format @"date"@ corresponds to @yyyy-mm-dd@ format.
@@ -658,7 +462,7 @@ instance ToSchema LocalTime where
658462 declareNamedSchema _ = pure $ named "LocalTime" $ timeSchema "yyyy-mm-ddThh:MM:ss"
659463 & example ?~ toJSON (LocalTime (fromGregorian 2016 7 22) (TimeOfDay 7 40 0))
660464
661−-- | Format @"date-time"@ corresponds to @yyyy-mm-ddThh:MM:ss(Z|+hh:MM)@ format.
465+-- | Format @"date"@ corresponds to @yyyy-mm-ddThh:MM:ss(Z|+hh:MM)@ format.
662466instance ToSchema ZonedTime where
663467 declareNamedSchema _ = pure $ named "ZonedTime" $ timeSchema "date-time"
664468 & example ?~ toJSON (ZonedTime (LocalTime (fromGregorian 2016 7 22) (TimeOfDay 7 40 0)) (hoursToTimeZone 3))
@@ -690,7 +494,7 @@ instance ToSchemaByteStringError BSL.ByteString => ToSchema BSL.ByteString where
690494instance ToSchema IntSet where declareNamedSchema _ = declareNamedSchema (Proxy :: Proxy (Set Int))
691495
692496-- | NOTE: This schema does not account for the uniqueness of keys.
693−instance (ToSchema a) => ToSchema (IntMap a) where
497+instance ToSchema a => ToSchema (IntMap a) where
694498 declareNamedSchema _ = declareNamedSchema (Proxy :: Proxy [(Int, a)])
695499
696500instance (ToJSONKey k, ToSchema k, ToSchema v) => ToSchema (Map k v) where
@@ -701,7 +505,7 @@ instance (ToJSONKey k, ToSchema k, ToSchema v) => ToSchema (Map k v) where
701505 declareObjectMapSchema = do
702506 schema <- declareSchemaRef (Proxy :: Proxy v)
703507 return $ unnamed $ mempty
704− & type_ ?~ OpenApiObject
508+ & type_ ?~ SwaggerObject
705509 & additionalProperties ?~ AdditionalPropertiesSchema schema
706510
707511instance (ToJSONKey k, ToSchema k, ToSchema v) => ToSchema (HashMap k v) where
@@ -709,7 +513,7 @@ instance (ToJSONKey k, ToSchema k, ToSchema v) => ToSchema (HashMap k v) where
709513
710514instance {-# OVERLAPPING #-} ToSchema Object where
711515 declareNamedSchema _ = pure $ NamedSchema (Just "Object") $ mempty
712− & type_ ?~ OpenApiObject
516+ & type_ ?~ SwaggerObject
713517 & description ?~ "Arbitrary JSON object."
714518 & additionalProperties ?~ AdditionalPropertiesAllowed True
715519
@@ -746,15 +550,11 @@ instance ToSchema a => ToSchema (Identity a) where declareNamedSchema _ = declar
746550
747551-- | Default schema for @'Bounded'@, @'Integral'@ types.
748552--
749−-- >>> BSL.putStrLn $ encodePretty $ toSchemaBoundedIntegral (Proxy :: Proxy Int16)
750−-- {
751−-- "maximum": 32767,
752−-- "minimum": -32768,
753−-- "type": "integer"
754−-- }
553+-- >>> BSL.putStrLn $ encode $ toSchemaBoundedIntegral (Proxy :: Proxy Int16)
554+-- {"maximum":32767,"minimum":-32768,"type":"integer"}
755555toSchemaBoundedIntegral :: forall a. (Bounded a, Integral a) => Proxy a -> Schema
756556toSchemaBoundedIntegral _ = mempty
757− & type_ ?~ OpenApiInteger
557+ & type_ ?~ SwaggerInteger
758558 & minimum_ ?~ fromInteger (toInteger (minBound :: a))
759559 & maximum_ ?~ fromInteger (toInteger (maxBound :: a))
760560
@@ -783,27 +583,8 @@ genericDeclareNamedSchemaNewtype opts f proxy = genericNameSchema opts proxy <$>
783583-- >>> instance ToSchema ButtonState
784584-- >>> instance ToJSONKey ButtonState where toJSONKey = toJSONKeyText (T.pack . show)
785585-- >>> type ImageUrl = T.Text
786−-- >>> BSL.putStrLn $ encodePretty $ toSchemaBoundedEnumKeyMapping (Proxy :: Proxy (Map ButtonState ImageUrl))
787−-- {
788−-- "properties": {
789−-- "Active": {
790−-- "type": "string"
791−-- },
792−-- "Disabled": {
793−-- "type": "string"
794−-- },
795−-- "Focus": {
796−-- "type": "string"
797−-- },
798−-- "Hover": {
799−-- "type": "string"
800−-- },
801−-- "Neutral": {
802−-- "type": "string"
803−-- }
804−-- },
805−-- "type": "object"
806−-- }
586+-- >>> BSL.putStrLn $ encode $ toSchemaBoundedEnumKeyMapping (Proxy :: Proxy (Map ButtonState ImageUrl))
587+-- {"type":"object","properties":{"Focus":{"type":"string"},"Disabled":{"type":"string"},"Active":{"type":"string"},"Neutral":{"type":"string"},"Hover":{"type":"string"}}}
807588--
808589-- Note: this is only useful when @key@ is encoded with 'ToJSONKeyText'.
809590-- If it is encoded with 'ToJSONKeyValue' then a regular schema for @[(key, value)]@ is used.
@@ -811,15 +592,15 @@ declareSchemaBoundedEnumKeyMapping :: forall map key value.
811592 (Bounded key, Enum key, ToJSONKey key, ToSchema key, ToSchema value)
812593 => Proxy (map key value) -> Declare (Definitions Schema) Schema
813594declareSchemaBoundedEnumKeyMapping _ = case toJSONKey :: ToJSONKeyFunction key of
814− ToJSONKeyText getKey _ -> objectSchema getKey
595+ ToJSONKeyText keyToText _ -> objectSchema keyToText
815596 ToJSONKeyValue _ _ -> declareSchema (Proxy :: Proxy [(key, value)])
816597 where
817− objectSchema getKey = do
598+ objectSchema keyToText = do
818599 valueRef <- declareSchemaRef (Proxy :: Proxy value)
819600 let allKeys = [minBound..maxBound :: key]
820− mkPair k = (keyToText $ getKey k, valueRef)
601+ mkPair k = (keyToText k, valueRef)
821602 return $ mempty
822− & type_ ?~ OpenApiObject
603+ & type_ ?~ SwaggerObject
823604 & properties .~ InsOrdHashMap.fromList (map mkPair allKeys)
824605
825606-- | A 'Schema' for a mapping with 'Bounded' 'Enum' keys.
@@ -830,27 +611,8 @@ declareSchemaBoundedEnumKeyMapping _ = case toJSONKey :: ToJSONKeyFunction key o
830611-- >>> instance ToSchema ButtonState
831612-- >>> instance ToJSONKey ButtonState where toJSONKey = toJSONKeyText (T.pack . show)
832613-- >>> type ImageUrl = T.Text
833−-- >>> BSL.putStrLn $ encodePretty $ toSchemaBoundedEnumKeyMapping (Proxy :: Proxy (Map ButtonState ImageUrl))
834−-- {
835−-- "properties": {
836−-- "Active": {
837−-- "type": "string"
838−-- },
839−-- "Disabled": {
840−-- "type": "string"
841−-- },
842−-- "Focus": {
843−-- "type": "string"
844−-- },
845−-- "Hover": {
846−-- "type": "string"
847−-- },
848−-- "Neutral": {
849−-- "type": "string"
850−-- }
851−-- },
852−-- "type": "object"
853−-- }
614+-- >>> BSL.putStrLn $ encode $ toSchemaBoundedEnumKeyMapping (Proxy :: Proxy (Map ButtonState ImageUrl))
615+-- {"type":"object","properties":{"Focus":{"type":"string"},"Disabled":{"type":"string"},"Active":{"type":"string"},"Neutral":{"type":"string"},"Hover":{"type":"string"}}}
854616--
855617-- Note: this is only useful when @key@ is encoded with 'ToJSONKeyText'.
856618-- If it is encoded with 'ToJSONKeyValue' then a regular schema for @[(key, value)]@ is used.
@@ -860,7 +622,7 @@ toSchemaBoundedEnumKeyMapping :: forall map key value.
860622toSchemaBoundedEnumKeyMapping = flip evalDeclare mempty . declareSchemaBoundedEnumKeyMapping
861623
862624-- | A configurable generic @'Schema'@ creator.
863−genericDeclareSchema :: (Generic a, GToSchema (Rep a), Typeable a) =>
625+genericDeclareSchema :: (Generic a, GToSchema (Rep a)) =>
864626 SchemaOptions -> Proxy a -> Declare (Definitions Schema) Schema
865627genericDeclareSchema opts proxy = _namedSchemaSchema <$> genericDeclareNamedSchema opts proxy
866628
@@ -868,24 +630,9 @@ genericDeclareSchema opts proxy = _namedSchemaSchema <$> genericDeclareNamedSche
868630-- This function applied to @'defaultSchemaOptions'@
869631-- is used as the default for @'declareNamedSchema'@
870632-- when the type is an instance of @'Generic'@.
871−--
872−-- Default implementation will use the name from 'Typeable' instance, including concrete
873−-- instantioations of type variables.
874−--
875−-- For example:
876−--
877−-- >>> _namedSchemaName $ undeclare $ genericDeclareNamedSchema defaultSchemaOptions (Proxy :: Proxy (Either Int Bool))
878−-- Just "Either_Int_Bool"
879−genericDeclareNamedSchema :: forall a. (Generic a, GToSchema (Rep a), Typeable a) =>
633+genericDeclareNamedSchema :: forall a. (Generic a, GToSchema (Rep a)) =>
880634 SchemaOptions -> Proxy a -> Declare (Definitions Schema) NamedSchema
881−genericDeclareNamedSchema opts _ =
882− rename (Just $ T.pack name) <$> gdeclareNamedSchema opts (Proxy :: Proxy (Rep a)) mempty
883− where
884− unspace ' ' = '_'
885− unspace x = x
886− orig = fmap unspace $ show $ typeRep @a
887− name = datatypeNameModifier opts orig
888−
635+genericDeclareNamedSchema opts _ = gdeclareNamedSchema opts (Proxy :: Proxy (Rep a)) mempty
889636
890637-- | Derive a 'Generic'-based name for a datatype and assign it to a given 'Schema'.
891638genericNameSchema :: forall a d f.
@@ -912,8 +659,8 @@ paramSchemaToSchema = toParamSchema
912659
913660nullarySchema :: Schema
914661nullarySchema = mempty
915− & type_ ?~ OpenApiArray
916− & items ?~ OpenApiItemsArray []
662+ & type_ ?~ SwaggerArray
663+ & items ?~ SwaggerItemsArray []
917664
918665gtoNamedSchema :: GToSchema f => SchemaOptions -> Proxy f -> NamedSchema
919666gtoNamedSchema opts proxy = undeclare $ gdeclareNamedSchema opts proxy mempty
@@ -943,15 +690,12 @@ instance (Selector s, GToSchema f, GToSchema (S1 s f)) => GToSchema (C1 c (S1 s
943690 | unwrapUnaryRecords opts = fieldSchema
944691 | otherwise =
945692 case schema ^. items of
946− Just (OpenApiItemsArray [_]) -> fieldSchema
693+ Just (SwaggerItemsArray [_]) -> fieldSchema
947694 _ -> do
948− -- We have to run recordSchema instead of just using its defs,
949− -- since those can be recursive and will lead to infinite loop,
950− -- see https://github.com/biocad/openapi3/pull/37
951− NamedSchema _ schema' <- recordSchema
952− return (unnamed schema')
695+ declare defs
696+ return (unnamed schema)
953697 where
954− (_, NamedSchema _ schema) = runDeclare recordSchema mempty
698+ (defs, NamedSchema _ schema) = runDeclare recordSchema mempty
955699 recordSchema = gdeclareNamedSchema opts (Proxy :: Proxy (S1 s f)) s
956700 fieldSchema = gdeclareNamedSchema opts (Proxy :: Proxy f) s
957701
@@ -974,10 +718,10 @@ gdeclareSchemaRef opts proxy = do
974718 return $ Ref (Reference name)
975719 _ -> Inline <$> gdeclareSchema opts proxy
976720
977−appendItem :: Referenced Schema -> Maybe OpenApiItems -> Maybe OpenApiItems
978−appendItem x Nothing = Just (OpenApiItemsArray [x])
979−appendItem x (Just (OpenApiItemsArray xs)) = Just (OpenApiItemsArray (xs ++ [x]))
980−appendItem _ _ = error "GToSchema.appendItem: cannot append to OpenApiItemsObject"
721+appendItem :: Referenced Schema -> Maybe SwaggerItems -> Maybe SwaggerItems
722+appendItem x Nothing = Just (SwaggerItemsArray [x])
723+appendItem x (Just (SwaggerItemsArray xs)) = Just (SwaggerItemsArray (xs ++ [x]))
724+appendItem _ _ = error "GToSchema.appendItem: cannot append to SwaggerItemsObject"
981725
982726withFieldSchema :: forall proxy s f. (Selector s, GToSchema f) =>
983727 SchemaOptions -> proxy s f -> Bool -> Schema -> Declare (Definitions Schema) Schema
@@ -986,12 +730,12 @@ withFieldSchema opts _ isRequiredField schema = do
986730 return $
987731 if T.null fname
988732 then schema
989− & type_ ?~ OpenApiArray
733+ & type_ ?~ SwaggerArray
990734 & items %~ appendItem ref
991735 & maxItems %~ Just . maybe 1 (+1) -- increment maxItems
992736 & minItems %~ Just . maybe 1 (+1) -- increment minItems
993737 else schema
994− & type_ ?~ OpenApiObject
738+ & type_ ?~ SwaggerObject
995739 & properties . at fname ?~ ref
996740 & if isRequiredField
997741 then required %~ (++ [fname])
@@ -1026,14 +770,14 @@ gdeclareNamedSumSchema opts proxy _
1026770 | otherwise = do
1027771 (schemas, _) <- runWriterT declareSumSchema
1028772 return $ unnamed $ mempty
1029− & type_ ?~ OpenApiObject
773+ & type_ ?~ SwaggerObject
1030774 & oneOf ?~ (snd <$> schemas)
1031775 where
1032776 declareSumSchema = gsumToSchema opts proxy
1033777 (sumSchemas, All allNullary) = undeclare (runWriterT declareSumSchema)
1034778
1035779 toStringTag schemas = mempty
1036− & type_ ?~ OpenApiString
780+ & type_ ?~ SwaggerString
1037781 & enum_ ?~ map (String . fst) sumSchemas
1038782
1039783type AllNullary = All
@@ -1055,15 +799,15 @@ gsumConToSchemaWith ref opts _ = (tag, schema)
1055799 case ref of
1056800 -- If subschema is an object and constructor is a record, we add tag directly
1057801 -- to the record, as Aeson does it.
1058− Just (Inline sub) | sub ^. type_ == Just OpenApiObject && isRecord -> Inline $ sub
802+ Just (Inline sub) | sub ^. type_ == Just SwaggerObject && isRecord -> Inline $ sub
1059803 & required <>~ [T.pack tagField]
1060− & properties . at (T.pack tagField) ?~ (Inline $ mempty & type_ ?~ OpenApiString & enum_ ?~ [String tag])
804+ & properties . at (T.pack tagField) ?~ (Inline $ mempty & type_ ?~ SwaggerString & enum_ ?~ [String tag])
1061805
1062806 -- If it is not a record, we need to put subschema into "contents" field.
1063807 _ | not isRecord -> Inline $ mempty
1064− & type_ ?~ OpenApiObject
808+ & type_ ?~ SwaggerObject
1065809 & required .~ [T.pack tagField]
1066− & properties . at (T.pack tagField) ?~ (Inline $ mempty & type_ ?~ OpenApiString & enum_ ?~ [String tag])
810+ & properties . at (T.pack tagField) ?~ (Inline $ mempty & type_ ?~ SwaggerString & enum_ ?~ [String tag])
1067811 -- If constructor is nullary, there is no content.
1068812 & case ref of
1069813 Just r -> (properties . at (T.pack contentsField) ?~ r) . (required <>~ [T.pack contentsField])
@@ -1071,17 +815,17 @@ gsumConToSchemaWith ref opts _ = (tag, schema)
1071815
1072816 -- In the remaining cases we combine "tag" object and "contents" object using allOf.
1073817 _ -> Inline $ mempty
1074− & type_ ?~ OpenApiObject
818+ & type_ ?~ SwaggerObject
1075819 & allOf ?~ [Inline $ mempty
1076− & type_ ?~ OpenApiObject
820+ & type_ ?~ SwaggerObject
1077821 & required .~ (T.pack tagField : if isRecord then [] else [T.pack contentsField])
1078− & properties . at (T.pack tagField) ?~ (Inline $ mempty & type_ ?~ OpenApiString & enum_ ?~ [String tag])]
822+ & properties . at (T.pack tagField) ?~ (Inline $ mempty & type_ ?~ SwaggerString & enum_ ?~ [String tag])]
1079823 & if isRecord
1080824 then allOf . _Just <>~ [refOrNullary]
1081− else allOf . _Just <>~ [Inline $ mempty & type_ ?~ OpenApiObject & properties . at (T.pack contentsField) ?~ refOrNullary]
825+ else allOf . _Just <>~ [Inline $ mempty & type_ ?~ SwaggerObject & properties . at (T.pack contentsField) ?~ refOrNullary]
1082826 UntaggedValue -> refOrEnum -- Aeson encodes nullary constructors as strings in this case.
1083827 ObjectWithSingleField -> Inline $ mempty
1084− & type_ ?~ OpenApiObject
828+ & type_ ?~ SwaggerObject
1085829 & required .~ [tag]
1086830 & properties . at tag ?~ refOrNullary
1087831 TwoElemArray -> error "unrepresentable in OpenAPI 3"
@@ -1089,7 +833,7 @@ gsumConToSchemaWith ref opts _ = (tag, schema)
1089833 tag = T.pack (constructorTagModifier opts (conName (Proxy3 :: Proxy3 c f p)))
1090834 isRecord = conIsRecord (Proxy3 :: Proxy3 c f p)
1091835 refOrNullary = fromMaybe (Inline nullarySchema) ref
1092− refOrEnum = fromMaybe (Inline $ mempty & type_ ?~ OpenApiString & enum_ ?~ [String tag]) ref
836+ refOrEnum = fromMaybe (Inline $ mempty & type_ ?~ SwaggerString & enum_ ?~ [String tag]) ref
1093837
1094838gsumConToSchema :: (GToSchema (C1 c f), Constructor c) =>
1095839 SchemaOptions -> Proxy (C1 c f) -> Declare (Definitions Schema) [(T.Text, Referenced Schema)]
@@ -1114,13 +858,7 @@ data Proxy2 a b = Proxy2
1114858
1115859data Proxy3 a b c = Proxy3
1116860
1117−{- $setup
1118−>>> import Data.OpenApi
1119−>>> import Data.Aeson (encode)
1120−>>> import Data.Aeson.Types (toJSONKeyText)
1121−>>> import Data.OpenApi.Internal.Utils
1122−>>> :set -XScopedTypeVariables
1123−>>> :set -XDeriveAnyClass
1124−>>> :set -XStandaloneDeriving
1125−>>> :set -XTypeApplications
1126−-}
861+-- $setup
862+-- >>> import Data.Swagger
863+-- >>> import Data.Aeson (encode)
864+-- >>> import Data.Aeson.Types (toJSONKeyText)
src/Data/OpenApi/Internal/Schema/Validation.hs → src/Data/Swagger/Internal/Schema/Validation.hsrenamed+62−74
@@ -1,5 +1,4 @@
11{-# OPTIONS_GHC -Wall #-}
2−{-# LANGUAGE CPP #-}
32{-# LANGUAGE DataKinds #-}
43{-# LANGUAGE DeriveFunctor #-}
54{-# LANGUAGE FlexibleInstances #-}
@@ -15,14 +14,14 @@
1514{-# LANGUAGE UndecidableInstances #-}
1615{-# LANGUAGE ViewPatterns #-}
1716-- |
18−-- Module: Data.OpenApi.Internal.Schema.Validation
17+-- Module: Data.Swagger.Internal.Schema.Validation
1918-- Copyright: (c) 2015 GetShopTV
2019-- License: BSD3
2120-- Maintainer: Nickolay Kudasov <nickolay@getshoptv.com>
2221-- Stability: experimental
2322--
2423-- Validate JSON values with Swagger Schema.
25−module Data.OpenApi.Internal.Schema.Validation where
24+module Data.Swagger.Internal.Schema.Validation where
2625
2726import Prelude ()
2827import Prelude.Compat
@@ -32,14 +31,11 @@ import Control.Lens hiding (allOf)
3231import Control.Monad (forM, forM_, when)
3332
3433import Data.Aeson hiding (Result)
35−#if MIN_VERSION_aeson(2,0,0)
36−import qualified Data.Aeson.KeyMap as KeyMap
37−#endif
34+import Data.Aeson.Encode.Pretty (encodePretty)
3835import Data.Foldable (for_, sequenceA_,
3936 traverse_)
40−#if !MIN_VERSION_aeson(2,0,0)
4137import Data.HashMap.Strict (HashMap)
42−#endif
38+import qualified Data.HashMap.Strict as HashMap
4339import qualified Data.HashMap.Strict.InsOrd as InsOrdHashMap
4440import qualified "unordered-containers" Data.HashSet as HashSet
4541import Data.Maybe (fromMaybe)
@@ -52,12 +48,10 @@ import qualified Data.Text.Lazy.Encoding as TL
5248import Data.Vector (Vector)
5349import qualified Data.Vector as Vector
5450
55−import Data.OpenApi.Aeson.Compat (hasKey, keyToText, lookupKey, objectToList)
56−import Data.OpenApi.Declare
57−import Data.OpenApi.Internal
58−import Data.OpenApi.Internal.Schema
59−import Data.OpenApi.Internal.Utils
60−import Data.OpenApi.Lens
51+import Data.Swagger.Declare
52+import Data.Swagger.Internal
53+import Data.Swagger.Internal.Schema
54+import Data.Swagger.Lens
6155
6256-- | Validate @'ToJSON'@ instance matches @'ToSchema'@ for a given value.
6357-- This can be used with QuickCheck to ensure those instances are coherent:
@@ -109,33 +103,33 @@ validateToJSONWithPatternChecker checker = validateJSONWithPatternChecker checke
109103-- <BLANKLINE>
110104-- Swagger Schema:
111105-- {
112−-- "properties": {
113−-- "name": {
114−-- "type": "string"
115−-- },
116−-- "phone": {
117−-- "$ref": "#/components/schemas/Phone"
118−-- }
119−-- },
120106-- "required": [
121107-- "name",
122108-- "phone"
123109-- ],
124−-- "type": "object"
110+-- "type": "object",
111+-- "properties": {
112+-- "phone": {
113+-- "$ref": "#/components/schemas/Phone"
114+-- },
115+-- "name": {
116+-- "type": "string"
117+-- }
118+-- }
125119-- }
126120-- <BLANKLINE>
127121-- Swagger Description Context:
128122-- {
129123-- "Phone": {
124+-- "required": [
125+-- "value"
126+-- ],
127+-- "type": "object",
130128-- "properties": {
131129-- "value": {
132130-- "type": "string"
133131-- }
134−-- },
135−-- "required": [
136−-- "value"
137−-- ],
138−-- "type": "object"
132+-- }
139133-- }
140134-- }
141135-- <BLANKLINE>
@@ -321,11 +315,11 @@ validateNumber n = withConfig $ \_cfg -> withSchema $ \sch -> do
321315
322316 check maximum_ $ \m ->
323317 when (if exMax then (n >= m) else (n > m)) $
324− invalid ("value " ++ show n ++ " exceeds maximum (should be " ++ (if exMax then "<" else "<=") ++ show m ++ ")")
318+ invalid ("value " ++ show n ++ " exceeds maximum (should be " ++ if exMax then "<" else "<=" ++ show m ++ ")")
325319
326320 check minimum_ $ \m ->
327321 when (if exMin then (n <= m) else (n < m)) $
328− invalid ("value " ++ show n ++ " falls below minimum (should be " ++ (if exMin then ">" else ">=") ++ show m ++ ")")
322+ invalid ("value " ++ show n ++ " falls below minimum (should be " ++ if exMin then ">" else ">=" ++ show m ++ ")")
329323
330324 check multipleOf $ \k ->
331325 when (not (isInteger (n / k))) $
@@ -359,8 +353,8 @@ validateArray xs = do
359353 invalid ("array is too short (size should be >=" ++ show n ++ ")")
360354
361355 check items $ \case
362− OpenApiItemsObject itemSchema -> traverse_ (validateWithSchemaRef itemSchema) xs
363− OpenApiItemsArray itemSchemas -> do
356+ SwaggerItemsObject itemSchema -> traverse_ (validateWithSchemaRef itemSchema) xs
357+ SwaggerItemsArray itemSchemas -> do
364358 when (len /= length itemSchemas) $
365359 invalid ("array size is invalid (should be exactly " ++ show (length itemSchemas) ++ ")")
366360 sequenceA_ (zipWith validateWithSchemaRef itemSchemas (Vector.toList xs))
@@ -372,16 +366,10 @@ validateArray xs = do
372366 len = Vector.length xs
373367 allUnique = len == HashSet.size (HashSet.fromList (Vector.toList xs))
374368
375−validateObject ::
376−#if MIN_VERSION_aeson(2,0,0)
377− KeyMap.KeyMap Value
378−#else
379− HashMap Text Value
380−#endif
381− -> Validation Schema ()
369+validateObject :: HashMap Text Value -> Validation Schema ()
382370validateObject o = withSchema $ \sch ->
383371 case sch ^. discriminator of
384− Just (Discriminator pname types) -> case fromJSON <$> lookupKey pname o of
372+ Just (Discriminator pname types) -> case fromJSON <$> HashMap.lookup pname o of
385373 Just (Success pvalue) ->
386374 let ref = fromMaybe pvalue $ InsOrdHashMap.lookup pvalue types
387375 -- TODO ref may be name or reference
@@ -400,15 +388,15 @@ validateObject o = withSchema $ \sch ->
400388 validateRequired
401389 validateProps
402390 where
403− size = fromIntegral (length o)
391+ size = fromIntegral (HashMap.size o)
404392
405393 validateRequired = withSchema $ \sch -> traverse_ validateReq (sch ^. required)
406394 validateReq n =
407− when (not (hasKey n o)) $
395+ when (not (HashMap.member n o)) $
408396 invalid ("property " ++ show n ++ " is required, but not found in " ++ show (encode o))
409397
410398 validateProps = withSchema $ \sch -> do
411− for_ (objectToList o) $ \(keyToText -> k, v) ->
399+ for_ (HashMap.toList o) $ \(k, v) ->
412400 case v of
413401 Null | not (k `elem` (sch ^. required)) -> valid -- null is fine for non-required property
414402 _ ->
@@ -435,10 +423,10 @@ validateEnum val = do
435423-- This is like 'inferParamSchemaTypes', but also works for objects:
436424--
437425-- >>> inferSchemaTypes <$> decode "{\"minProperties\": 1}"
438−-- Just [OpenApiObject]
439−inferSchemaTypes :: Schema -> [OpenApiType]
426+-- Just [SwaggerObject]
427+inferSchemaTypes :: Schema -> [SwaggerType]
440428inferSchemaTypes sch = inferParamSchemaTypes sch ++
441− [ OpenApiObject | any ($ sch)
429+ [ SwaggerObject | any ($ sch)
442430 [ has (additionalProperties._Just)
443431 , has (maxProperties._Just)
444432 , has (minProperties._Just)
@@ -448,30 +436,30 @@ inferSchemaTypes sch = inferParamSchemaTypes sch ++
448436-- | Infer schema type based on used properties.
449437--
450438-- >>> inferSchemaTypes <$> decode "{\"minLength\": 2}"
451−-- Just [OpenApiString]
439+-- Just [SwaggerString]
452440--
453441-- >>> inferSchemaTypes <$> decode "{\"maxItems\": 0}"
454−-- Just [OpenApiArray]
442+-- Just [SwaggerArray]
455443--
456−-- From numeric properties 'OpenApiInteger' type is inferred.
457−-- If you want 'OpenApiNumber' instead, you must specify it explicitly.
444+-- From numeric properties 'SwaggerInteger' type is inferred.
445+-- If you want 'SwaggerNumber' instead, you must specify it explicitly.
458446--
459447-- >>> inferSchemaTypes <$> decode "{\"minimum\": 1}"
460−-- Just [OpenApiInteger]
461−inferParamSchemaTypes :: Schema -> [OpenApiType]
448+-- Just [SwaggerInteger]
449+inferParamSchemaTypes :: Schema -> [SwaggerType]
462450inferParamSchemaTypes sch = concat
463− [ [ OpenApiArray | any ($ sch)
451+ [ [ SwaggerArray | any ($ sch)
464452 [ has (items._Just)
465453 , has (maxItems._Just)
466454 , has (minItems._Just)
467455 , has (uniqueItems._Just) ] ]
468− , [ OpenApiInteger | any ($ sch)
456+ , [ SwaggerInteger | any ($ sch)
469457 [ has (exclusiveMaximum._Just)
470458 , has (exclusiveMinimum._Just)
471459 , has (maximum_._Just)
472460 , has (minimum_._Just)
473461 , has (multipleOf._Just) ] ]
474− , [ OpenApiString | any ($ sch)
462+ , [ SwaggerString | any ($ sch)
475463 [ has (maxLength._Just)
476464 , has (minLength._Just)
477465 , has (pattern._Just) ] ]
@@ -495,13 +483,13 @@ validateSchemaType val = withSchema $ \sch ->
495483
496484 _ ->
497485 case (sch ^. type_, val) of
498− (Just OpenApiNull, Null) -> valid
499− (Just OpenApiBoolean, Bool _) -> valid
500− (Just OpenApiInteger, Number n) -> validateInteger n
501− (Just OpenApiNumber, Number n) -> validateNumber n
502− (Just OpenApiString, String s) -> validateString s
503− (Just OpenApiArray, Array xs) -> validateArray xs
504− (Just OpenApiObject, Object o) -> validateObject o
486+ (Just SwaggerNull, Null) -> valid
487+ (Just SwaggerBoolean, Bool _) -> valid
488+ (Just SwaggerInteger, Number n) -> validateInteger n
489+ (Just SwaggerNumber, Number n) -> validateNumber n
490+ (Just SwaggerString, String s) -> validateString s
491+ (Just SwaggerArray, Array xs) -> validateArray xs
492+ (Just SwaggerObject, Object o) -> validateObject o
505493 (Nothing, Null) -> valid
506494 (Nothing, Bool _) -> valid
507495 -- Number by default
@@ -514,11 +502,11 @@ validateSchemaType val = withSchema $ \sch ->
514502validateParamSchemaType :: Value -> Validation Schema ()
515503validateParamSchemaType val = withSchema $ \sch ->
516504 case (sch ^. type_, val) of
517− (Just OpenApiBoolean, Bool _) -> valid
518− (Just OpenApiInteger, Number n) -> validateInteger n
519− (Just OpenApiNumber, Number n) -> validateNumber n
520− (Just OpenApiString, String s) -> validateString s
521− (Just OpenApiArray, Array xs) -> validateArray xs
505+ (Just SwaggerBoolean, Bool _) -> valid
506+ (Just SwaggerInteger, Number n) -> validateInteger n
507+ (Just SwaggerNumber, Number n) -> validateNumber n
508+ (Just SwaggerString, String s) -> validateString s
509+ (Just SwaggerArray, Array xs) -> validateArray xs
522510 (Nothing, Bool _) -> valid
523511 -- Number by default
524512 (Nothing, Number n) -> validateNumber n
@@ -526,11 +514,11 @@ validateParamSchemaType val = withSchema $ \sch ->
526514 (Nothing, Array xs) -> validateArray xs
527515 bad -> invalid $ "expected JSON value of type " ++ showType bad
528516
529−showType :: (Maybe OpenApiType, Value) -> String
517+showType :: (Maybe SwaggerType, Value) -> String
530518showType (Just ty, _) = show ty
531−showType (Nothing, Null) = "OpenApiNull"
532−showType (Nothing, Bool _) = "OpenApiBoolean"
533−showType (Nothing, Number _) = "OpenApiNumber"
534−showType (Nothing, String _) = "OpenApiString"
535−showType (Nothing, Array _) = "OpenApiArray"
536−showType (Nothing, Object _) = "OpenApiObject"
519+showType (Nothing, Null) = "SwaggerNull"
520+showType (Nothing, Bool _) = "SwaggerBoolean"
521+showType (Nothing, Number _) = "SwaggerNumber"
522+showType (Nothing, String _) = "SwaggerString"
523+showType (Nothing, Array _) = "SwaggerArray"
524+showType (Nothing, Object _) = "SwaggerObject"
src/Data/OpenApi/Internal/TypeShape.hs → src/Data/Swagger/Internal/TypeShape.hsrenamed+1−1
@@ -4,7 +4,7 @@
44{-# LANGUAGE TypeOperators #-}
55{-# LANGUAGE UndecidableInstances #-}
66
7−module Data.OpenApi.Internal.TypeShape where
7+module Data.Swagger.Internal.TypeShape where
88
99import Data.Proxy
1010import GHC.Generics
src/Data/OpenApi/Internal/Utils.hs → src/Data/Swagger/Internal/Utils.hsrenamed+1−6
@@ -4,7 +4,7 @@
44{-# LANGUAGE OverloadedStrings #-}
55{-# LANGUAGE RankNTypes #-}
66{-# LANGUAGE TypeOperators #-}
7−module Data.OpenApi.Internal.Utils where
7+module Data.Swagger.Internal.Utils where
88
99import Prelude ()
1010import Prelude.Compat
@@ -13,8 +13,6 @@ import Control.Lens ((&), (%~))
1313import Control.Lens.TH
1414import Data.Aeson
1515import Data.Aeson.Types
16−import qualified Data.Aeson.Encode.Pretty as P
17−import qualified Data.ByteString.Lazy as BSL
1816import Data.Char
1917import Data.Data
2018import Data.Hashable (Hashable)
@@ -134,6 +132,3 @@ instance SwaggerMonoid (Maybe a) where
134132 swaggerMempty = Nothing
135133 swaggerMappend x Nothing = x
136134 swaggerMappend _ y = y
137−
138−encodePretty :: ToJSON a => a -> BSL.ByteString
139−encodePretty = P.encodePretty' $ P.defConfig { P.confCompare = P.compare }
src/Data/OpenApi/Lens.hs → src/Data/Swagger/Lens.hsrenamed+20−20
@@ -10,23 +10,23 @@
1010{-# LANGUAGE UndecidableInstances #-}
1111{-# OPTIONS_GHC -fno-warn-orphans #-}
1212-- |
13−-- Module: Data.OpenApi.Lens
13+-- Module: Data.Swagger.Lens
1414-- Maintainer: Nickolay Kudasov <nickolay@getshoptv.com>
1515-- Stability: experimental
1616--
1717-- Lenses and prisms for Swagger.
18−module Data.OpenApi.Lens where
18+module Data.Swagger.Lens where
1919
2020import Control.Lens
2121import Data.Aeson (Value)
2222import Data.Scientific (Scientific)
23−import Data.OpenApi.Internal
24−import Data.OpenApi.Internal.Utils
23+import Data.Swagger.Internal
24+import Data.Swagger.Internal.Utils
2525import Data.Text (Text)
2626
2727-- * Classy lenses
2828
29−makeFields ''OpenApi
29+makeFields ''Swagger
3030makeFields ''Components
3131makeFields ''Server
3232makeFields ''RequestBody
@@ -64,24 +64,24 @@ makePrisms ''SecuritySchemeType
6464-- ** 'Referenced' prisms
6565makePrisms ''Referenced
6666
67−-- ** 'OpenApiItems' prisms
67+-- ** 'SwaggerItems' prisms
6868
69−_OpenApiItemsArray :: Review OpenApiItems [Referenced Schema]
70−_OpenApiItemsArray
71− = unto (\x -> OpenApiItemsArray x)
69+_SwaggerItemsArray :: Review SwaggerItems [Referenced Schema]
70+_SwaggerItemsArray
71+ = unto (\x -> SwaggerItemsArray x)
7272{- \x -> case x of
73− OpenApiItemsPrimitive c p -> Left (OpenApiItemsPrimitive c p)
74− OpenApiItemsObject o -> Left (OpenApiItemsObject o)
75− OpenApiItemsArray a -> Right a
73+ SwaggerItemsPrimitive c p -> Left (SwaggerItemsPrimitive c p)
74+ SwaggerItemsObject o -> Left (SwaggerItemsObject o)
75+ SwaggerItemsArray a -> Right a
7676-}
7777
78−_OpenApiItemsObject :: Review OpenApiItems (Referenced Schema)
79−_OpenApiItemsObject
80− = unto (\x -> OpenApiItemsObject x)
78+_SwaggerItemsObject :: Review SwaggerItems (Referenced Schema)
79+_SwaggerItemsObject
80+ = unto (\x -> SwaggerItemsObject x)
8181{- \x -> case x of
82− OpenApiItemsPrimitive c p -> Left (OpenApiItemsPrimitive c p)
83− OpenApiItemsObject o -> Right o
84− OpenApiItemsArray a -> Left (OpenApiItemsArray a)
82+ SwaggerItemsPrimitive c p -> Left (SwaggerItemsPrimitive c p)
83+ SwaggerItemsObject o -> Right o
84+ SwaggerItemsArray a -> Left (SwaggerItemsArray a)
8585-}
8686
8787-- =============================================================
@@ -99,7 +99,7 @@ instance At Responses where at n = responses . at n
9999instance Ixed Operation where ix n = responses . ix n
100100instance At Operation where at n = responses . at n
101101
102−instance HasType NamedSchema (Maybe OpenApiType) where type_ = schema.type_
102+instance HasType NamedSchema (Maybe SwaggerType) where type_ = schema.type_
103103
104104-- OVERLAPPABLE instances
105105
@@ -112,7 +112,7 @@ instance
112112instance
113113 {-# OVERLAPPABLE #-}
114114 HasSchema s Schema
115− => HasItems s (Maybe OpenApiItems) where
115+ => HasItems s (Maybe SwaggerItems) where
116116 items = schema.items
117117
118118instance
src/Data/OpenApi/Operation.hs → src/Data/Swagger/Operation.hsrenamed+29−136
@@ -1,13 +1,13 @@
11{-# LANGUAGE RankNTypes #-}
22-- |
3−-- Module: Data.OpenApi.Operation
3+-- Module: Data.Swagger.Operation
44-- Maintainer: Nickolay Kudasov <nickolay@getshoptv.com>
55-- Stability: experimental
66--
77-- Helper traversals and functions for Swagger operations manipulations.
88-- These might be useful when you already have Swagger specification
99-- generated by something else.
10−module Data.OpenApi.Operation (
10+module Data.Swagger.Operation (
1111 -- * Operation traversals
1212 allOperations,
1313 operationsOf,
@@ -42,10 +42,10 @@ import qualified Data.Set as Set
4242import Data.Text (Text)
4343import Network.HTTP.Media (MediaType)
4444
45−import Data.OpenApi.Declare
46−import Data.OpenApi.Internal
47−import Data.OpenApi.Lens
48−import Data.OpenApi.Schema
45+import Data.Swagger.Declare
46+import Data.Swagger.Internal
47+import Data.Swagger.Lens
48+import Data.Swagger.Schema
4949
5050import qualified Data.HashMap.Strict.InsOrd as InsOrdHashMap
5151import qualified Data.HashSet.InsOrd as InsOrdHS
@@ -55,17 +55,14 @@ import qualified Data.HashSet.InsOrd as InsOrdHS
5555-- >>> import Data.Proxy
5656-- >>> import Data.Time
5757-- >>> import qualified Data.ByteString.Lazy.Char8 as BSL
58−-- >>> import Data.OpenApi.Internal.Utils
5958
6059-- | Prepend path piece to all operations of the spec.
6160-- Leading and trailing slashes are trimmed/added automatically.
6261--
63−-- >>> let api = (mempty :: OpenApi) & paths .~ [("/info", mempty)]
64−-- >>> BSL.putStrLn $ encodePretty $ prependPath "user/{user_id}" api ^. paths
65−-- {
66−-- "/user/{user_id}/info": {}
67−-- }
68−prependPath :: FilePath -> OpenApi -> OpenApi
62+-- >>> let api = (mempty :: Swagger) & paths .~ [("/info", mempty)]
63+-- >>> BSL.putStrLn $ encode $ prependPath "user/{user_id}" api ^. paths
64+-- {"/user/{user_id}/info":{}}
65+prependPath :: FilePath -> Swagger -> Swagger
6966prependPath path = paths %~ InsOrdHashMap.mapKeys (path </>)
7067 where
7168 x </> y = case trim y of
@@ -75,7 +72,7 @@ prependPath path = paths %~ InsOrdHashMap.mapKeys (path </>)
7572 trim = dropWhile (== '/') . dropWhileEnd (== '/')
7673
7774-- | All operations of a Swagger spec.
78−allOperations :: Traversal' OpenApi Operation
75+allOperations :: Traversal' Swagger Operation
7976allOperations = paths.traverse.template
8077
8178-- | @'operationsOf' sub@ will traverse only those operations
@@ -83,66 +80,13 @@ allOperations = paths.traverse.template
8380-- by both path and method.
8481--
8582-- >>> let ok = (mempty :: Operation) & at 200 ?~ "OK"
86−-- >>> let api = (mempty :: OpenApi) & paths .~ [("/user", mempty & get ?~ ok & post ?~ ok)]
87−-- >>> let sub = (mempty :: OpenApi) & paths .~ [("/user", mempty & get ?~ mempty)]
88−-- >>> BSL.putStrLn $ encodePretty api
89−-- {
90−-- "components": {},
91−-- "info": {
92−-- "title": "",
93−-- "version": ""
94−-- },
95−-- "openapi": "3.0.0",
96−-- "paths": {
97−-- "/user": {
98−-- "get": {
99−-- "responses": {
100−-- "200": {
101−-- "description": "OK"
102−-- }
103−-- }
104−-- },
105−-- "post": {
106−-- "responses": {
107−-- "200": {
108−-- "description": "OK"
109−-- }
110−-- }
111−-- }
112−-- }
113−-- }
114−-- }
115−-- >>> BSL.putStrLn $ encodePretty $ api & operationsOf sub . at 404 ?~ "Not found"
116−-- {
117−-- "components": {},
118−-- "info": {
119−-- "title": "",
120−-- "version": ""
121−-- },
122−-- "openapi": "3.0.0",
123−-- "paths": {
124−-- "/user": {
125−-- "get": {
126−-- "responses": {
127−-- "200": {
128−-- "description": "OK"
129−-- },
130−-- "404": {
131−-- "description": "Not found"
132−-- }
133−-- }
134−-- },
135−-- "post": {
136−-- "responses": {
137−-- "200": {
138−-- "description": "OK"
139−-- }
140−-- }
141−-- }
142−-- }
143−-- }
144−-- }
145−operationsOf :: OpenApi -> Traversal' OpenApi Operation
83+-- >>> let api = (mempty :: Swagger) & paths .~ [("/user", mempty & get ?~ ok & post ?~ ok)]
84+-- >>> let sub = (mempty :: Swagger) & paths .~ [("/user", mempty & get ?~ mempty)]
85+-- >>> BSL.putStrLn $ encode api
86+-- {"openapi":"3.0.0","info":{"version":"","title":""},"paths":{"/user":{"get":{"responses":{"200":{"description":"OK"}}},"post":{"responses":{"200":{"description":"OK"}}}}},"components":{}}
87+-- >>> BSL.putStrLn $ encode $ api & operationsOf sub . at 404 ?~ "Not found"
88+-- {"openapi":"3.0.0","info":{"version":"","title":""},"paths":{"/user":{"get":{"responses":{"404":{"description":"Not found"},"200":{"description":"OK"}}},"post":{"responses":{"200":{"description":"OK"}}}}},"components":{}}
89+operationsOf :: Swagger -> Traversal' Swagger Operation
14690operationsOf sub = paths.itraversed.withIndex.subops
14791 where
14892 -- | Traverse operations that correspond to paths and methods of the sub API.
@@ -164,12 +108,12 @@ operationsOf sub = paths.itraversed.withIndex.subops
164108-- @
165109-- 'applyTags' = 'applyTagsFor' 'allOperations'
166110-- @
167−applyTags :: [Tag] -> OpenApi -> OpenApi
111+applyTags :: [Tag] -> Swagger -> Swagger
168112applyTags = applyTagsFor allOperations
169113
170114-- | Apply tags to a part of Swagger spec and update the global
171115-- list of tags.
172−applyTagsFor :: Traversal' OpenApi Operation -> [Tag] -> OpenApi -> OpenApi
116+applyTagsFor :: Traversal' Swagger Operation -> [Tag] -> Swagger -> Swagger
173117applyTagsFor ops ts swag = swag
174118 & ops . tags %~ (<> InsOrdHS.fromList (map _tagName ts))
175119 & tags %~ (<> InsOrdHS.fromList ts)
@@ -179,26 +123,8 @@ applyTagsFor ops ts swag = swag
179123--
180124-- FIXME doc
181125--
182−-- >>> BSL.putStrLn $ encodePretty $ runDeclare (declareResponse "application/json" (Proxy :: Proxy Day)) mempty
183−-- [
184−-- {
185−-- "Day": {
186−-- "example": "2016-07-22",
187−-- "format": "date",
188−-- "type": "string"
189−-- }
190−-- },
191−-- {
192−-- "content": {
193−-- "application/json": {
194−-- "schema": {
195−-- "$ref": "#/components/schemas/Day"
196−-- }
197−-- }
198−-- },
199−-- "description": ""
200−-- }
201−-- ]
126+-- >>> BSL.putStrLn $ encode $ runDeclare (declareResponse "application/json" (Proxy :: Proxy Day)) mempty
127+-- [{"Day":{"example":"2016-07-22","format":"date","type":"string"}},{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Day"}}}}]
202128declareResponse :: ToSchema a => MediaType -> Proxy a -> Declare (Definitions Schema) Response
203129declareResponse cType proxy = do
204130 s <- declareSchemaRef proxy
@@ -215,46 +141,13 @@ declareResponse cType proxy = do
215141--
216142-- Example:
217143--
218−-- >>> let api = (mempty :: OpenApi) & paths .~ [("/user", mempty & get ?~ mempty)]
144+-- >>> let api = (mempty :: Swagger) & paths .~ [("/user", mempty & get ?~ mempty)]
219145-- >>> let res = declareResponse "application/json" (Proxy :: Proxy Day)
220−-- >>> BSL.putStrLn $ encodePretty $ api & setResponse 200 res
221−-- {
222−-- "components": {
223−-- "schemas": {
224−-- "Day": {
225−-- "example": "2016-07-22",
226−-- "format": "date",
227−-- "type": "string"
228−-- }
229−-- }
230−-- },
231−-- "info": {
232−-- "title": "",
233−-- "version": ""
234−-- },
235−-- "openapi": "3.0.0",
236−-- "paths": {
237−-- "/user": {
238−-- "get": {
239−-- "responses": {
240−-- "200": {
241−-- "content": {
242−-- "application/json": {
243−-- "schema": {
244−-- "$ref": "#/components/schemas/Day"
245−-- }
246−-- }
247−-- },
248−-- "description": ""
249−-- }
250−-- }
251−-- }
252−-- }
253−-- }
254−-- }
146+-- >>> BSL.putStrLn $ encode $ api & setResponse 200 res
147+-- {"openapi":"3.0.0","info":{"version":"","title":""},"paths":{"/user":{"get":{"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Day"}}},"description":""}}}}},"components":{"schemas":{"Day":{"example":"2016-07-22","format":"date","type":"string"}}}}
255148--
256149-- See also @'setResponseWith'@.
257−setResponse :: HttpStatusCode -> Declare (Definitions Schema) Response -> OpenApi -> OpenApi
150+setResponse :: HttpStatusCode -> Declare (Definitions Schema) Response -> Swagger -> Swagger
258151setResponse = setResponseFor allOperations
259152
260153-- | Set or update response for all operations.
@@ -268,7 +161,7 @@ setResponse = setResponseFor allOperations
268161-- @
269162--
270163-- See also @'setResponse'@.
271−setResponseWith :: (Response -> Response -> Response) -> HttpStatusCode -> Declare (Definitions Schema) Response -> OpenApi -> OpenApi
164+setResponseWith :: (Response -> Response -> Response) -> HttpStatusCode -> Declare (Definitions Schema) Response -> Swagger -> Swagger
272165setResponseWith = setResponseForWith allOperations
273166
274167-- | Set response for specified operations.
@@ -277,7 +170,7 @@ setResponseWith = setResponseForWith allOperations
277170-- If the response already exists it will be overwritten.
278171--
279172-- See also @'setResponseForWith'@.
280−setResponseFor :: Traversal' OpenApi Operation -> HttpStatusCode -> Declare (Definitions Schema) Response -> OpenApi -> OpenApi
173+setResponseFor :: Traversal' Swagger Operation -> HttpStatusCode -> Declare (Definitions Schema) Response -> Swagger -> Swagger
281174setResponseFor ops code dres swag = swag
282175 & components.schemas %~ (<> defs)
283176 & ops . at code ?~ Inline res
@@ -291,7 +184,7 @@ setResponseFor ops code dres swag = swag
291184-- then just the new response is used.
292185--
293186-- See also @'setResponseFor'@.
294−setResponseForWith :: Traversal' OpenApi Operation -> (Response -> Response -> Response) -> HttpStatusCode -> Declare (Definitions Schema) Response -> OpenApi -> OpenApi
187+setResponseForWith :: Traversal' Swagger Operation -> (Response -> Response -> Response) -> HttpStatusCode -> Declare (Definitions Schema) Response -> Swagger -> Swagger
295188setResponseForWith ops f code dres swag = swag
296189 & components.schemas %~ (<> defs)
297190 & ops . at code %~ Just . Inline . combine
src/Data/OpenApi/Optics.hs → src/Data/Swagger/Optics.hsrenamed+29−74
@@ -7,7 +7,7 @@
77{-# LANGUAGE UndecidableInstances #-}
88{-# OPTIONS_GHC -fno-warn-orphans #-}
99-- |
10−-- Module: Data.OpenApi.Optics
10+-- Module: Data.Swagger.Optics
1111-- Maintainer: Andrzej Rybczak <andrzej@rybczak.net>
1212-- Stability: experimental
1313--
@@ -19,98 +19,53 @@
1919-- >>> :set -XOverloadedLabels
2020-- >>> import qualified Data.ByteString.Lazy.Char8 as BSL
2121--
22−-- Example from the "Data.OpenApi" module using @optics@:
22+-- Example from the "Data.Swagger" module using @optics@:
2323--
2424-- >>> :{
25−-- BSL.putStrLn $ encodePretty $ (mempty :: OpenApi)
26−-- & #components % #schemas .~ [ ("User", mempty & #type ?~ OpenApiString) ]
25+-- BSL.putStrLn $ encode $ (mempty :: Swagger)
26+-- & #components % #schemas .~ [ ("User", mempty & #type ?~ SwaggerString) ]
2727-- & #paths .~
2828-- [ ("/user", mempty & #get ?~ (mempty
2929-- & at 200 ?~ ("OK" & #_Inline % #content % at "application/json" ?~ (mempty & #schema ?~ Ref (Reference "User")))
3030-- & at 404 ?~ "User info not found")) ]
3131-- :}
32−-- {
33−-- "components": {
34−-- "schemas": {
35−-- "User": {
36−-- "type": "string"
37−-- }
38−-- }
39−-- },
40−-- "info": {
41−-- "title": "",
42−-- "version": ""
43−-- },
44−-- "openapi": "3.0.0",
45−-- "paths": {
46−-- "/user": {
47−-- "get": {
48−-- "responses": {
49−-- "200": {
50−-- "content": {
51−-- "application/json": {
52−-- "schema": {
53−-- "$ref": "#/components/schemas/User"
54−-- }
55−-- }
56−-- },
57−-- "description": "OK"
58−-- },
59−-- "404": {
60−-- "description": "User info not found"
61−-- }
62−-- }
63−-- }
64−-- }
65−-- }
66−-- }
32+-- {"openapi":"3.0.0","info":{"version":"","title":""},"paths":{"/user":{"get":{"responses":{"404":{"description":"User info not found"},"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/User"}}},"description":"OK"}}}}},"components":{"schemas":{"User":{"type":"string"}}}}
6733--
6834-- For convenience optics are defined as /labels/. It means that field accessor
6935-- names can be overloaded for different types. One such common field is
7036-- @#description@. Many components of a Swagger specification can have
7137-- descriptions, and you can use the same name for them:
7238--
73−-- >>> BSL.putStrLn $ encodePretty $ (mempty :: Response) & #description .~ "No content"
74−-- {
75−-- "description": "No content"
76−-- }
39+-- >>> BSL.putStrLn $ encode $ (mempty :: Response) & #description .~ "No content"
40+-- {"description":"No content"}
7741-- >>> :{
78−-- BSL.putStrLn $ encodePretty $ (mempty :: Schema)
79−-- & #type ?~ OpenApiBoolean
42+-- BSL.putStrLn $ encode $ (mempty :: Schema)
43+-- & #type ?~ SwaggerBoolean
8044-- & #description ?~ "To be or not to be"
8145-- :}
82−-- {
83−-- "description": "To be or not to be",
84−-- "type": "boolean"
85−-- }
46+-- {"type":"boolean","description":"To be or not to be"}
8647--
8748-- Additionally, to simplify working with @'Response'@, both @'Operation'@ and
8849-- @'Responses'@ have direct access to it via @'Optics.Core.At.at'@. Example:
8950--
9051-- >>> :{
91−-- BSL.putStrLn $ encodePretty $ (mempty :: Operation)
52+-- BSL.putStrLn $ encode $ (mempty :: Operation)
9253-- & at 404 ?~ "Not found"
9354-- :}
94−-- {
95−-- "responses": {
96−-- "404": {
97−-- "description": "Not found"
98−-- }
99−-- }
100−-- }
101−module Data.OpenApi.Optics () where
55+-- {"responses":{"404":{"description":"Not found"}}}
56+--
57+module Data.Swagger.Optics () where
10258
10359import Data.Aeson (Value)
10460import Data.Scientific (Scientific)
105−import Data.OpenApi.Internal
106−import Data.OpenApi.Internal.Utils
61+import Data.Swagger.Internal
10762import Data.Text (Text)
10863import Optics.Core
10964import Optics.TH
11065
11166-- Lenses
11267
113−makeFieldLabels ''OpenApi
68+makeFieldLabels ''Swagger
11469makeFieldLabels ''Components
11570makeFieldLabels ''Server
11671makeFieldLabels ''ServerVariable
@@ -148,30 +103,30 @@ makeFieldLabels ''Link
148103makePrismLabels ''SecuritySchemeType
149104makePrismLabels ''Referenced
150105
151−-- OpenApiItems prisms
106+-- SwaggerItems prisms
152107
153108instance
154109 ( a ~ [Referenced Schema]
155110 , b ~ [Referenced Schema]
156− ) => LabelOptic "_OpenApiItemsArray"
111+ ) => LabelOptic "_SwaggerItemsArray"
157112 A_Review
158− OpenApiItems
159− OpenApiItems
113+ SwaggerItems
114+ SwaggerItems
160115 a
161116 b where
162− labelOptic = unto (\x -> OpenApiItemsArray x)
117+ labelOptic = unto (\x -> SwaggerItemsArray x)
163118 {-# INLINE labelOptic #-}
164119
165120instance
166121 ( a ~ Referenced Schema
167122 , b ~ Referenced Schema
168− ) => LabelOptic "_OpenApiItemsObject"
123+ ) => LabelOptic "_SwaggerItemsObject"
169124 A_Review
170− OpenApiItems
171− OpenApiItems
125+ SwaggerItems
126+ SwaggerItems
172127 a
173128 b where
174− labelOptic = unto (\x -> OpenApiItemsObject x)
129+ labelOptic = unto (\x -> SwaggerItemsObject x)
175130 {-# INLINE labelOptic #-}
176131
177132-- =============================================================
@@ -200,8 +155,8 @@ instance At Operation where
200155-- #type
201156
202157instance
203− ( a ~ Maybe OpenApiType
204− , b ~ Maybe OpenApiType
158+ ( a ~ Maybe SwaggerType
159+ , b ~ Maybe SwaggerType
205160 ) => LabelOptic "type" A_Lens NamedSchema NamedSchema a b where
206161 labelOptic = #schema % #type
207162 {-# INLINE labelOptic #-}
@@ -225,8 +180,8 @@ instance
225180-- #items
226181
227182instance
228− ( a ~ Maybe OpenApiItems
229− , b ~ Maybe OpenApiItems
183+ ( a ~ Maybe SwaggerItems
184+ , b ~ Maybe SwaggerItems
230185 ) => LabelOptic "items" A_Lens NamedSchema NamedSchema a b where
231186 labelOptic = #schema % #items
232187 {-# INLINE labelOptic #-}
src/Data/OpenApi/ParamSchema.hs → src/Data/Swagger/ParamSchema.hsrenamed+4−4
@@ -1,10 +1,10 @@
11-- |
2−-- Module: Data.OpenApi.ParamSchema
2+-- Module: Data.Swagger.ParamSchema
33-- Maintainer: Nickolay Kudasov <nickolay@getshoptv.com>
44-- Stability: experimental
55--
66-- Types and functions for working with Swagger parameter schema.
7−module Data.OpenApi.ParamSchema (
7+module Data.Swagger.ParamSchema (
88 -- * Encoding
99 ToParamSchema(..),
1010
@@ -22,5 +22,5 @@ module Data.OpenApi.ParamSchema (
2222 defaultSchemaOptions,
2323) where
2424
25−import Data.OpenApi.Internal.ParamSchema
26−import Data.OpenApi.SchemaOptions
25+import Data.Swagger.Internal.ParamSchema
26+import Data.Swagger.SchemaOptions
src/Data/OpenApi/Schema.hs → src/Data/Swagger/Schema.hsrenamed+4−4
@@ -1,10 +1,10 @@
11-- |
2−-- Module: Data.OpenApi.Schema
2+-- Module: Data.Swagger.Schema
33-- Maintainer: Nickolay Kudasov <nickolay@getshoptv.com>
44-- Stability: experimental
55--
66-- Types and functions for working with Swagger schema.
7−module Data.OpenApi.Schema (
7+module Data.Swagger.Schema (
88 -- * Encoding
99 ToSchema(..),
1010 declareSchema,
@@ -48,5 +48,5 @@ module Data.OpenApi.Schema (
4848 fromAesonOptions,
4949) where
5050
51−import Data.OpenApi.Internal.Schema
52−import Data.OpenApi.SchemaOptions
51+import Data.Swagger.Internal.Schema
52+import Data.Swagger.SchemaOptions
src/Data/OpenApi/Schema/Generator.hs → src/Data/Swagger/Schema/Generator.hsrenamed+14−16
@@ -2,7 +2,7 @@
22{-# LANGUAGE OverloadedLists #-}
33{-# LANGUAGE ScopedTypeVariables #-}
44
5−module Data.OpenApi.Schema.Generator where
5+module Data.Swagger.Schema.Generator where
66
77import Prelude ()
88import Prelude.Compat
@@ -16,17 +16,15 @@ import Data.Maybe
1616import Data.Proxy
1717import Data.Scientific
1818import qualified Data.Set as S
19−import Data.OpenApi
20−import Data.OpenApi.Declare
21−import Data.OpenApi.Internal.Schema.Validation (inferSchemaTypes)
19+import Data.Swagger
20+import Data.Swagger.Declare
21+import Data.Swagger.Internal.Schema.Validation (inferSchemaTypes)
2222import qualified Data.Text as T
2323import qualified Data.Vector as V
2424import Test.QuickCheck (arbitrary)
2525import Test.QuickCheck.Gen
2626import Test.QuickCheck.Property
2727
28−import Data.OpenApi.Aeson.Compat (fromInsOrdHashMap)
29−
3028-- | Note: 'schemaGen' may 'error', if schema type is not specified,
3129-- and cannot be inferred.
3230schemaGen :: Definitions Schema -> Schema -> Gen Value
@@ -41,25 +39,25 @@ schemaGen defns schema =
4139 [ inferredType ] -> schemaGen defns (schema & type_ ?~ inferredType)
4240 -- Gen is not MonadFail
4341 _ -> error "unable to infer schema type"
44− Just OpenApiBoolean -> Bool <$> elements [True, False]
45− Just OpenApiNull -> pure Null
46− Just OpenApiNumber
42+ Just SwaggerBoolean -> Bool <$> elements [True, False]
43+ Just SwaggerNull -> pure Null
44+ Just SwaggerNumber
4745 | Just min <- schema ^. minimum_
4846 , Just max <- schema ^. maximum_ ->
4947 Number . fromFloatDigits <$>
5048 choose (toRealFloat min, toRealFloat max :: Double)
5149 | otherwise -> Number .fromFloatDigits <$> (arbitrary :: Gen Double)
52− Just OpenApiInteger
50+ Just SwaggerInteger
5351 | Just min <- schema ^. minimum_
5452 , Just max <- schema ^. maximum_ ->
5553 Number . fromInteger <$>
5654 choose (truncate min, truncate max)
5755 | otherwise -> Number . fromInteger <$> arbitrary
58− Just OpenApiArray
56+ Just SwaggerArray
5957 | Just 0 <- schema ^. maxLength -> pure $ Array V.empty
6058 | Just items <- schema ^. items ->
6159 case items of
62− OpenApiItemsObject ref -> do
60+ SwaggerItemsObject ref -> do
6361 size <- getSize
6462 let itemSchema = dereference defns ref
6563 minLength' = fromMaybe 0 $ fromInteger <$> schema ^. minItems
@@ -67,17 +65,17 @@ schemaGen defns schema =
6765 arrayLength <- choose (minLength', max minLength' maxLength')
6866 generatedArray <- vectorOf arrayLength $ schemaGen defns itemSchema
6967 return . Array $ V.fromList generatedArray
70− OpenApiItemsArray refs ->
68+ SwaggerItemsArray refs ->
7169 let itemGens = schemaGen defns . dereference defns <$> refs
7270 in fmap (Array . V.fromList) $ sequence itemGens
73− Just OpenApiString -> do
71+ Just SwaggerString -> do
7472 size <- getSize
7573 let minLength' = fromMaybe 0 $ fromInteger <$> schema ^. minLength
7674 let maxLength' = fromMaybe size $ fromInteger <$> schema ^. maxLength
7775 length <- choose (minLength', max minLength' maxLength')
7876 str <- vectorOf length arbitrary
7977 return . String $ T.pack str
80− Just OpenApiObject -> do
78+ Just SwaggerObject -> do
8179 size <- getSize
8280 let props = dereference defns <$> schema ^. properties
8381 reqKeys = S.fromList $ schema ^. required
@@ -97,7 +95,7 @@ schemaGen defns schema =
9795 return . M.fromList $ zip additionalKeys (repeat . schemaGen defns $ dereference defns addlSchema)
9896 _ -> return []
9997 x <- sequence $ gens <> additionalGens
100− return . Object $ fromInsOrdHashMap x
98+ return . Object $ M.toHashMap x
10199
102100dereference :: Definitions a -> Referenced a -> a
103101dereference _ (Inline a) = a
src/Data/OpenApi/Schema/Validation.hs → src/Data/Swagger/Schema/Validation.hsrenamed+7−7
@@ -1,10 +1,10 @@
11-- |
2−-- Module: Data.OpenApi.Schema.Validation
2+-- Module: Data.Swagger.Schema.Validation
33-- Maintainer: Nickolay Kudasov <nickolay@getshoptv.com>
44-- Stability: experimental
55--
66-- Validate JSON values with Swagger Schema.
7−module Data.OpenApi.Schema.Validation (
7+module Data.Swagger.Schema.Validation (
88 -- * How to use validation
99 -- $howto
1010
@@ -29,13 +29,13 @@ module Data.OpenApi.Schema.Validation (
2929 validateJSONWithPatternChecker,
3030) where
3131
32−import Data.OpenApi.Internal.Schema.Validation
32+import Data.Swagger.Internal.Schema.Validation
3333
3434-- $setup
3535-- >>> import Control.Lens
3636-- >>> import Data.Aeson
3737-- >>> import Data.Proxy
38−-- >>> import Data.OpenApi
38+-- >>> import Data.Swagger
3939-- >>> import GHC.Generics
4040-- >>> :set -XDeriveGeneric
4141
@@ -71,11 +71,11 @@ import Data.OpenApi.Internal.Schema.Validation
7171-- generally fails for @null@ JSON:
7272--
7373-- >>> validateToJSON (Nothing :: Maybe String)
74−-- ["expected JSON value of type OpenApiString"]
74+-- ["expected JSON value of type SwaggerString"]
7575-- >>> validateToJSON ([Just "hello", Nothing] :: [Maybe String])
76−-- ["expected JSON value of type OpenApiString"]
76+-- ["expected JSON value of type SwaggerString"]
7777-- >>> validateToJSON (123, Nothing :: Maybe String)
78−-- ["expected JSON value of type OpenApiString"]
78+-- ["expected JSON value of type SwaggerString"]
7979--
8080-- However, when @'Maybe' a@ is a type of a record field,
8181-- validation takes @'required'@ property of the @'Schema'@
src/Data/OpenApi/SchemaOptions.hs → src/Data/Swagger/SchemaOptions.hsrenamed+2−2
@@ -1,11 +1,11 @@
11{-# LANGUAGE RecordWildCards #-}
22-- |
3−-- Module: Data.OpenApi.SchemaOptions
3+-- Module: Data.Swagger.SchemaOptions
44-- Maintainer: Nickolay Kudasov <nickolay@getshoptv.com>
55-- Stability: experimental
66--
77-- Generic deriving options for @'ToParamSchema'@ and @'ToSchema'@.
8−module Data.OpenApi.SchemaOptions where
8+module Data.Swagger.SchemaOptions where
99
1010import qualified Data.Aeson.Types as Aeson
1111
stack.yaml+1−1
@@ -1,4 +1,4 @@
1−resolver: lts-16.31
1+resolver: lts-15.1
22packages:
33- '.'
44extra-deps:
test/Data/OpenApi/CommonTestTypes.hs → test/Data/Swagger/CommonTestTypes.hsrenamed+2−125
@@ -2,7 +2,7 @@
22{-# LANGUAGE QuasiQuotes #-}
33{-# LANGUAGE ScopedTypeVariables #-}
44
5−module Data.OpenApi.CommonTestTypes where
5+module Data.Swagger.CommonTestTypes where
66
77import Prelude ()
88import Prelude.Compat
@@ -18,7 +18,7 @@ import qualified Data.Text as Text
1818import Data.Word
1919import GHC.Generics
2020
21−import Data.OpenApi
21+import Data.Swagger
2222
2323-- ========================================================================
2424-- Unit type
@@ -863,129 +863,6 @@ singleMaybeFieldSchemaJSON = [aesonQQ|
863863}
864864|]
865865
866−-- ========================================================================
867−-- Natural Language (single field data with recursive fields)
868−-- ========================================================================
869−
870−data Predicate
871− = PredicateNoun Noun
872− | PredicateOmitted Omitted
873− deriving (Eq, Ord, Read, Show, Generic)
874−instance ToJSON Predicate
875−instance ToSchema Predicate
876−
877−data Noun
878− = Noun
879− { nounSurf :: LangWord
880− , nounModify :: [Modifier]
881− }
882− deriving (Eq, Ord, Read, Show, Generic)
883−instance ToJSON Noun
884−instance ToSchema Noun
885−
886−data LangWord
887− = LangWord
888− { langWordSurf :: String
889− , langWordBase :: String
890− }
891− deriving (Eq, Ord, Read, Show, Generic)
892−instance ToJSON LangWord
893−instance ToSchema LangWord
894−
895−data Modifier
896− = ModifierNoun Noun
897− | ModifierOmitted Omitted
898− deriving (Eq, Ord, Read, Show, Generic)
899−instance ToJSON Modifier
900−instance ToSchema Modifier
901−
902−newtype Omitted
903− = Omitted
904− { omittedModify :: [Modifier]
905− }
906− deriving (Eq, Ord, Read, Show, Generic)
907−instance ToJSON Omitted
908−instance ToSchema Omitted
909−
910−predicateSchemaDeclareJSON :: Value
911−predicateSchemaDeclareJSON = [aesonQQ|
912−[
913− {
914− "Predicate": {
915− "oneOf": [
916− {
917− "properties": {
918− "contents": { "$ref": "#/components/schemas/Noun" },
919− "tag": { "enum": ["PredicateNoun"], "type": "string" }
920− },
921− "required": ["tag", "contents"],
922− "type": "object"
923− },
924− {
925− "properties": {
926− "contents": { "$ref": "#/components/schemas/Omitted" },
927− "tag": { "enum": ["PredicateOmitted"], "type": "string" }
928− },
929− "required": ["tag", "contents"],
930− "type": "object"
931− }
932− ],
933− "type": "object"
934− },
935− "Noun": {
936− "properties": {
937− "nounModify": {
938− "items": { "$ref": "#/components/schemas/Modifier" },
939− "type": "array"
940− },
941− "nounSurf": { "$ref": "#/components/schemas/LangWord" }
942− },
943− "required": ["nounSurf", "nounModify"],
944− "type": "object"
945− },
946− "LangWord": {
947− "properties": {
948− "langWordBase": { "type": "string" },
949− "langWordSurf": { "type": "string" }
950− },
951− "required": ["langWordSurf", "langWordBase"],
952− "type": "object"
953− },
954− "Modifier": {
955− "oneOf": [
956− {
957− "properties": {
958− "contents": { "$ref": "#/components/schemas/Noun" },
959− "tag": { "enum": ["ModifierNoun"], "type": "string" }
960− },
961− "required": ["tag", "contents"],
962− "type": "object"
963− },
964− {
965− "properties": {
966− "contents": { "$ref": "#/components/schemas/Omitted" },
967− "tag": { "enum": ["ModifierOmitted"], "type": "string" }
968− },
969− "required": ["tag", "contents"],
970− "type": "object"
971− }
972− ],
973− "type": "object"
974− },
975− "Omitted": {
976− "properties": {
977− "omittedModify": {
978− "items": { "$ref": "#/components/schemas/Modifier" },
979− "type": "array"
980− }
981− },
982− "required": ["omittedModify"],
983− "type": "object"
984− }
985− },
986− { "$ref": "#/components/schemas/Predicate" }
987−]
988−|]
989866
990867-- ========================================================================
991868-- TimeOfDay
test/Data/OpenApi/ParamSchemaSpec.hs → test/Data/Swagger/ParamSchemaSpec.hsrenamed+3−3
@@ -4,7 +4,7 @@
44{-# LANGUAGE TemplateHaskell #-}
55{-# LANGUAGE QuasiQuotes #-}
66{-# LANGUAGE OverloadedStrings #-}
7−module Data.OpenApi.ParamSchemaSpec where
7+module Data.Swagger.ParamSchemaSpec where
88
99import Data.Aeson
1010import Data.Aeson.QQ.Simple
@@ -12,9 +12,9 @@ import Data.Char
1212import Data.Proxy
1313import GHC.Generics
1414
15−import Data.OpenApi
15+import Data.Swagger
1616
17−import Data.OpenApi.CommonTestTypes
17+import Data.Swagger.CommonTestTypes
1818import SpecCommon
1919import Test.Hspec
2020import Data.Time.LocalTime
test/Data/OpenApi/Schema/GeneratorSpec.hs → test/Data/Swagger/Schema/GeneratorSpec.hsrenamed+7−7
@@ -1,13 +1,13 @@
11{-# LANGUAGE OverloadedLists #-}
22{-# LANGUAGE OverloadedStrings #-}
33{-# LANGUAGE PackageImports #-}
4−module Data.OpenApi.Schema.GeneratorSpec where
4+module Data.Swagger.Schema.GeneratorSpec where
55
66import Prelude ()
77import Prelude.Compat
88
9−import Data.OpenApi
10−import Data.OpenApi.Schema.Generator
9+import Data.Swagger
10+import Data.Swagger.Schema.Generator
1111
1212import Control.Lens.Operators
1313import Data.Aeson
@@ -103,7 +103,7 @@ instance FromJSON WrongType where
103103instance ToSchema WrongType where
104104 declareNamedSchema _ = return . NamedSchema (Just "WrongType") $
105105 mempty
106− & type_ ?~ OpenApiObject
106+ & type_ ?~ SwaggerObject
107107
108108
109109data MissingRequired = MissingRequired
@@ -123,7 +123,7 @@ instance ToSchema MissingRequired where
123123 boolSchema <- declareSchemaRef (Proxy :: Proxy Bool)
124124 return . NamedSchema (Just "MissingRequired") $
125125 mempty
126− & type_ ?~ OpenApiObject
126+ & type_ ?~ SwaggerObject
127127 & properties .~ [("propA", stringSchema)
128128 ,("propB", boolSchema)
129129 ]
@@ -145,7 +145,7 @@ instance ToSchema MissingProperty where
145145 stringSchema <- declareSchemaRef (Proxy :: Proxy String)
146146 return . NamedSchema (Just "MissingProperty") $
147147 mempty
148− & type_ ?~ OpenApiObject
148+ & type_ ?~ SwaggerObject
149149 & properties .~ [("propC", stringSchema)]
150150 & required .~ ["propC"]
151151
@@ -163,6 +163,6 @@ instance ToSchema WrongPropType where
163163 boolSchema <- declareSchemaRef (Proxy :: Proxy Bool)
164164 return . NamedSchema (Just "WrongPropType") $
165165 mempty
166− & type_ ?~ OpenApiObject
166+ & type_ ?~ SwaggerObject
167167 & properties .~ [("propE", boolSchema)]
168168 & required .~ ["propE"]
test/Data/OpenApi/Schema/ValidationSpec.hs → test/Data/Swagger/Schema/ValidationSpec.hsrenamed+10−27
@@ -1,18 +1,13 @@
1−{-# LANGUAGE CPP #-}
21{-# LANGUAGE DeriveGeneric #-}
32{-# LANGUAGE PackageImports #-}
43{-# LANGUAGE RecordWildCards #-}
54{-# LANGUAGE ScopedTypeVariables #-}
65{-# OPTIONS_GHC -fno-warn-orphans #-}
7−module Data.OpenApi.Schema.ValidationSpec where
6+module Data.Swagger.Schema.ValidationSpec where
87
98import Control.Applicative
109import Control.Lens ((&), (.~), (?~))
1110import Data.Aeson
12−#if MIN_VERSION_aeson(2,0,0)
13−import qualified Data.Aeson.Key as Key
14−import qualified Data.Aeson.KeyMap as KeyMap
15−#endif
1611import Data.Aeson.Types
1712import Data.Hashable (Hashable)
1813import Data.HashMap.Strict (HashMap)
@@ -33,9 +28,8 @@ import Data.Version (Version)
3328import Data.Word
3429import GHC.Generics
3530
36−import Data.OpenApi
37−import Data.OpenApi.Declare
38−import Data.OpenApi.Aeson.Compat (stringToKey)
31+import Data.Swagger
32+import Data.Swagger.Declare
3933
4034import Test.Hspec
4135import Test.Hspec.QuickCheck
@@ -130,9 +124,9 @@ instance Arbitrary Person where
130124
131125invalidPersonToJSON :: Person -> Value
132126invalidPersonToJSON Person{..} = object
133− [ stringToKey "personName" .= toJSON name
134− , stringToKey "personPhone" .= toJSON phone
135− , stringToKey "personEmail" .= toJSON email
127+ [ T.pack "personName" .= toJSON name
128+ , T.pack "personPhone" .= toJSON phone
129+ , T.pack "personEmail" .= toJSON email
136130 ]
137131
138132-- ========================================================================
@@ -196,7 +190,7 @@ instance Arbitrary MyRoseTree where
196190data Light = NoLight | LightFreq Double | LightColor Color deriving (Show, Generic)
197191
198192instance ToSchema Light where
199− declareNamedSchema = genericDeclareNamedSchema defaultSchemaOptions { Data.OpenApi.sumEncoding = ObjectWithSingleField }
193+ declareNamedSchema = genericDeclareNamedSchema defaultSchemaOptions { Data.Swagger.sumEncoding = ObjectWithSingleField }
200194
201195instance ToJSON Light where
202196 toJSON = genericToJSON defaultOptions { Data.Aeson.Types.sumEncoding = ObjectWithSingleField }
@@ -221,7 +215,7 @@ instance ToJSON LightTaggedObject where
221215
222216instance ToSchema LightTaggedObject where
223217 declareNamedSchema _ =
224− genericDeclareNamedSchema defaultSchemaOptions { Data.OpenApi.sumEncoding = defaultTaggedObject } (Proxy :: Proxy Light)
218+ genericDeclareNamedSchema defaultSchemaOptions { Data.Swagger.sumEncoding = defaultTaggedObject } (Proxy :: Proxy Light)
225219
226220instance Arbitrary LightTaggedObject where
227221 arbitrary = LightTaggedObject <$> arbitrary
@@ -234,7 +228,7 @@ instance ToJSON LightUntaggedValue where
234228
235229instance ToSchema LightUntaggedValue where
236230 declareNamedSchema _ =
237− genericDeclareNamedSchema defaultSchemaOptions { Data.OpenApi.sumEncoding = UntaggedValue } (Proxy :: Proxy Light)
231+ genericDeclareNamedSchema defaultSchemaOptions { Data.Swagger.sumEncoding = UntaggedValue } (Proxy :: Proxy Light)
238232
239233instance Arbitrary LightUntaggedValue where
240234 arbitrary = LightUntaggedValue <$> arbitrary
@@ -283,7 +277,7 @@ instance ToJSON FreeForm where
283277
284278instance ToSchema FreeForm where
285279 declareNamedSchema _ = pure $ NamedSchema (Just $ T.pack "FreeForm") $ mempty
286− & type_ ?~ OpenApiObject
280+ & type_ ?~ SwaggerObject
287281 & additionalProperties ?~ AdditionalPropertiesAllowed True
288282
289283instance Arbitrary FreeForm where
@@ -301,8 +295,6 @@ instance Eq ZonedTime where
301295-- Arbitrary instance for Data.Aeson.Value
302296-- ========================================================================
303297
304−-- These instances were introduces in aeson upstream in 2.0.3
305−#if !MIN_VERSION_aeson(2,0,3)
306298instance Arbitrary Value where
307299 -- Weights are almost random
308300 -- Uniform oneof tends not to build complex objects cause of recursive call.
@@ -313,12 +305,3 @@ instance Arbitrary Value where
313305 , (3, Number <$> arbitrary)
314306 , (3, Bool <$> arbitrary)
315307 , (1, return Null) ]
316−
317−#if MIN_VERSION_aeson(2,0,0)
318−instance Arbitrary v => Arbitrary (KeyMap.KeyMap v) where
319− arbitrary = KeyMap.fromList <$> arbitrary
320−
321−instance Arbitrary Key.Key where
322− arbitrary = Key.fromText <$> arbitrary
323−#endif
324−#endif
test/Data/OpenApi/SchemaSpec.hs → test/Data/Swagger/SchemaSpec.hsrenamed+4−8
@@ -2,7 +2,7 @@
22{-# LANGUAGE ScopedTypeVariables #-}
33{-# LANGUAGE TemplateHaskell #-}
44{-# LANGUAGE QuasiQuotes #-}
5−module Data.OpenApi.SchemaSpec where
5+module Data.Swagger.SchemaSpec where
66
77import Prelude ()
88import Prelude.Compat
@@ -14,10 +14,10 @@ import Data.Proxy
1414import Data.Set (Set)
1515import qualified Data.Text as Text
1616
17−import Data.OpenApi
18−import Data.OpenApi.Declare
17+import Data.Swagger
18+import Data.Swagger.Declare
1919
20−import Data.OpenApi.CommonTestTypes
20+import Data.Swagger.CommonTestTypes
2121import SpecCommon
2222import Test.Hspec
2323
@@ -59,9 +59,6 @@ checkInlinedRecSchema proxy js = inlineNonRecursiveSchemas defs s <=> js
5959 where
6060 (defs, s) = runDeclare (declareSchema proxy) mempty
6161
62−checkToSchemaDeclare :: (HasCallStack, ToSchema a) => Proxy a -> Value -> Spec
63−checkToSchemaDeclare proxy js = runDeclare (declareSchemaRef proxy) mempty <=> js
64−
6562spec :: Spec
6663spec = do
6764 describe "Generic ToSchema" $ do
@@ -81,7 +78,6 @@ spec = do
8178 context "UserId (non-record newtype)" $ checkToSchema (Proxy :: Proxy UserId) userIdSchemaJSON
8279 context "Player (unary record)" $ checkToSchema (Proxy :: Proxy Player) playerSchemaJSON
8380 context "SingleMaybeField (unary record with Maybe)" $ checkToSchema (Proxy :: Proxy SingleMaybeField) singleMaybeFieldSchemaJSON
84− context "Natural Language (single field data with recursive fields)" $ checkToSchemaDeclare (Proxy :: Proxy Predicate) predicateSchemaDeclareJSON
8581 context "Players (inlining schema)" $ checkToSchema (Proxy :: Proxy Players) playersSchemaJSON
8682 context "MyRoseTree (datatypeNameModifier)" $ checkToSchema (Proxy :: Proxy MyRoseTree) myRoseTreeSchemaJSON
8783 context "MyRoseTree' (datatypeNameModifier)" $ checkToSchema (Proxy :: Proxy MyRoseTree') myRoseTreeSchemaJSON'
test/Data/OpenApiSpec.hs → test/Data/SwaggerSpec.hsrenamed+36−52
@@ -2,7 +2,7 @@
22{-# LANGUAGE OverloadedStrings #-}
33{-# LANGUAGE ScopedTypeVariables #-}
44{-# LANGUAGE QuasiQuotes #-}
5−module Data.OpenApiSpec where
5+module Data.SwaggerSpec where
66
77import Prelude ()
88import Prelude.Compat
@@ -15,7 +15,7 @@ import Data.HashMap.Strict (HashMap)
1515import qualified Data.HashSet.InsOrd as InsOrdHS
1616import Data.Text (Text)
1717
18−import Data.OpenApi
18+import Data.Swagger
1919import SpecCommon
2020import Test.Hspec hiding (example)
2121
@@ -42,13 +42,9 @@ spec = do
4242 context "Todo Example" $ swaggerExample <=> swaggerExampleJSON
4343 context "PetStore Example" $ do
4444 it "decodes successfully" $ do
45− fromJSON petstoreExampleJSON `shouldSatisfy` (\x -> case x of Success (_ :: OpenApi) -> True; _ -> False)
45+ fromJSON petstoreExampleJSON `shouldSatisfy` (\x -> case x of Success (_ :: Swagger) -> True; _ -> False)
4646 it "roundtrips: fmap toJSON . fromJSON" $ do
47− (toJSON :: OpenApi -> Value) <$> fromJSON petstoreExampleJSON `shouldBe` Success petstoreExampleJSON
48− context "Security schemes" $ do
49− it "merged correctly" $ do
50− let merged = oAuth2SecurityDefinitionsReadOpenApi <> oAuth2SecurityDefinitionsWriteOpenApi
51− merged `shouldBe` oAuth2SecurityDefinitionsOpenApi
47+ (toJSON :: Swagger -> Value) <$> fromJSON petstoreExampleJSON `shouldBe` Success petstoreExampleJSON
5248
5349main :: IO ()
5450main = hspec spec
@@ -136,15 +132,15 @@ operationExample = mempty
136132 & description ?~ "ID of pet that needs to be updated"
137133 & required ?~ True
138134 & in_ .~ ParamPath
139− & schema ?~ Inline (mempty & type_ ?~ OpenApiString))]
135+ & schema ?~ Inline (mempty & type_ ?~ SwaggerString))]
140136 & requestBody ?~ Inline (
141137 mempty & content . at "application/x-www-form-urlencoded" ?~ (mempty & schema ?~ (Inline (mempty
142138 & properties . at "petId" ?~ Inline (mempty
143139 & description ?~ "Updated name of the pet"
144− & type_ ?~ OpenApiString)
140+ & type_ ?~ SwaggerString)
145141 & properties . at "status" ?~ Inline (mempty
146142 & description ?~ "Updated status of the pet"
147− & type_ ?~ OpenApiString)))))
143+ & type_ ?~ SwaggerString)))))
148144 & at 200 ?~ "Pet updated."
149145 & at 405 ?~ "Invalid input"
150146 & security .~ [SecurityRequirement [("petstore_auth", ["write:pets", "read:pets"])]]
@@ -212,7 +208,7 @@ operationExampleJSON = [aesonQQ|
212208
213209schemaPrimitiveExample :: Schema
214210schemaPrimitiveExample = mempty
215− & type_ ?~ OpenApiString
211+ & type_ ?~ SwaggerString
216212 & format ?~ "email"
217213
218214schemaPrimitiveExampleJSON :: Value
@@ -225,14 +221,14 @@ schemaPrimitiveExampleJSON = [aesonQQ|
225221
226222schemaSimpleModelExample :: Schema
227223schemaSimpleModelExample = mempty
228− & type_ ?~ OpenApiObject
224+ & type_ ?~ SwaggerObject
229225 & required .~ [ "name" ]
230226 & properties .~
231− [ ("name", Inline (mempty & type_ ?~ OpenApiString))
227+ [ ("name", Inline (mempty & type_ ?~ SwaggerString))
232228 , ("address", Ref (Reference "Address"))
233229 , ("age", Inline $ mempty
234230 & minimum_ ?~ 0
235− & type_ ?~ OpenApiInteger
231+ & type_ ?~ SwaggerInteger
236232 & format ?~ "int32" ) ]
237233
238234schemaSimpleModelExampleJSON :: Value
@@ -257,8 +253,8 @@ schemaSimpleModelExampleJSON = [aesonQQ|
257253
258254schemaModelDictExample :: Schema
259255schemaModelDictExample = mempty
260− & type_ ?~ OpenApiObject
261− & additionalProperties ?~ AdditionalPropertiesSchema (Inline (mempty & type_ ?~ OpenApiString))
256+ & type_ ?~ SwaggerObject
257+ & additionalProperties ?~ AdditionalPropertiesSchema (Inline (mempty & type_ ?~ SwaggerString))
262258
263259schemaModelDictExampleJSON :: Value
264260schemaModelDictExampleJSON = [aesonQQ|
@@ -272,7 +268,7 @@ schemaModelDictExampleJSON = [aesonQQ|
272268
273269schemaAdditionalExample :: Schema
274270schemaAdditionalExample = mempty
275− & type_ ?~ OpenApiObject
271+ & type_ ?~ SwaggerObject
276272 & additionalProperties ?~ AdditionalPropertiesAllowed True
277273
278274schemaAdditionalExampleJSON :: Value
@@ -285,13 +281,13 @@ schemaAdditionalExampleJSON = [aesonQQ|
285281
286282schemaWithExampleExample :: Schema
287283schemaWithExampleExample = mempty
288− & type_ ?~ OpenApiObject
284+ & type_ ?~ SwaggerObject
289285 & properties .~
290286 [ ("id", Inline $ mempty
291− & type_ ?~ OpenApiInteger
287+ & type_ ?~ SwaggerInteger
292288 & format ?~ "int64" )
293289 , ("name", Inline $ mempty
294− & type_ ?~ OpenApiString) ]
290+ & type_ ?~ SwaggerString) ]
295291 & required .~ [ "name" ]
296292 & example ?~ [aesonQQ|
297293 {
@@ -330,19 +326,19 @@ schemaWithExampleExampleJSON = [aesonQQ|
330326definitionsExample :: HashMap Text Schema
331327definitionsExample =
332328 [ ("Category", mempty
333− & type_ ?~ OpenApiObject
329+ & type_ ?~ SwaggerObject
334330 & properties .~
335331 [ ("id", Inline $ mempty
336− & type_ ?~ OpenApiInteger
332+ & type_ ?~ SwaggerInteger
337333 & format ?~ "int64")
338− , ("name", Inline (mempty & type_ ?~ OpenApiString)) ] )
334+ , ("name", Inline (mempty & type_ ?~ SwaggerString)) ] )
339335 , ("Tag", mempty
340− & type_ ?~ OpenApiObject
336+ & type_ ?~ SwaggerObject
341337 & properties .~
342338 [ ("id", Inline $ mempty
343− & type_ ?~ OpenApiInteger
339+ & type_ ?~ SwaggerInteger
344340 & format ?~ "int64")
345− , ("name", Inline (mempty & type_ ?~ OpenApiString)) ] ) ]
341+ , ("name", Inline (mempty & type_ ?~ SwaggerString)) ] ) ]
346342
347343definitionsExampleJSON :: Value
348344definitionsExampleJSON = [aesonQQ|
@@ -386,7 +382,7 @@ paramsDefinitionExample =
386382 & required ?~ True
387383 & in_ .~ ParamQuery
388384 & schema ?~ Inline (mempty
389− & type_ ?~ OpenApiInteger
385+ & type_ ?~ SwaggerInteger
390386 & format ?~ "int32" ))
391387 , ("limitParam", mempty
392388 & name .~ "limit"
@@ -394,7 +390,7 @@ paramsDefinitionExample =
394390 & required ?~ True
395391 & in_ .~ ParamQuery
396392 & schema ?~ Inline (mempty
397− & type_ ?~ OpenApiInteger
393+ & type_ ?~ SwaggerInteger
398394 & format ?~ "int32" )) ]
399395
400396paramsDefinitionExampleJSON :: Value
@@ -445,7 +441,7 @@ responsesDefinitionExampleJSON = [aesonQQ|
445441|]
446442
447443-- =======================================================================
448−-- Security Definition object
444+-- Responses Definition object
449445-- =======================================================================
450446
451447securityDefinitionsExample :: SecurityDefinitions
@@ -531,23 +527,11 @@ oAuth2SecurityDefinitionsExampleJSON = [aesonQQ|
531527}
532528|]
533529
534−oAuth2SecurityDefinitionsReadOpenApi :: OpenApi
535−oAuth2SecurityDefinitionsReadOpenApi =
536− mempty & components . securitySchemes .~ oAuth2SecurityDefinitionsReadExample
537−
538−oAuth2SecurityDefinitionsWriteOpenApi :: OpenApi
539−oAuth2SecurityDefinitionsWriteOpenApi =
540− mempty & components . securitySchemes .~ oAuth2SecurityDefinitionsWriteExample
541−
542−oAuth2SecurityDefinitionsOpenApi :: OpenApi
543−oAuth2SecurityDefinitionsOpenApi =
544− mempty & components . securitySchemes .~ oAuth2SecurityDefinitionsExample
545−
546530-- =======================================================================
547531-- Swagger object
548532-- =======================================================================
549533
550−emptyPathsFieldExample :: OpenApi
534+emptyPathsFieldExample :: Swagger
551535emptyPathsFieldExample = mempty
552536
553537emptyPathsFieldExampleJSON :: Value
@@ -560,7 +544,7 @@ emptyPathsFieldExampleJSON = [aesonQQ|
560544}
561545|]
562546
563−swaggerExample :: OpenApi
547+swaggerExample :: Swagger
564548swaggerExample = mempty
565549 -- & basePath ?~ "/"
566550 -- & schemes ?~ [Http]
@@ -575,7 +559,7 @@ swaggerExample = mempty
575559 & description .~ "OK"
576560 & content . at "application/json" ?~ (mempty
577561 & schema ?~ Inline (mempty
578− & type_ ?~ OpenApiObject
562+ & type_ ?~ SwaggerObject
579563 & example ?~ [aesonQQ|
580564 {
581565 "created": 100,
@@ -584,9 +568,9 @@ swaggerExample = mempty
584568 & description ?~ "This is some real Todo right here"
585569 & properties .~
586570 [ ("created", Inline $ mempty
587− & type_ ?~ OpenApiInteger
571+ & type_ ?~ SwaggerInteger
588572 & format ?~ "int32")
589− , ("description", Inline (mempty & type_ ?~ OpenApiString))])))
573+ , ("description", Inline (mempty & type_ ?~ SwaggerString))])))
590574 & parameters .~
591575 [ Inline $ mempty
592576 & required ?~ True
@@ -594,7 +578,7 @@ swaggerExample = mempty
594578 & description ?~ "TodoId param"
595579 & in_ .~ ParamPath
596580 & schema ?~ Inline (mempty
597− & type_ ?~ OpenApiString ) ]
581+ & type_ ?~ SwaggerString ) ]
598582 & tags .~ InsOrdHS.fromList [ "todo" ] ))
599583
600584swaggerExampleJSON :: Value
@@ -933,14 +917,14 @@ petstoreExampleJSON = [aesonQQ|
933917
934918compositionSchemaExample :: Schema
935919compositionSchemaExample = mempty
936− & type_ ?~ OpenApiObject
937− & Data.OpenApi.allOf ?~ [
920+ & type_ ?~ SwaggerObject
921+ & Data.Swagger.allOf ?~ [
938922 Ref (Reference "Other")
939923 , Inline (mempty
940− & type_ ?~ OpenApiObject
924+ & type_ ?~ SwaggerObject
941925 & properties .~
942926 [ ("greet", Inline $ mempty
943− & type_ ?~ OpenApiString) ])
927+ & type_ ?~ SwaggerString) ])
944928 ]
945929
946930compositionSchemaExampleJSON :: Value
test/SpecCommon.hs+8
@@ -8,6 +8,14 @@ import qualified Data.Vector as Vector
88
99import Test.Hspec
1010
11+isSubJSON :: Value -> Value -> Bool
12+isSubJSON Null _ = True
13+isSubJSON (Object x) (Object y) = HashMap.keys x == HashMap.keys i && F.and i
14+ where
15+ i = HashMap.intersectionWith isSubJSON x y
16+isSubJSON (Array xs) (Array ys) = Vector.length xs == Vector.length ys && F.and (Vector.zipWith isSubJSON xs ys)
17+isSubJSON x y = x == y
18+
1119(<=>) :: (Eq a, Show a, ToJSON a, FromJSON a, HasCallStack) => a -> Value -> Spec
1220x <=> js = do
1321 it "encodes correctly" $ do