diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 000000000..dd84ea782 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,38 @@ +--- +name: Bug report +about: Create a report to help us improve +title: '' +labels: '' +assignees: '' + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +Steps to reproduce the behavior: +1. Go to '...' +2. Click on '....' +3. Scroll down to '....' +4. See error + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Screenshots** +If applicable, add screenshots to help explain your problem. + +**Desktop (please complete the following information):** + - OS: [e.g. iOS] + - Browser [e.g. chrome, safari] + - Version [e.g. 22] + +**Smartphone (please complete the following information):** + - Device: [e.g. iPhone6] + - OS: [e.g. iOS8.1] + - Browser [e.g. stock browser, safari] + - Version [e.g. 22] + +**Additional context** +Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 000000000..bbcbbe7d6 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,20 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: '' +labels: '' +assignees: '' + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/.github/workflows/pr_checks.yml b/.github/workflows/pr_checks.yml index 088741c95..1891fdb64 100644 --- a/.github/workflows/pr_checks.yml +++ b/.github/workflows/pr_checks.yml @@ -5,40 +5,33 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - - name: Set up JDK 11 + - name: Set up JDK 17 uses: actions/setup-java@v2 with: distribution: 'adopt' - java-version: '11' - - name: Cache Gradle packages - uses: actions/cache@v2 + java-version: '17' + - name: Lint + uses: burrunan/gradle-cache-action@v1 with: - path: ~/.gradle/caches - key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle.kts') }} - restore-keys: ${{ runner.os }}-gradle - - name: Lint using detekt - run: ./gradlew detekt + gradle-version: wrapper + arguments: detekt + properties: | + org.gradle.vfs.watch=false + org.gradle.vfs.verbose=false unit: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - - name: Set up JDK 11 + - name: Set up JDK 17 uses: actions/setup-java@v2 with: distribution: 'adopt' - java-version: '11' - - name: Cache Gradle packages - uses: actions/cache@v2 + java-version: '17' + - name: Unit Tests + uses: burrunan/gradle-cache-action@v1 with: - path: ~/.gradle/caches - key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle.kts') }} - restore-keys: ${{ runner.os }}-gradle - - name: Assemble with Gradle - run: ./gradlew assemble - - name: Run Unit Tests - run: ./gradlew test - - name: Cache Coverage Results - uses: actions/cache@v2 - with: - path: ./**/build/reports/jacoco - key: ${{ runner.os }}-unit-${{ env.GITHUB_SHA }} + gradle-version: wrapper + arguments: test koverCollectReports + properties: | + org.gradle.vfs.watch=false + org.gradle.vfs.verbose=false diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 901052b15..d47688c5c 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -13,34 +13,14 @@ jobs: - uses: actions/setup-java@v2 with: distribution: 'adopt' - java-version: '11' - - name: Cache Gradle packages - uses: actions/cache@v2 + java-version: '17' + - name: Publish to GitHub Packages + uses: burrunan/gradle-cache-action@v1 with: - path: ~/.gradle/caches - key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle.kts') }} - restore-keys: ${{ runner.os }}-gradle - - name: Publish package - run: ./gradlew publishAllPublicationsToGithubPackagesRepository + gradle-version: wrapper + arguments: publishAllPublicationsToGithubPackagesRepository + properties: | + org.gradle.vfs.watch=false + org.gradle.vfs.verbose=false env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - code-coverage: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - uses: actions/setup-java@v2 - with: - distribution: 'adopt' - java-version: '11' - - name: Cache Gradle packages - uses: actions/cache@v2 - with: - path: ~/.gradle/caches - key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle.kts') }} - restore-keys: ${{ runner.os }}-gradle - - name: Run Unit Tests - run: ./gradlew test - - name: Publish code coverage to Codacy - uses: codacy/codacy-coverage-reporter-action@v1 - with: - project-token: ${{ secrets.CODACY_PROJECT_TOKEN }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 92b53a23d..32f8c258f 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -15,15 +15,16 @@ jobs: - uses: actions/setup-java@v2 with: distribution: 'adopt' - java-version: '11' - - name: Cache Gradle packages - uses: actions/cache@v2 + java-version: '17' + - name: Publish to GitHub Packages + uses: burrunan/gradle-cache-action@v1 with: - path: ~/.gradle/caches - key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle.kts') }} - restore-keys: ${{ runner.os }}-gradle - - name: Publish packages to Github - run: ./gradlew publishAllPublicationsToGithubPackagesRepository -Prelease=true + gradle-version: wrapper + arguments: publishAllPublicationsToGithubPackagesRepository + properties: | + release=true + org.gradle.vfs.watch=false + org.gradle.vfs.verbose=false env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} publish-to-nexus: @@ -33,15 +34,13 @@ jobs: - uses: actions/setup-java@v2 with: distribution: 'adopt' - java-version: '11' - - name: Cache Gradle packages - uses: actions/cache@v2 + java-version: '17' + - name: Publlish to GithubPackages + uses: burrunan/gradle-cache-action@v1 with: - path: ~/.gradle/caches - key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle.kts') }} - restore-keys: ${{ runner.os }}-gradle - - name: Publish packages to Github - run: ./gradlew publishToSonatype closeAndReleaseSonatypeStagingRepository -Prelease=true - env: - ORG_GRADLE_PROJECT_sonatypeUsername: ${{ secrets.SONATYPE_USER }} - ORG_GRADLE_PROJECT_sonatypePassword: ${{ secrets.SONATYPE_PASSWORD }} + gradle-version: wrapper + arguments: publishToSonatype closeAndReleaseSonatypeStagingRepository + properties: | + release=true + org.gradle.vfs.watch=false + org.gradle.vfs.verbose=false diff --git a/.gitignore b/.gitignore index 1f93dfcff..43a50b842 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,5 @@ -# Ignore Gradle project-specific cache directory .gradle - -# Ignore Gradle build output directory build - .idea +dokka +wiki diff --git a/.tool-versions b/.tool-versions deleted file mode 100644 index b76921ca0..000000000 --- a/.tool-versions +++ /dev/null @@ -1,3 +0,0 @@ -kotlin 1.5.0-M2 -java openjdk-14.0.1 -gradle 7.0 diff --git a/CHANGELOG.md b/CHANGELOG.md index 69ea5d186..e32d80c30 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,59 @@ # Changelog +## Unreleased +### Added + +### Changed + +### Remove + +--- + +## Released + +## [2.0.0-alpha] - January 2nd, 2021 +### Added +- Support for OAuth authentication +- Gradle Toolchain feature to ensure match between local JDK and compile target +- Dokka integration +- Post-processing callback hook +- `description` key to KompendiumField +- Set of base constraints for simple and formatted types +- Ability to document expected unstructured data + +### Changed +- `$ref` types are no longer generated, instead all objects are defined explicitly +- All OpenAPI domain models moved to a separate module `kompendium-oas` +- Moved all files in `kompendium-core` into `io.bkbn.kompendium.core` package from `io.bkbn.kompendium` +- Gradle bumped to 7.3.2 +- Gradle build logic offloaded to Sourdough Plugin +- Minimum supported Java version is now 11 +- Bumped Kotlin to 1.6 +- Annotations now live in a separate module. (Should not impact end users as module is imported as api dependency by core). +- Kotest as the testing framework of choice +- Path calculation removed in favor of built-in route toString +- Ktor to 1.6.7 +- Completely reworked authentication and exceptions +- MethodInfo now exists in a separate package as a sealed interface, each implementation also has its own file +- Kompendium is now a Ktor Plugin! +- GitHub Actions now leverage Gradle Wrapper +- Dropped Codacy support b/c codacy kinda sucks +- Fixed bug where KompendiumField was being completely ignored +- Redid playground to serve as a showcase for various functionality +- README updates +- Refactored `handleComplexType` 🎉 +- Enabled field descriptions +- Dropped Version Catalog +- Responses are now a map of _actual_ responses rather than generic payloads +- Fixed bug where params with default values were listed as required +- Made empty put/post request info opt-in rather than default +- Fields are now marked as required when there is no default, and they are non-nullable +- `KompendiumField` and 'KompendiumParam' renamed to `Field` and `Param` respectively +- Description dropped from `Param` +- Dropped unnecessary parameter content scanning method +- Fixed bug causing all request bodies to be marked as optional +- Dropped ASDF tool manifest + ## [1.11.1] - November 25th, 2021 ### Added - Documentation showing how to add header names using Kotlin backtick convention diff --git a/README.md b/README.md index f08918f7c..272fd4848 100644 --- a/README.md +++ b/README.md @@ -1,20 +1,24 @@ # Kompendium -[![Codacy Badge](https://app.codacy.com/project/badge/Grade/a9bfd6c77d22497b907b3221849a3ba9)](https://www.codacy.com/gh/bkbnio/kompendium/dashboard?utm_source=github.com&utm_medium=referral&utm_content=bkbnio/kompendium&utm_campaign=Badge_Grade) -[![Codacy Badge](https://app.codacy.com/project/badge/Coverage/a9bfd6c77d22497b907b3221849a3ba9)](https://www.codacy.com/gh/bkbnio/kompendium/dashboard?utm_source=github.com&utm_medium=referral&utm_content=bkbnio/kompendium&utm_campaign=Badge_Coverage) [![version](https://img.shields.io/maven-central/v/io.bkbn/kompendium-core?style=flat-square)](https://search.maven.org/search?q=io.bkbn%20kompendium) +## Table of Contents + +- [What Is Kompendium](#what-is-kompendium) +- [How to Install](#how-to-install) +- [Library Details](#library-details) +- [Local Development](#local-development) +- [The Playground](#the-playground) + ## What is Kompendium -### ⚠️ For info on V2 please see [here](#V2) - -Kompendium is intended to be a minimally invasive OpenApi Specification generator for [Ktor](https://ktor.io). Minimally -invasive meaning that users will use only Ktor native functions when implementing their API, and will supplement with -Kompendium code in order to generate the appropriate spec. +Kompendium is intended to be a minimally invasive OpenApi Specification generator for Ktor. Minimally invasive meaning +that users will use only Ktor native functions when implementing their API, and will supplement with Kompendium code in +order to generate the appropriate spec. ## How to install -Kompendium publishes all releases to Maven Central. As such, using the stable version of `Kompendium` is as simple as +Kompendium publishes all releases to Maven Central. As such, using the release versions of `Kompendium` is as simple as declaring it as an implementation dependency in your `build.gradle.kts` ```kotlin @@ -23,42 +27,19 @@ repositories { } dependencies { - implementation("io.bkbn:kompendium-core:1.8.1") - implementation("io.bkbn:kompendium-auth:1.8.1") - implementation("io.bkbn:kompendium-swagger-ui:1.8.1") - - // Other dependencies... + implementation("io.bkbn:kompendium-core:latest.release") } ``` The last two dependencies are optional. -If you want to get a little spicy 🤠 every merge of Kompendium is published to the GitHub package registry. Pulling from -GitHub is slightly more involved, but such is the price you pay for bleeding edge fake data generation. +In addition to publishing releases to Maven Central, a snapshot version gets published to GitHub Packages on every merge +to `main`. These can be consumed by adding the repository to your gradle build file. Instructions can be +found [here](https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-gradle-registry#using-a-published-package) -```kotlin -// 1 Setup a helper function to import any Github Repository Package -// This step is optional but I have a bunch of stuff stored on github so I find it useful 😄 -fun RepositoryHandler.github(packageUrl: String) = maven { - name = "GithubPackages" - url = uri(packageUrl) - credentials { - username = java.lang.System.getenv("GITHUB_USER") - password = java.lang.System.getenv("GITHUB_TOKEN") - } - } +# Library Details -// 2 Add the repo in question (in this case Kompendium) -repositories { - github("https://maven.pkg.github.com/bkbnio/kompendium") -} - -// 3 Add the package like any normal dependency -dependencies { - implementation("io.bkbn:kompendium-core:1.8.1") -} - -``` +Details on how to use Kompendium can be found in the Wiki (WIP, this is new for V2 and will be fleshed out prior to release) ## Local Development @@ -66,320 +47,9 @@ Kompendium should run locally right out of the box, no configuration necessary ( New features can be built locally and published to your local maven repository with the `./gradlew publishToMavenLocal` command! -## In depth +## The Playground -### Notarized Routes +This repo contains a `playground` module that contains a number of working examples showcasing the capabilities of +Kompendium. -Kompendium introduces the concept of `notarized` HTTP methods. That is, for all your `GET`, `POST`, `PUT`, and `DELETE` -operations, there is a corresponding `notarized` method. These operations are strongly typed, and use reification for a -lot of the class based reflection that powers Kompendium. Generally speaking the three types that a `notarized` method -will consume are - -- `TParam`: Used to notarize expected request parameters -- `TReq`: Used to build the object schema for a request body -- `TResp`: Used to build the object schema for a response body - -`GET` and `DELETE` take `TParam` and `TResp` while `PUT` and `POST` take all three. - -In addition to standard HTTP Methods, Kompendium also introduced the concept of `notarizedExceptions`. Using -the `StatusPage` -extension, users can notarize all handled exceptions, along with their respective HTTP codes and response types. -Exceptions that have been `notarized` require two types as supplemental information - -- `TErr`: Used to notarize the exception being handled by this use case. Used for matching responses at the route level. -- `TResp`: Same as above, this dictates the expected return type of the error response. - -In keeping with minimal invasion, these extension methods all consume the same code block as a standard Ktor route -method, meaning that swapping in a default Ktor route and a Kompendium `notarized` route is as simple as a single method -change. - -### Supplemental Annotations - -In general, Kompendium tries to limit the number of annotations that developers need to use in order to get an app -integrated. - -Currently, the annotations used by Kompendium are as follows - -- `KompendiumField` -- `KompendiumParam` - -The intended purpose of `KompendiumField` is to offer field level overrides such as naming conventions (ie snake instead -of camel). - -The purpose of `KompendiumParam` is to provide supplemental information needed to properly assign the type of parameter -(cookie, header, query, path) as well as other parameter-level metadata. - -Using backticks, users can use data classes to represent things like header names as follows - -```kotlin -data class HeaderNameTest( - @KompendiumParam(type = ParamType.HEADER) val `X-UserEmail`: String -) -``` - -### Undeclared Field - -There is also a final `UndeclaredField` annotation. This should be used only in an absolutely emergency. This annotation -will allow you to inject a _single_ undeclared field that will be included as part of the schema. - -Due to limitations in using repeated annotations, this can only be used once per class - -This is a complete hack, and is included for odd scenarios like kotlinx serialization polymorphic adapters that expect a -`type` field in order to perform their analysis. - -Use this _only_ when **all** else fails - -### Polymorphism - -Speaking of polymorphism... out of the box, Kompendium has support for sealed classes and interfaces. At runtime, it -will build a mapping of all available sub-classes and build a spec that takes `anyOf` the implementations. This is -currently a weak point of the entire library, and suggestions on better implementations are welcome 🤠 - -### Serialization - -Under the hood, Kompendium uses Jackson to serialize the final api spec. However, this implementation detail does not -leak to the actual API, meaning that users are free to choose the serialization library of their choice. - -Added the possibility to add your own ObjectMapper for Jackson. - -Added a default parameter with the following configuration: - -```kotlin -ObjectMapper() - .setSerializationInclusion(JsonInclude.Include.NON_NULL) - .enable(SerializationFeature.INDENT_OUTPUT) -``` - -If you want to change this default configuration and use your own ObjectMapper you only need to pass it as a second -argument to the openApi module: - -```kotlin -routing { - openApi(oas, objectMapper) - route("/potato/spud") { - notarizedGet(simpleGetInfo) { - call.respond(HttpStatusCode.OK) - } - } -} -``` - -### Route Handling - -> ⚠️ Warning: Custom route handling is almost definitely an indication that either a new selector should be added to kompendium-core or that kompendium is in need of another module to handle a new ktor companion module. If you have encountered a route selector that is not already handled, please consider opening an [issue](https://github.com/bkbnio/kompendium/issues/new) - -Kompendium does its best to handle all Ktor routes out of the gate. However, in keeping with the modular approach of -Ktor and Kompendium, this is not always possible. - -Should you need to, custom route handlers can be registered via the -`Kompendium.addCustomRouteHandler` function. - -The handler signature is as follows - -```kotlin -fun addCustomRouteHandler( - selector: KClass, - handler: PathCalculator.(Route, String) -> String -) -``` - -This function takes a selector, which _must_ be a KClass of the Ktor `RouteSelector` type. The handler is a function -that extends the Kompendium `PathCalculator`. This is necessary because it gives you access -to `PathCalculator.calculate`, which you are going to want in order to recursively calculate the remainder of the -route :) - -Its parameters are the `Route` itself, along with the "tail" of the Path (the path that has been calculated thus far). - -Working examples `init` blocks of the `PathCalculator` and `KompendiumAuth` object. - -### Ktor Locations Plugin - -Kompendium offers integration with the Ktor [Locations](https://ktor.io/docs/locations.html) plugin via an optional -module `kompendium-locations`. - -This provides a wrapper around the Locations api, provide full path analysis, along with typesafe access to request -parameters. However, due to the way that Kompendium core parses class metadata, you will still need to annotate all -parameters with `@KompendiumParam`. A simple example - -```kotlin -@Location("/test/{name}") -data class TestLocations( - @KompendiumParam(ParamType.PATH) - val name: String, -) -``` - -When passed to a notarized route (make sure you are using the notarized methods found in -the `io.bkbn.kompendium.locations` package ⚠️), this will provide you with a notarized route that also passes through -the type safe instance containing all of your parameters! - -```kotlin -notarizedGet(testLocation) { tl -> - call.respondText { tl.name } -} -``` - -A working example can be found in the `kompendium-playground` in the `LocationsSpike` file :) - -## Examples - -The full source code can be found in the `kompendium-playground` module. Here is a simple get endpoint example - -```kotlin -// Minimal API Example -fun Application.mainModule() { - install(StatusPages) { - notarizedException( - info = ResponseInfo( - KompendiumHttpCodes.BAD_REQUEST, - "Bad Things Happened" - ) - ) { - call.respond(HttpStatusCode.BadRequest, ExceptionResponse("Why you do dis?")) - } - } - routing { - openApi(oas) - redoc(oas) - swaggerUI() - route("/potato/spud") { - notarizedGet(simpleGetInfo) { - call.respond(HttpStatusCode.OK) - } - } - } -} - -val simpleGetInfo = GetInfo( - summary = "Example Parameters", - description = "A test for setting parameter examples", - operationId = "getExamples", - responseInfo = ResponseInfo( - status = 200, - description = "nice", - examples = mapOf("test" to ExampleResponse(c = "spud")) - ), - canThrow = setOf(Exception::class) -) -``` - -### Kompendium Auth and security schemes - -There is a separate library to handle security schemes: `kompendium-auth`. This needs to be added to your project as -dependency. - -At the moment, the basic and jwt authentication is only supported. - -A minimal example would be: - -```kotlin -install(Authentication) { - notarizedBasic("basic") { - realm = "Ktor realm 1" - // configure basic authentication provider.. - } - notarizedJwt("jwt") { - realm = "Ktor realm 2" - // configure jwt authentication provider... - } -} -routing { - authenticate("basic") { - route("/basic_auth") { - notarizedGet(basicAuthGetInfo) { - call.respondText { "basic auth" } - } - } - } - authenticate("jwt") { - route("/jwt") { - notarizedGet(jwtAuthGetInfo) { - call.respondText { "jwt" } - } - } - } -} - -val basicAuthGetInfo = MethodInfo( - summary = "Another get test", - description = "testing more", - responseInfo = testGetResponse, - securitySchemes = setOf("basic") -) -val jwtAuthGetInfo = basicAuthGetInfo.copy(securitySchemes = setOf("jwt")) -``` - -### Enabling Swagger ui - -To enable Swagger UI, `kompendium-swagger-ui` needs to be added. This will also add -the [ktor webjars feature](https://ktor.io/docs/webjars.html) to your classpath as it is required for swagger ui. -Minimal Example: - -```kotlin - install(Webjars) -routing { - openApi(oas) - swaggerUI() -} -``` - -### Enabling ReDoc - -Unlike swagger, redoc is provided (perhaps confusingly, in the `core` module). This means out of the box -with `kompendium-core`, you can add -[ReDoc](https://github.com/Redocly/redoc) as follows - -```kotlin -routing { - openApi(oas) - redoc(oas) -} -``` - -## Custom Type Overrides - -Kompendium does its best to analyze types and to generate an OpenAPI format accordingly. However, there are certain -classes that just don't play nice with the standard reflection analysis that Kompendium performs. Should you encounter a -data type that Kompendium cannot comprehend, you will need to add it explicitly. For example, adding the Joda -Time `DateTime` object would be as simple as the following - -```kotlin - Kompendium.addCustomTypeSchema(DateTime::class, FormatSchema("date-time", "string")) -``` - -Since `Kompendium` is an object, this needs to be declared once, ahead of the actual API instantiation. This way, this -type override can be cached ahead of reflection. Kompendium will then match all instances of this type and return the -specified schema. - -So how do you know a type can and cannot be inferred? The safe bet is that it can be. So go ahead and give it a shot. -However, in the very odd scenario (almost always having to do with date/time libraries 😤) where it can't, you can rest -safely knowing that you have the option to inject a custom override should you need to. - -## Limitations - -### Kompendium as a singleton - -Currently, Kompendium exists as a Kotlin object. This comes with a couple perks, but a couple downsides. Primarily, it -offers a seriously clean UX where the implementer doesn't need to worry about what instance to send data to. The main -drawback, however, is that you are limited to a single API per classpath. - -If this is a blocker, please open a GitHub issue, and we can start to think out solutions! - -## Future Work - -Work on V1 of Kompendium has come to a close. This, however, does not mean it has achieved complete parity with the -OpenAPI feature spec, nor does it have all-of-the nice to have features that a truly next-gen API spec should have. -There are several outstanding features that have been added to the -[V2 Milestone](https://github.com/bkbnio/kompendium/milestone/2). Among others, this includes - -- AsyncAPI Integration -- Field Validation - -If you have a feature that you would like to see implemented that is not on this list, or discover a 🐞, please open an -issue [here](https://github.com/bkbnio/kompendium/issues/new) - -### V2 - -Due to the large number of breaking changes that will be made in version 2, development is currently being done on the -long-lived `v2` feature branch. If you are working on any feature in the `V2` milestone, please target that branch! -If you are unsure where your changes should be, please open an issue first :) +Feel free to check it out, or even create your own example! diff --git a/build.gradle.kts b/build.gradle.kts index 2ee5d6f3b..2bbec91a4 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,13 +1,23 @@ -import com.adarshr.gradle.testlogger.TestLoggerExtension -import com.adarshr.gradle.testlogger.theme.ThemeType -import io.gitlab.arturbosch.detekt.extensions.DetektExtension -import org.jetbrains.kotlin.gradle.tasks.KotlinCompile +import io.bkbn.sourdough.gradle.core.extension.SourdoughLibraryExtension plugins { - id("org.jetbrains.kotlin.jvm") version "1.5.31" apply false - id("io.gitlab.arturbosch.detekt") version "1.18.1" apply false - id("com.adarshr.test-logger") version "3.0.0" apply false - id("io.github.gradle-nexus.publish-plugin") version "1.1.0" apply true + id("io.bkbn.sourdough.root") version "0.3.0" + id("com.github.jakemarsden.git-hooks") version "0.0.2" +} + +sourdough { + toolChainJavaVersion.set(JavaLanguageVersion.of(JavaVersion.VERSION_17.majorVersion)) + jvmTarget.set(JavaVersion.VERSION_11.majorVersion) + compilerArgs.set(listOf("-opt-in=kotlin.RequiresOptIn")) +} + +gitHooks { + setHooks( + mapOf( + "pre-commit" to "detekt", + "pre-push" to "test" + ) + ) } allprojects { @@ -20,76 +30,20 @@ allprojects { else -> "$baseVersion-SNAPSHOT" } } - - repositories { - mavenCentral() - maven { url = uri("https://maven.pkg.jetbrains.space/public/p/kotlinx-html/maven") } - } - - apply(plugin = "org.jetbrains.kotlin.jvm") - apply(plugin = "io.gitlab.arturbosch.detekt") - apply(plugin = "com.adarshr.test-logger") - apply(plugin = "idea") - apply(plugin = "jacoco") - - tasks.withType().configureEach { - kotlinOptions { - jvmTarget = "1.8" - } - } - - tasks.withType() { - finalizedBy(tasks.withType(JacocoReport::class)) - } - - tasks.withType() { - reports { - html.required.set(true) - xml.required.set(true) - } - } - - configure { - toolVersion = "0.8.7" - } - - @Suppress("MagicNumber") - configure { - theme = ThemeType.MOCHA - setLogLevel("lifecycle") - showExceptions = true - showStackTraces = true - showFullStackTraces = false - showCauses = true - slowThreshold = 2000 - showSummary = true - showSimpleNames = false - showPassed = true - showSkipped = true - showFailed = true - showStandardStreams = false - showPassedStandardStreams = true - showSkippedStandardStreams = true - showFailedStandardStreams = true - } - - configure { - toolVersion = "1.18.1" - config = files("${rootProject.projectDir}/detekt.yml") - buildUponDefaultConfig = true - } - - configure { - withSourcesJar() - withJavadocJar() - } } -nexusPublishing { - repositories { - sonatype { - nexusUrl.set(uri("https://s01.oss.sonatype.org/service/local/")) - snapshotRepositoryUrl.set(uri("https://s01.oss.sonatype.org/content/repositories/snapshots/")) - } +subprojects { + apply(plugin = "io.bkbn.sourdough.library") + + configure { + githubOrg.set("bkbnio") + githubRepo.set("kompendium") + libraryName.set("Kompendium") + libraryDescription.set("A minimally invasive OpenAPI spec generator for Ktor") + licenseName.set("MIT License") + licenseUrl.set("https://mit-license.org") + developerId.set("bkbnio") + developerName.set("Ryan Brink") + developerEmail.set("admin@bkbn.io") } } diff --git a/codacy.yml b/codacy.yml new file mode 100644 index 000000000..d44a9a724 --- /dev/null +++ b/codacy.yml @@ -0,0 +1,3 @@ +--- +exclude_paths: + - "**/*.md" diff --git a/detekt.yml b/detekt.yml index 21bea2069..7096bfd7c 100644 --- a/detekt.yml +++ b/detekt.yml @@ -12,9 +12,14 @@ formatting: active: false style: MaxLineLength: - excludes: ['**/test/**/*', '**/testIntegration/**/*'] + excludes: ['**/test/**/*'] active: true maxLineLength: 120 + MagicNumber: + excludes: ['**/kompendium-playground/**/*', '**/test/**/*'] naming: ConstructorParameterNaming: active: false +performance: + SpreadOperator: + active: false diff --git a/gradle.properties b/gradle.properties index 383684c82..a75240f76 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,7 +1,12 @@ # Kompendium -project.version=1.11.1 +project.version=2.0.0-alpha # Kotlin kotlin.code.style=official # Gradle org.gradle.vfs.watch=true org.gradle.vfs.verbose=true +org.gradle.jvmargs=-Xmx2000m + +# Dependencies +ktorVersion=1.6.7 +kotestVersion=5.0.3 diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml deleted file mode 100644 index 572f2390f..000000000 --- a/gradle/libs.versions.toml +++ /dev/null @@ -1,41 +0,0 @@ -[versions] -kotlin = "1.4.32" -ktor = "1.6.5" -kotlinx-serialization = "1.2.1" -jackson-kotlin = "2.12.0" -slf4j = "1.7.30" -logback = "1.2.3" -swagger-ui = "3.47.1" - -[libraries] -# API -ktor-server-core = { group = "io.ktor", name = "ktor-server-core", version.ref = "ktor" } -ktor-server-netty = { group = "io.ktor", name = "ktor-server-netty", version.ref = "ktor" } -ktor-jackson = { group = "io.ktor", name = "ktor-jackson", version.ref = "ktor" } -ktor-serialization = { group = "io.ktor", name = "ktor-serialization", version.ref = "ktor" } -ktor-html-builder = { group = "io.ktor", name = "ktor-html-builder", version.ref = "ktor" } -ktor-auth-lib = { group = "io.ktor", name = "ktor-auth", version.ref = "ktor" } -ktor-auth-jwt = { group = "io.ktor", name = "ktor-auth-jwt", version.ref = "ktor" } -ktor-webjars = { group = "io.ktor", name = "ktor-webjars", version.ref = "ktor" } -ktor-locations = { group = "io.ktor", name = "ktor-locations", version.ref = "ktor" } - -# Serialization -jackson-module-kotlin = { group = "com.fasterxml.jackson.module", name = "jackson-module-kotlin", version.ref = "jackson-kotlin" } -kotlinx-serialization-json = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-json", version.ref = "kotlinx-serialization" } - - -# Logging -slf4j = { group = "org.slf4j", name = "slf4j-api", version.ref = "slf4j" } -logback-classic = { group = "ch.qos.logback", name = "logback-classic", version.ref = "logback" } -logback-core = { group = "ch.qos.logback", name = "logback-core", version.ref = "logback" } - -# webjars -webjars-swagger-ui = { group = "org.webjars", name = "swagger-ui", version.ref = "swagger-ui" } - -# Testing -ktor-server-test-host = { group = "io.ktor", name = "ktor-server-test-host", version.ref = "ktor" } - -[bundles] -ktor = ["ktor-server-core", "ktor-server-netty", "ktor-html-builder"] -ktorAuth = ["ktor-auth-lib", "ktor-auth-jwt"] -logging = ["slf4j", "logback-classic", "logback-core"] diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index e708b1c02..7454180f2 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index ffed3a254..d2880ba80 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,5 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.2-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index 4f906e0c8..1b6c78733 100755 --- a/gradlew +++ b/gradlew @@ -1,7 +1,7 @@ -#!/usr/bin/env sh +#!/bin/sh # -# Copyright 2015 the original author or authors. +# Copyright © 2015-2021 the original authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -17,67 +17,101 @@ # ############################################################################## -## -## Gradle start up script for UN*X -## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# ############################################################################## # Attempt to set APP_HOME + # Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` +APP_BASE_NAME=${0##*/} # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' # Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" +MAX_FD=maximum warn () { echo "$*" -} +} >&2 die () { echo echo "$*" echo exit 1 -} +} >&2 # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; esac CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar @@ -87,9 +121,9 @@ CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACMD=$JAVA_HOME/jre/sh/java else - JAVACMD="$JAVA_HOME/bin/java" + JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME @@ -98,7 +132,7 @@ Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else - JAVACMD="java" + JAVACMD=java which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the @@ -106,80 +140,95 @@ location of your Java installation." fi # Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi -fi - -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi - -# For Cygwin or MSYS, switch paths to Windows format before running java -if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi - # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" - fi - i=`expr $i + 1` - done - case $i in - 0) set -- ;; - 1) set -- "$args0" ;; - 2) set -- "$args0" "$args1" ;; - 3) set -- "$args0" "$args1" "$args2" ;; - 4) set -- "$args0" "$args1" "$args2" "$args3" ;; - 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" esac fi -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=`save "$@"` +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' exec "$JAVACMD" "$@" diff --git a/kompendium-annotations/Module.md b/kompendium-annotations/Module.md new file mode 100644 index 000000000..294dc7523 --- /dev/null +++ b/kompendium-annotations/Module.md @@ -0,0 +1,9 @@ +# Module kompendium-annotations + +This module houses all annotations that Kompendium uses to provide key metadata when performing reflective analysis. + +It is separated from core predominantly to allow for potential future integrations with [Kotlin Symbol Processing](https://github.com/google/ksp) + +# Package io.bkbn.kompendium.annotations + +Contains all annotations used by Kompendium diff --git a/kompendium-annotations/build.gradle.kts b/kompendium-annotations/build.gradle.kts new file mode 100644 index 000000000..57decae86 --- /dev/null +++ b/kompendium-annotations/build.gradle.kts @@ -0,0 +1,3 @@ +plugins { + id("io.bkbn.sourdough.library") +} diff --git a/kompendium-annotations/src/main/kotlin/io/bkbn/kompendium/annotations/Field.kt b/kompendium-annotations/src/main/kotlin/io/bkbn/kompendium/annotations/Field.kt new file mode 100644 index 000000000..22b6b1848 --- /dev/null +++ b/kompendium-annotations/src/main/kotlin/io/bkbn/kompendium/annotations/Field.kt @@ -0,0 +1,9 @@ +package io.bkbn.kompendium.annotations + +/** + * Annotation used to perform field level overrides. + * @param name Indicates that a field name override is desired. Often used for camel case to snake case conversions. + */ +@Retention(AnnotationRetention.RUNTIME) +@Target(AnnotationTarget.PROPERTY) +annotation class Field(val name: String = "", val description: String = "") diff --git a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/annotations/KompendiumField.kt b/kompendium-annotations/src/main/kotlin/io/bkbn/kompendium/annotations/FreeFormObject.kt similarity index 69% rename from kompendium-core/src/main/kotlin/io/bkbn/kompendium/annotations/KompendiumField.kt rename to kompendium-annotations/src/main/kotlin/io/bkbn/kompendium/annotations/FreeFormObject.kt index b25e4d8be..b7de9ed8e 100644 --- a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/annotations/KompendiumField.kt +++ b/kompendium-annotations/src/main/kotlin/io/bkbn/kompendium/annotations/FreeFormObject.kt @@ -2,4 +2,4 @@ package io.bkbn.kompendium.annotations @Retention(AnnotationRetention.RUNTIME) @Target(AnnotationTarget.PROPERTY) -annotation class KompendiumField(val name: String) +annotation class FreeFormObject diff --git a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/annotations/KompendiumParam.kt b/kompendium-annotations/src/main/kotlin/io/bkbn/kompendium/annotations/Param.kt similarity index 54% rename from kompendium-core/src/main/kotlin/io/bkbn/kompendium/annotations/KompendiumParam.kt rename to kompendium-annotations/src/main/kotlin/io/bkbn/kompendium/annotations/Param.kt index 7752563f0..13966584c 100644 --- a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/annotations/KompendiumParam.kt +++ b/kompendium-annotations/src/main/kotlin/io/bkbn/kompendium/annotations/Param.kt @@ -3,15 +3,7 @@ package io.bkbn.kompendium.annotations /** * Used to indicate that a field in a data class represents an OpenAPI parameter * @param type The type of parameter, must be valid [ParamType] - * @param description Description of the parameter to include in OpenAPI Spec */ @Retention(AnnotationRetention.RUNTIME) @Target(AnnotationTarget.PROPERTY) -annotation class KompendiumParam(val type: ParamType, val description: String = "") - -enum class ParamType { - COOKIE, - HEADER, - PATH, - QUERY -} +annotation class Param(val type: ParamType) diff --git a/kompendium-annotations/src/main/kotlin/io/bkbn/kompendium/annotations/ParamType.kt b/kompendium-annotations/src/main/kotlin/io/bkbn/kompendium/annotations/ParamType.kt new file mode 100644 index 000000000..48f5eb759 --- /dev/null +++ b/kompendium-annotations/src/main/kotlin/io/bkbn/kompendium/annotations/ParamType.kt @@ -0,0 +1,11 @@ +package io.bkbn.kompendium.annotations + +/** + * The allowed parameter types as specified by the OpenAPI specification + */ +enum class ParamType { + COOKIE, + HEADER, + PATH, + QUERY +} diff --git a/kompendium-annotations/src/main/kotlin/io/bkbn/kompendium/annotations/UndeclaredField.kt b/kompendium-annotations/src/main/kotlin/io/bkbn/kompendium/annotations/UndeclaredField.kt new file mode 100644 index 000000000..790c8c205 --- /dev/null +++ b/kompendium-annotations/src/main/kotlin/io/bkbn/kompendium/annotations/UndeclaredField.kt @@ -0,0 +1,15 @@ +package io.bkbn.kompendium.annotations + +import kotlin.reflect.KClass + +/** + * This annotation allows users to add additional fields that are not part of the core data model. This should be used + * EXTREMELY sparingly. Most useful in supporting a variety of polymorphic serialization techniques. + * @param field Name of the extra field to add to the model + * @param clazz Class type of the field being added. If this is a complex type, you are most likely doing something + * wrong. + */ +@Repeatable +@Retention(AnnotationRetention.RUNTIME) +@Target(AnnotationTarget.CLASS) +annotation class UndeclaredField(val field: String, val clazz: KClass<*>) diff --git a/kompendium-annotations/src/main/kotlin/io/bkbn/kompendium/annotations/constraint/Format.kt b/kompendium-annotations/src/main/kotlin/io/bkbn/kompendium/annotations/constraint/Format.kt new file mode 100644 index 000000000..543b8169f --- /dev/null +++ b/kompendium-annotations/src/main/kotlin/io/bkbn/kompendium/annotations/constraint/Format.kt @@ -0,0 +1,5 @@ +package io.bkbn.kompendium.annotations.constraint + +@Retention(AnnotationRetention.RUNTIME) +@Target(AnnotationTarget.PROPERTY) +annotation class Format(val format: String) diff --git a/kompendium-annotations/src/main/kotlin/io/bkbn/kompendium/annotations/constraint/MaxItems.kt b/kompendium-annotations/src/main/kotlin/io/bkbn/kompendium/annotations/constraint/MaxItems.kt new file mode 100644 index 000000000..c938750b2 --- /dev/null +++ b/kompendium-annotations/src/main/kotlin/io/bkbn/kompendium/annotations/constraint/MaxItems.kt @@ -0,0 +1,5 @@ +package io.bkbn.kompendium.annotations.constraint + +@Retention(AnnotationRetention.RUNTIME) +@Target(AnnotationTarget.PROPERTY) +annotation class MaxItems(val items: Int) diff --git a/kompendium-annotations/src/main/kotlin/io/bkbn/kompendium/annotations/constraint/MaxLength.kt b/kompendium-annotations/src/main/kotlin/io/bkbn/kompendium/annotations/constraint/MaxLength.kt new file mode 100644 index 000000000..95ee0154e --- /dev/null +++ b/kompendium-annotations/src/main/kotlin/io/bkbn/kompendium/annotations/constraint/MaxLength.kt @@ -0,0 +1,5 @@ +package io.bkbn.kompendium.annotations.constraint + +@Retention(AnnotationRetention.RUNTIME) +@Target(AnnotationTarget.PROPERTY) +annotation class MaxLength(val length: Int) diff --git a/kompendium-annotations/src/main/kotlin/io/bkbn/kompendium/annotations/constraint/MaxProperties.kt b/kompendium-annotations/src/main/kotlin/io/bkbn/kompendium/annotations/constraint/MaxProperties.kt new file mode 100644 index 000000000..2aa6ffed0 --- /dev/null +++ b/kompendium-annotations/src/main/kotlin/io/bkbn/kompendium/annotations/constraint/MaxProperties.kt @@ -0,0 +1,5 @@ +package io.bkbn.kompendium.annotations.constraint + +@Retention(AnnotationRetention.RUNTIME) +@Target(AnnotationTarget.PROPERTY) +annotation class MaxProperties(val properties: Int) diff --git a/kompendium-annotations/src/main/kotlin/io/bkbn/kompendium/annotations/constraint/Maximum.kt b/kompendium-annotations/src/main/kotlin/io/bkbn/kompendium/annotations/constraint/Maximum.kt new file mode 100644 index 000000000..4e06cdd3a --- /dev/null +++ b/kompendium-annotations/src/main/kotlin/io/bkbn/kompendium/annotations/constraint/Maximum.kt @@ -0,0 +1,5 @@ +package io.bkbn.kompendium.annotations.constraint + +@Retention(AnnotationRetention.RUNTIME) +@Target(AnnotationTarget.PROPERTY) +annotation class Maximum(val max: String, val exclusive: Boolean = false) diff --git a/kompendium-annotations/src/main/kotlin/io/bkbn/kompendium/annotations/constraint/MinItems.kt b/kompendium-annotations/src/main/kotlin/io/bkbn/kompendium/annotations/constraint/MinItems.kt new file mode 100644 index 000000000..94cdbc36f --- /dev/null +++ b/kompendium-annotations/src/main/kotlin/io/bkbn/kompendium/annotations/constraint/MinItems.kt @@ -0,0 +1,5 @@ +package io.bkbn.kompendium.annotations.constraint + +@Retention(AnnotationRetention.RUNTIME) +@Target(AnnotationTarget.PROPERTY) +annotation class MinItems(val items: Int) diff --git a/kompendium-annotations/src/main/kotlin/io/bkbn/kompendium/annotations/constraint/MinLength.kt b/kompendium-annotations/src/main/kotlin/io/bkbn/kompendium/annotations/constraint/MinLength.kt new file mode 100644 index 000000000..646ed2907 --- /dev/null +++ b/kompendium-annotations/src/main/kotlin/io/bkbn/kompendium/annotations/constraint/MinLength.kt @@ -0,0 +1,5 @@ +package io.bkbn.kompendium.annotations.constraint + +@Retention(AnnotationRetention.RUNTIME) +@Target(AnnotationTarget.PROPERTY) +annotation class MinLength(val length: Int) diff --git a/kompendium-annotations/src/main/kotlin/io/bkbn/kompendium/annotations/constraint/MinProperties.kt b/kompendium-annotations/src/main/kotlin/io/bkbn/kompendium/annotations/constraint/MinProperties.kt new file mode 100644 index 000000000..eede7a453 --- /dev/null +++ b/kompendium-annotations/src/main/kotlin/io/bkbn/kompendium/annotations/constraint/MinProperties.kt @@ -0,0 +1,5 @@ +package io.bkbn.kompendium.annotations.constraint + +@Retention(AnnotationRetention.RUNTIME) +@Target(AnnotationTarget.PROPERTY) +annotation class MinProperties(val properties: Int) diff --git a/kompendium-annotations/src/main/kotlin/io/bkbn/kompendium/annotations/constraint/Minimum.kt b/kompendium-annotations/src/main/kotlin/io/bkbn/kompendium/annotations/constraint/Minimum.kt new file mode 100644 index 000000000..b8652cda8 --- /dev/null +++ b/kompendium-annotations/src/main/kotlin/io/bkbn/kompendium/annotations/constraint/Minimum.kt @@ -0,0 +1,5 @@ +package io.bkbn.kompendium.annotations.constraint + +@Retention(AnnotationRetention.RUNTIME) +@Target(AnnotationTarget.PROPERTY) +annotation class Minimum(val min: String, val exclusive: Boolean = false) diff --git a/kompendium-annotations/src/main/kotlin/io/bkbn/kompendium/annotations/constraint/MultipleOf.kt b/kompendium-annotations/src/main/kotlin/io/bkbn/kompendium/annotations/constraint/MultipleOf.kt new file mode 100644 index 000000000..3bc002090 --- /dev/null +++ b/kompendium-annotations/src/main/kotlin/io/bkbn/kompendium/annotations/constraint/MultipleOf.kt @@ -0,0 +1,5 @@ +package io.bkbn.kompendium.annotations.constraint + +@Retention(AnnotationRetention.RUNTIME) +@Target(AnnotationTarget.PROPERTY) +annotation class MultipleOf(val multiple: String) diff --git a/kompendium-annotations/src/main/kotlin/io/bkbn/kompendium/annotations/constraint/Pattern.kt b/kompendium-annotations/src/main/kotlin/io/bkbn/kompendium/annotations/constraint/Pattern.kt new file mode 100644 index 000000000..a1b76ba62 --- /dev/null +++ b/kompendium-annotations/src/main/kotlin/io/bkbn/kompendium/annotations/constraint/Pattern.kt @@ -0,0 +1,5 @@ +package io.bkbn.kompendium.annotations.constraint + +@Retention(AnnotationRetention.RUNTIME) +@Target(AnnotationTarget.PROPERTY) +annotation class Pattern(val pattern: String) diff --git a/kompendium-annotations/src/main/kotlin/io/bkbn/kompendium/annotations/constraint/UniqueItems.kt b/kompendium-annotations/src/main/kotlin/io/bkbn/kompendium/annotations/constraint/UniqueItems.kt new file mode 100644 index 000000000..f1e3f7b1f --- /dev/null +++ b/kompendium-annotations/src/main/kotlin/io/bkbn/kompendium/annotations/constraint/UniqueItems.kt @@ -0,0 +1,5 @@ +package io.bkbn.kompendium.annotations.constraint + +@Retention(AnnotationRetention.RUNTIME) +@Target(AnnotationTarget.PROPERTY) +annotation class UniqueItems diff --git a/kompendium-auth/Module.md b/kompendium-auth/Module.md new file mode 100644 index 000000000..6869a9798 --- /dev/null +++ b/kompendium-auth/Module.md @@ -0,0 +1,9 @@ +# Module kompendium-auth + +This module is responsible for providing wrappers around ktor-auth configuration blocks, allowing users to document +their API authentication with minimal modifications to their existing configuration. + +# Package io.bkbn.kompendium.auth + +Base package that is responsible for setting up required authentication route handlers along with exposing +wrapper methods for each ktor-auth authentication mechanism. diff --git a/kompendium-auth/build.gradle.kts b/kompendium-auth/build.gradle.kts index c2681c64c..c321c24cc 100644 --- a/kompendium-auth/build.gradle.kts +++ b/kompendium-auth/build.gradle.kts @@ -1,78 +1,18 @@ plugins { - `java-library` - `maven-publish` - signing + id("io.bkbn.sourdough.library") } + dependencies { - implementation(platform("org.jetbrains.kotlin:kotlin-bom")) - implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8") - implementation(libs.bundles.ktor) - implementation(libs.bundles.ktorAuth) + // IMPLEMENTATION + + val ktorVersion: String by project implementation(projects.kompendiumCore) + implementation(group = "io.ktor", name = "ktor-server-core", version = ktorVersion) + implementation(group = "io.ktor", name = "ktor-auth", version = ktorVersion) + implementation(group = "io.ktor", name = "ktor-auth-jwt", version = ktorVersion) - testImplementation(libs.ktor.jackson) - testImplementation("org.jetbrains.kotlin:kotlin-test") - testImplementation("org.jetbrains.kotlin:kotlin-test-junit") - testImplementation(libs.jackson.module.kotlin) - testImplementation(libs.ktor.server.test.host) -} - -java { - withSourcesJar() - withJavadocJar() -} - -publishing { - repositories { - maven { - name = "GithubPackages" - url = uri("https://maven.pkg.github.com/bkbnio/kompendium") - credentials { - username = System.getenv("GITHUB_ACTOR") - password = System.getenv("GITHUB_TOKEN") - } - } - } - publications { - create("kompendium") { - from(components["kotlin"]) - artifact(tasks.sourcesJar) - artifact(tasks.javadocJar) - groupId = project.group.toString() - artifactId = project.name.toLowerCase() - version = project.version.toString() - - pom { - name.set("Kompendium") - description.set("A minimally invasive OpenAPI spec generator for Ktor") - url.set("https://github.com/bkbnio/Kompendium") - licenses { - license { - name.set("MIT License") - url.set("https://mit-license.org/") - } - } - developers { - developer { - id.set("bkbnio") - name.set("Ryan Brink") - email.set("admin@bkbn.io") - } - } - scm { - connection.set("scm:git:git://github.com/bkbnio/Kompendium.git") - developerConnection.set("scm:git:ssh://github.com/bkbnio/Kompendium.git") - url.set("https://github.com/bkbnio/Kompendium.git") - } - } - } - } -} - -signing { - val signingKey: String? by project - val signingPassword: String? by project - useInMemoryPgpKeys(signingKey, signingPassword) - sign(publishing.publications) + // TESTING + + testImplementation(testFixtures(projects.kompendiumCore)) } diff --git a/kompendium-auth/src/main/kotlin/io/bkbn/kompendium/auth/KompendiumAuth.kt b/kompendium-auth/src/main/kotlin/io/bkbn/kompendium/auth/KompendiumAuth.kt deleted file mode 100644 index 1b041384c..000000000 --- a/kompendium-auth/src/main/kotlin/io/bkbn/kompendium/auth/KompendiumAuth.kt +++ /dev/null @@ -1,53 +0,0 @@ -package io.bkbn.kompendium.auth - -import io.ktor.auth.Authentication -import io.ktor.auth.basic -import io.ktor.auth.BasicAuthenticationProvider -import io.ktor.auth.jwt.jwt -import io.ktor.auth.jwt.JWTAuthenticationProvider -import io.bkbn.kompendium.Kompendium -import io.bkbn.kompendium.models.oas.OpenApiSpecSchemaSecurity -import io.ktor.auth.AuthenticationRouteSelector - -object KompendiumAuth { - - init { - Kompendium.addCustomRouteHandler(AuthenticationRouteSelector::class) { route, tail -> - calculate(route.parent, tail) - } - } - - fun Authentication.Configuration.notarizedBasic( - name: String? = null, - configure: BasicAuthenticationProvider.Configuration.() -> Unit - ) { - Kompendium.openApiSpec.components.securitySchemes[name ?: "default"] = OpenApiSpecSchemaSecurity( - type = "http", - scheme = "basic" - ) - basic(name, configure) - } - - fun Authentication.Configuration.notarizedJwt( - name: String? = null, - header: String? = null, - scheme: String? = null, - configure: JWTAuthenticationProvider.Configuration.() -> Unit - ) { - if (header == null || header == "Authorization") { - Kompendium.openApiSpec.components.securitySchemes[name ?: "default"] = OpenApiSpecSchemaSecurity( - type = "http", - scheme = scheme ?: "bearer" - ) - } else { - Kompendium.openApiSpec.components.securitySchemes[name ?: "default"] = OpenApiSpecSchemaSecurity( - type = "apiKey", - name = header, - `in` = "header" - ) - } - jwt(name, configure) - } - - // TODO support other authentication providers (e.g., oAuth)? -} diff --git a/kompendium-auth/src/main/kotlin/io/bkbn/kompendium/auth/Notarized.kt b/kompendium-auth/src/main/kotlin/io/bkbn/kompendium/auth/Notarized.kt new file mode 100644 index 000000000..f5ee89369 --- /dev/null +++ b/kompendium-auth/src/main/kotlin/io/bkbn/kompendium/auth/Notarized.kt @@ -0,0 +1,40 @@ +package io.bkbn.kompendium.auth + +import io.bkbn.kompendium.auth.configuration.ApiKeyConfiguration +import io.bkbn.kompendium.auth.configuration.BasicAuthConfiguration +import io.bkbn.kompendium.auth.configuration.JwtAuthConfiguration +import io.bkbn.kompendium.auth.configuration.OAuthConfiguration +import io.bkbn.kompendium.auth.configuration.SecurityConfiguration +import io.bkbn.kompendium.core.Kompendium +import io.bkbn.kompendium.oas.security.ApiKeyAuth +import io.bkbn.kompendium.oas.security.BasicAuth +import io.bkbn.kompendium.oas.security.BearerAuth +import io.bkbn.kompendium.oas.security.OAuth +import io.ktor.application.feature +import io.ktor.auth.authenticate +import io.ktor.routing.Route +import io.ktor.routing.application + +object Notarized { + + fun Route.notarizedAuthenticate( + vararg configurations: SecurityConfiguration, + optional: Boolean = false, + build: Route.() -> Unit + ): Route { + val configurationNames = configurations.map { it.name }.toTypedArray() + val feature = application.feature(Kompendium) + + configurations.forEach { config -> + feature.config.spec.components.securitySchemes[config.name] = when (config) { + is ApiKeyConfiguration -> ApiKeyAuth(config.location, config.keyName) + is BasicAuthConfiguration -> BasicAuth() + is JwtAuthConfiguration -> BearerAuth(config.bearerFormat) + is OAuthConfiguration -> OAuth(config.description, config.flows) + } + } + + return authenticate(*configurationNames, optional = optional, build = build) + } + +} diff --git a/kompendium-auth/src/main/kotlin/io/bkbn/kompendium/auth/configuration/ApiKeyConfiguration.kt b/kompendium-auth/src/main/kotlin/io/bkbn/kompendium/auth/configuration/ApiKeyConfiguration.kt new file mode 100644 index 000000000..3675ff292 --- /dev/null +++ b/kompendium-auth/src/main/kotlin/io/bkbn/kompendium/auth/configuration/ApiKeyConfiguration.kt @@ -0,0 +1,8 @@ +package io.bkbn.kompendium.auth.configuration + +import io.bkbn.kompendium.oas.security.ApiKeyAuth + +interface ApiKeyConfiguration : SecurityConfiguration { + val location: ApiKeyAuth.ApiKeyLocation + val keyName: String +} diff --git a/kompendium-auth/src/main/kotlin/io/bkbn/kompendium/auth/configuration/BasicAuthConfiguration.kt b/kompendium-auth/src/main/kotlin/io/bkbn/kompendium/auth/configuration/BasicAuthConfiguration.kt new file mode 100644 index 000000000..b207f8ac7 --- /dev/null +++ b/kompendium-auth/src/main/kotlin/io/bkbn/kompendium/auth/configuration/BasicAuthConfiguration.kt @@ -0,0 +1,3 @@ +package io.bkbn.kompendium.auth.configuration + +interface BasicAuthConfiguration : SecurityConfiguration diff --git a/kompendium-auth/src/main/kotlin/io/bkbn/kompendium/auth/configuration/JwtAuthConfiguration.kt b/kompendium-auth/src/main/kotlin/io/bkbn/kompendium/auth/configuration/JwtAuthConfiguration.kt new file mode 100644 index 000000000..052ce42fc --- /dev/null +++ b/kompendium-auth/src/main/kotlin/io/bkbn/kompendium/auth/configuration/JwtAuthConfiguration.kt @@ -0,0 +1,6 @@ +package io.bkbn.kompendium.auth.configuration + +interface JwtAuthConfiguration : SecurityConfiguration { + val bearerFormat: String + get() = "JWT" +} diff --git a/kompendium-auth/src/main/kotlin/io/bkbn/kompendium/auth/configuration/OAuthConfiguration.kt b/kompendium-auth/src/main/kotlin/io/bkbn/kompendium/auth/configuration/OAuthConfiguration.kt new file mode 100644 index 000000000..880c1d352 --- /dev/null +++ b/kompendium-auth/src/main/kotlin/io/bkbn/kompendium/auth/configuration/OAuthConfiguration.kt @@ -0,0 +1,9 @@ +package io.bkbn.kompendium.auth.configuration + +import io.bkbn.kompendium.oas.security.OAuth + +interface OAuthConfiguration: SecurityConfiguration { + val flows: OAuth.Flows + val description: String? + get() = null +} diff --git a/kompendium-auth/src/main/kotlin/io/bkbn/kompendium/auth/configuration/SecurityConfiguration.kt b/kompendium-auth/src/main/kotlin/io/bkbn/kompendium/auth/configuration/SecurityConfiguration.kt new file mode 100644 index 000000000..1941e3a71 --- /dev/null +++ b/kompendium-auth/src/main/kotlin/io/bkbn/kompendium/auth/configuration/SecurityConfiguration.kt @@ -0,0 +1,5 @@ +package io.bkbn.kompendium.auth.configuration + +sealed interface SecurityConfiguration { + val name: String +} diff --git a/kompendium-auth/src/test/kotlin/io/bkbn/kompendium/auth/KompendiumAuthTest.kt b/kompendium-auth/src/test/kotlin/io/bkbn/kompendium/auth/KompendiumAuthTest.kt index 51684ad7f..ada56e8ef 100644 --- a/kompendium-auth/src/test/kotlin/io/bkbn/kompendium/auth/KompendiumAuthTest.kt +++ b/kompendium-auth/src/test/kotlin/io/bkbn/kompendium/auth/KompendiumAuthTest.kt @@ -1,201 +1,69 @@ package io.bkbn.kompendium.auth -import com.fasterxml.jackson.annotation.JsonInclude -import com.fasterxml.jackson.databind.SerializationFeature -import io.ktor.application.Application -import io.ktor.application.call -import io.ktor.application.install -import io.ktor.auth.Authentication -import io.ktor.auth.UserIdPrincipal -import io.ktor.auth.authenticate -import io.ktor.features.ContentNegotiation -import io.ktor.http.ContentType -import io.ktor.http.HttpMethod -import io.ktor.http.HttpStatusCode -import io.ktor.jackson.jackson -import io.ktor.response.respondText -import io.ktor.routing.route -import io.ktor.routing.routing -import io.ktor.server.testing.handleRequest -import io.ktor.server.testing.withTestApplication -import kotlin.test.AfterTest -import kotlin.test.assertEquals -import org.junit.Test -import io.bkbn.kompendium.Kompendium -import io.bkbn.kompendium.Notarized.notarizedGet -import io.bkbn.kompendium.auth.KompendiumAuth.notarizedBasic -import io.bkbn.kompendium.auth.KompendiumAuth.notarizedJwt -import io.bkbn.kompendium.auth.util.TestData -import io.bkbn.kompendium.auth.util.TestParams -import io.bkbn.kompendium.auth.util.TestResponse -import io.bkbn.kompendium.models.meta.MethodInfo -import io.bkbn.kompendium.models.meta.ResponseInfo -import io.bkbn.kompendium.routes.openApi -import io.bkbn.kompendium.routes.redoc +import io.bkbn.kompendium.auth.configuration.BasicAuthConfiguration +import io.bkbn.kompendium.auth.configuration.JwtAuthConfiguration +import io.bkbn.kompendium.auth.configuration.OAuthConfiguration +import io.bkbn.kompendium.auth.util.AuthConfigName +import io.bkbn.kompendium.auth.util.configBasicAuth +import io.bkbn.kompendium.auth.util.configJwtAuth +import io.bkbn.kompendium.auth.util.notarizedAuthRoute +import io.bkbn.kompendium.auth.util.setupOauth +import io.bkbn.kompendium.core.fixtures.TestHelpers.openApiTest +import io.bkbn.kompendium.oas.security.OAuth +import io.kotest.core.spec.style.DescribeSpec -internal class KompendiumAuthTest { - - @AfterTest - fun `reset kompendium`() { - Kompendium.resetSchema() - } - - @Test - fun `Notarized Get with basic authentication records all expected information`() { - withTestApplication({ - configModule() - configBasicAuth() - docs() - notarizedAuthenticatedGetModule(TestData.AuthConfigName.Basic) - }) { - // do - val json = handleRequest(HttpMethod.Get, "/openapi.json").response.content - - // expect - val expected = TestData.getFileSnapshot("notarized_basic_authenticated_get.json").trim() - assertEquals(expected, json, "The received json spec should match the expected content") - } - } - - @Test - fun `Notarized Get with jwt authentication records all expected information`() { - withTestApplication({ - configModule() - configJwtAuth() - docs() - notarizedAuthenticatedGetModule(TestData.AuthConfigName.JWT) - }) { - // do - val json = handleRequest(HttpMethod.Get, "/openapi.json").response.content - - // expect - val expected = TestData.getFileSnapshot("notarized_jwt_authenticated_get.json").trim() - assertEquals(expected, json, "The received json spec should match the expected content") - } - } - - @Test - fun `Notarized Get with jwt authentication and custom scheme records all expected information`() { - withTestApplication({ - configModule() - configJwtAuth(scheme = "oauth") - docs() - notarizedAuthenticatedGetModule(TestData.AuthConfigName.JWT) - }) { - // do - val json = handleRequest(HttpMethod.Get, "/openapi.json").response.content - - // expect - val expected = TestData.getFileSnapshot("notarized_jwt_custom_scheme_authenticated_get.json").trim() - assertEquals(expected, json, "The received json spec should match the expected content") - } - } - - @Test - fun `Notarized Get with jwt authentication and custom header records all expected information`() { - withTestApplication({ - configModule() - configJwtAuth(header = "x-api-key") - docs() - notarizedAuthenticatedGetModule(TestData.AuthConfigName.JWT) - }) { - // do - val json = handleRequest(HttpMethod.Get, "/openapi.json").response.content - - // expect - val expected = TestData.getFileSnapshot("notarized_jwt_custom_header_authenticated_get.json").trim() - assertEquals(expected, json, "The received json spec should match the expected content") - } - } - - @Test - fun `Notarized Get with multiple jwt schemes records all expected information`() { - withTestApplication({ - configModule() - install(Authentication) { - notarizedJwt("jwt1", header = "x-api-key-1") { - realm = "Ktor server" - } - notarizedJwt("jwt2", header = "x-api-key-2") { - realm = "Ktor server" - } +class KompendiumAuthTest : DescribeSpec({ + describe("Basic Authentication") { + it("Can create a notarized basic authentication record with all expected information") { + // arrange + val authConfig = object : BasicAuthConfiguration { + override val name: String = AuthConfigName.Basic } - docs() - notarizedAuthenticatedGetModule("jwt1", "jwt2") - }) { - // do - val json = handleRequest(HttpMethod.Get, "/openapi.json").response.content - // expect - val expected = TestData.getFileSnapshot("notarized_multiple_jwt_authenticated_get.json").trim() - assertEquals(expected, json, "The received json spec should match the expected content") - } - } - - private fun Application.configModule() { - install(ContentNegotiation) { - jackson(ContentType.Application.Json) { - enable(SerializationFeature.INDENT_OUTPUT) - setSerializationInclusion(JsonInclude.Include.NON_NULL) + // act + openApiTest("notarized_basic_authenticated_get.json") { + configBasicAuth() + notarizedAuthRoute(authConfig) } } } + describe("JWT Authentication") { + it("Can create a simple notarized JWT route") { + // arrange + val authConfig = object : JwtAuthConfiguration { + override val name: String = AuthConfigName.JWT + } - private fun Application.configBasicAuth() { - install(Authentication) { - notarizedBasic(TestData.AuthConfigName.Basic) { - realm = "Ktor Server" - validate { credentials -> - if (credentials.name == credentials.password) { - UserIdPrincipal(credentials.name) - } else { - null - } - } + // act + openApiTest("notarized_jwt_authenticated_get.json") { + configJwtAuth() + notarizedAuthRoute(authConfig) } } } - - private fun Application.configJwtAuth( - header: String? = null, - scheme: String? = null - ) { - install(Authentication) { - notarizedJwt(TestData.AuthConfigName.JWT, header, scheme) { - realm = "Ktor server" - } - } - } - - private fun Application.notarizedAuthenticatedGetModule(vararg authenticationConfigName: String) { - routing { - authenticate(*authenticationConfigName) { - route(TestData.getRoutePath) { - notarizedGet(testGetInfo(*authenticationConfigName)) { - call.respondText { "hey dude ‼️ congratz on the get request" } - } - } - } - } - } - - private val oas = Kompendium.openApiSpec.copy() - - private fun Application.docs() { - routing { - openApi(oas) - redoc(oas) - } - } - - private companion object { - val testGetResponse = ResponseInfo(HttpStatusCode.OK, "A Successful Endeavor") - fun testGetInfo(vararg security: String) = - MethodInfo.GetInfo( - summary = "Another get test", - description = "testing more", - responseInfo = testGetResponse, - securitySchemes = security.toSet() + describe("OAuth Authentication") { + it("Can create an Oauth schema with all possible flows") { + // arrange + val flows = OAuth.Flows( + implicit = OAuth.Flows.Implicit( + "https://accounts.google.com/o/oauth2/auth", + scopes = mapOf("test" to "is a cool scope", "this" to "is also cool") + ), + authorizationCode = OAuth.Flows.AuthorizationCode("https://accounts.google.com/o/oauth2/auth"), + password = OAuth.Flows.Password("https://accounts.google.com/o/oauth2/auth"), + clientCredentials = OAuth.Flows.ClientCredential("https://accounts.google.com/token") ) + + val authConfig = object : OAuthConfiguration { + override val flows: OAuth.Flows = flows + override val name: String = AuthConfigName.OAuth + } + + // act + openApiTest("notarized_oauth_all_flows.json") { + setupOauth() + notarizedAuthRoute(authConfig) + } + } } -} +}) diff --git a/kompendium-auth/src/test/kotlin/io/bkbn/kompendium/auth/util/TestData.kt b/kompendium-auth/src/test/kotlin/io/bkbn/kompendium/auth/util/TestData.kt deleted file mode 100644 index 446dec2b9..000000000 --- a/kompendium-auth/src/test/kotlin/io/bkbn/kompendium/auth/util/TestData.kt +++ /dev/null @@ -1,18 +0,0 @@ -package io.bkbn.kompendium.auth.util - -import java.io.File - -object TestData { - object AuthConfigName { - const val Basic = "basic" - const val JWT = "jwt" - } - - const val getRoutePath = "/test" - - fun getFileSnapshot(fileName: String): String { - val snapshotPath = "src/test/resources" - val file = File("$snapshotPath/$fileName") - return file.readText() - } -} diff --git a/kompendium-auth/src/test/kotlin/io/bkbn/kompendium/auth/util/TestModels.kt b/kompendium-auth/src/test/kotlin/io/bkbn/kompendium/auth/util/TestModels.kt deleted file mode 100644 index cebdcc1c6..000000000 --- a/kompendium-auth/src/test/kotlin/io/bkbn/kompendium/auth/util/TestModels.kt +++ /dev/null @@ -1,19 +0,0 @@ -package io.bkbn.kompendium.auth.util - -import io.bkbn.kompendium.annotations.KompendiumField -import io.bkbn.kompendium.annotations.KompendiumParam -import io.bkbn.kompendium.annotations.ParamType - -data class TestParams( - @KompendiumParam(ParamType.PATH) val a: String, - @KompendiumParam(ParamType.QUERY) val aa: Int -) - -data class TestRequest( - @KompendiumField(name = "field_name") - val b: Double, - val aaa: List -) - -data class TestResponse(val c: String) - diff --git a/kompendium-auth/src/test/kotlin/io/bkbn/kompendium/auth/util/TestModules.kt b/kompendium-auth/src/test/kotlin/io/bkbn/kompendium/auth/util/TestModules.kt new file mode 100644 index 000000000..d4a9d6bfe --- /dev/null +++ b/kompendium-auth/src/test/kotlin/io/bkbn/kompendium/auth/util/TestModules.kt @@ -0,0 +1,92 @@ +package io.bkbn.kompendium.auth.util + +import io.bkbn.kompendium.auth.Notarized.notarizedAuthenticate +import io.bkbn.kompendium.auth.configuration.SecurityConfiguration +import io.bkbn.kompendium.core.Notarized.notarizedGet +import io.bkbn.kompendium.core.fixtures.TestParams +import io.bkbn.kompendium.core.fixtures.TestResponse +import io.bkbn.kompendium.core.fixtures.TestResponseInfo +import io.bkbn.kompendium.core.metadata.method.GetInfo +import io.ktor.application.Application +import io.ktor.application.call +import io.ktor.application.install +import io.ktor.auth.Authentication +import io.ktor.auth.OAuthServerSettings +import io.ktor.auth.UserIdPrincipal +import io.ktor.auth.basic +import io.ktor.auth.jwt.jwt +import io.ktor.auth.oauth +import io.ktor.client.HttpClient +import io.ktor.client.engine.cio.CIO +import io.ktor.http.HttpMethod +import io.ktor.response.respondText +import io.ktor.routing.route +import io.ktor.routing.routing + +fun Application.setupOauth() { + install(Authentication) { + oauth("oauth") { + urlProvider = { "http://localhost:8080/callback" } + client = HttpClient(CIO) + providerLookup = { + OAuthServerSettings.OAuth2ServerSettings( + name = "google", + authorizeUrl = "https://accounts.google.com/o/oauth2/auth", + accessTokenUrl = "https://accounts.google.com/o/oauth2/token", + requestMethod = HttpMethod.Post, + clientId = System.getenv("GOOGLE_CLIENT_ID"), + clientSecret = System.getenv("GOOGLE_CLIENT_SECRET"), + defaultScopes = listOf("https://www.googleapis.com/auth/userinfo.profile") + ) + } + } + } +} + +fun Application.configBasicAuth() { + install(Authentication) { + basic(AuthConfigName.Basic) { + realm = "Ktor Server" + validate { credentials -> + if (credentials.name == credentials.password) { + UserIdPrincipal(credentials.name) + } else { + null + } + } + } + } +} + +fun Application.notarizedAuthRoute(authConfig: SecurityConfiguration) { + routing { + notarizedAuthenticate(authConfig) { + route("/test") { notarizedGet(testGetInfo(authConfig.name)) { + call.respondText { "hey dude ‼️ congratz on the get request" } + } + } + } + } +} + +fun Application.configJwtAuth() { + install(Authentication) { + jwt(AuthConfigName.JWT) { + realm = "Ktor server" + } + } +} + +fun testGetInfo(vararg security: String) = + GetInfo( + summary = "Another get test", + description = "testing more", + responseInfo = TestResponseInfo.testGetResponse, + securitySchemes = security.toSet() + ) + +object AuthConfigName { + const val Basic = "basic" + const val JWT = "jwt" + const val OAuth = "oauth" +} diff --git a/kompendium-auth/src/test/resources/notarized_basic_authenticated_get.json b/kompendium-auth/src/test/resources/notarized_basic_authenticated_get.json index 07808b519..3695f4139 100644 --- a/kompendium-auth/src/test/resources/notarized_basic_authenticated_get.json +++ b/kompendium-auth/src/test/resources/notarized_basic_authenticated_get.json @@ -1,75 +1,94 @@ { - "openapi" : "3.0.3", - "info" : { }, - "servers" : [ ], - "paths" : { - "/test" : { - "get" : { - "tags" : [ ], - "summary" : "Another get test", - "description" : "testing more", - "parameters" : [ { - "name" : "a", - "in" : "path", - "schema" : { - "type" : "string" + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" + }, + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + } + }, + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/test": { + "get": { + "tags": [], + "summary": "Another get test", + "description": "testing more", + "parameters": [ + { + "name": "a", + "in": "path", + "schema": { + "type": "string" + }, + "required": true, + "deprecated": false }, - "required" : true, - "deprecated" : false - }, { - "name" : "aa", - "in" : "query", - "schema" : { - "type" : "integer", - "format" : "int32" - }, - "required" : true, - "deprecated" : false - } ], - "responses" : { - "200" : { - "description" : "A Successful Endeavor", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/TestResponse" + { + "name": "aa", + "in": "query", + "schema": { + "format": "int32", + "type": "integer" + }, + "required": true, + "deprecated": false + } + ], + "responses": { + "200": { + "description": "A Successful Endeavor", + "content": { + "application/json": { + "schema": { + "properties": { + "c": { + "type": "string" + } + }, + "required": [ + "c" + ], + "type": "object" } } } } }, - "deprecated" : false, - "security" : [ { - "basic" : [ ] - } ] - } - } - }, - "components" : { - "schemas" : { - "String" : { - "type" : "string" - }, - "TestResponse" : { - "type" : "object", - "properties" : { - "c" : { - "$ref" : "#/components/schemas/String" + "deprecated": false, + "security": [ + { + "basic": [] } - } - }, - "Int" : { - "type" : "integer", - "format" : "int32" - } - }, - "securitySchemes" : { - "basic" : { - "type" : "http", - "scheme" : "basic" + ] } } }, - "security" : [ ], - "tags" : [ ] + "components": { + "securitySchemes": { + "basic": { + "type": "http", + "scheme": "basic" + } + } + }, + "security": [], + "tags": [] } diff --git a/kompendium-auth/src/test/resources/notarized_jwt_authenticated_get.json b/kompendium-auth/src/test/resources/notarized_jwt_authenticated_get.json index c954bd922..b6c476623 100644 --- a/kompendium-auth/src/test/resources/notarized_jwt_authenticated_get.json +++ b/kompendium-auth/src/test/resources/notarized_jwt_authenticated_get.json @@ -1,75 +1,95 @@ { - "openapi" : "3.0.3", - "info" : { }, - "servers" : [ ], - "paths" : { - "/test" : { - "get" : { - "tags" : [ ], - "summary" : "Another get test", - "description" : "testing more", - "parameters" : [ { - "name" : "a", - "in" : "path", - "schema" : { - "type" : "string" + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" + }, + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + } + }, + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/test": { + "get": { + "tags": [], + "summary": "Another get test", + "description": "testing more", + "parameters": [ + { + "name": "a", + "in": "path", + "schema": { + "type": "string" + }, + "required": true, + "deprecated": false }, - "required" : true, - "deprecated" : false - }, { - "name" : "aa", - "in" : "query", - "schema" : { - "type" : "integer", - "format" : "int32" - }, - "required" : true, - "deprecated" : false - } ], - "responses" : { - "200" : { - "description" : "A Successful Endeavor", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/TestResponse" + { + "name": "aa", + "in": "query", + "schema": { + "format": "int32", + "type": "integer" + }, + "required": true, + "deprecated": false + } + ], + "responses": { + "200": { + "description": "A Successful Endeavor", + "content": { + "application/json": { + "schema": { + "properties": { + "c": { + "type": "string" + } + }, + "required": [ + "c" + ], + "type": "object" } } } } }, - "deprecated" : false, - "security" : [ { - "jwt" : [ ] - } ] - } - } - }, - "components" : { - "schemas" : { - "String" : { - "type" : "string" - }, - "TestResponse" : { - "type" : "object", - "properties" : { - "c" : { - "$ref" : "#/components/schemas/String" + "deprecated": false, + "security": [ + { + "jwt": [] } - } - }, - "Int" : { - "type" : "integer", - "format" : "int32" - } - }, - "securitySchemes" : { - "jwt" : { - "type" : "http", - "scheme" : "bearer" + ] } } }, - "security" : [ ], - "tags" : [ ] + "components": { + "securitySchemes": { + "jwt": { + "bearerFormat": "JWT", + "type": "http", + "scheme": "bearer" + } + } + }, + "security": [], + "tags": [] } diff --git a/kompendium-auth/src/test/resources/notarized_jwt_custom_header_authenticated_get.json b/kompendium-auth/src/test/resources/notarized_jwt_custom_header_authenticated_get.json deleted file mode 100644 index c8b2c2614..000000000 --- a/kompendium-auth/src/test/resources/notarized_jwt_custom_header_authenticated_get.json +++ /dev/null @@ -1,76 +0,0 @@ -{ - "openapi" : "3.0.3", - "info" : { }, - "servers" : [ ], - "paths" : { - "/test" : { - "get" : { - "tags" : [ ], - "summary" : "Another get test", - "description" : "testing more", - "parameters" : [ { - "name" : "a", - "in" : "path", - "schema" : { - "type" : "string" - }, - "required" : true, - "deprecated" : false - }, { - "name" : "aa", - "in" : "query", - "schema" : { - "type" : "integer", - "format" : "int32" - }, - "required" : true, - "deprecated" : false - } ], - "responses" : { - "200" : { - "description" : "A Successful Endeavor", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/TestResponse" - } - } - } - } - }, - "deprecated" : false, - "security" : [ { - "jwt" : [ ] - } ] - } - } - }, - "components" : { - "schemas" : { - "String" : { - "type" : "string" - }, - "TestResponse" : { - "type" : "object", - "properties" : { - "c" : { - "$ref" : "#/components/schemas/String" - } - } - }, - "Int" : { - "type" : "integer", - "format" : "int32" - } - }, - "securitySchemes" : { - "jwt" : { - "type" : "apiKey", - "name" : "x-api-key", - "in" : "header" - } - } - }, - "security" : [ ], - "tags" : [ ] -} diff --git a/kompendium-auth/src/test/resources/notarized_jwt_custom_scheme_authenticated_get.json b/kompendium-auth/src/test/resources/notarized_jwt_custom_scheme_authenticated_get.json deleted file mode 100644 index 615851f4b..000000000 --- a/kompendium-auth/src/test/resources/notarized_jwt_custom_scheme_authenticated_get.json +++ /dev/null @@ -1,75 +0,0 @@ -{ - "openapi" : "3.0.3", - "info" : { }, - "servers" : [ ], - "paths" : { - "/test" : { - "get" : { - "tags" : [ ], - "summary" : "Another get test", - "description" : "testing more", - "parameters" : [ { - "name" : "a", - "in" : "path", - "schema" : { - "type" : "string" - }, - "required" : true, - "deprecated" : false - }, { - "name" : "aa", - "in" : "query", - "schema" : { - "type" : "integer", - "format" : "int32" - }, - "required" : true, - "deprecated" : false - } ], - "responses" : { - "200" : { - "description" : "A Successful Endeavor", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/TestResponse" - } - } - } - } - }, - "deprecated" : false, - "security" : [ { - "jwt" : [ ] - } ] - } - } - }, - "components" : { - "schemas" : { - "String" : { - "type" : "string" - }, - "TestResponse" : { - "type" : "object", - "properties" : { - "c" : { - "$ref" : "#/components/schemas/String" - } - } - }, - "Int" : { - "type" : "integer", - "format" : "int32" - } - }, - "securitySchemes" : { - "jwt" : { - "type" : "http", - "scheme" : "oauth" - } - } - }, - "security" : [ ], - "tags" : [ ] -} diff --git a/kompendium-auth/src/test/resources/notarized_multiple_jwt_authenticated_get.json b/kompendium-auth/src/test/resources/notarized_multiple_jwt_authenticated_get.json deleted file mode 100644 index 8aaf733ab..000000000 --- a/kompendium-auth/src/test/resources/notarized_multiple_jwt_authenticated_get.json +++ /dev/null @@ -1,82 +0,0 @@ -{ - "openapi" : "3.0.3", - "info" : { }, - "servers" : [ ], - "paths" : { - "/test" : { - "get" : { - "tags" : [ ], - "summary" : "Another get test", - "description" : "testing more", - "parameters" : [ { - "name" : "a", - "in" : "path", - "schema" : { - "type" : "string" - }, - "required" : true, - "deprecated" : false - }, { - "name" : "aa", - "in" : "query", - "schema" : { - "type" : "integer", - "format" : "int32" - }, - "required" : true, - "deprecated" : false - } ], - "responses" : { - "200" : { - "description" : "A Successful Endeavor", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/TestResponse" - } - } - } - } - }, - "deprecated" : false, - "security" : [ { - "jwt1" : [ ], - "jwt2" : [ ] - } ] - } - } - }, - "components" : { - "schemas" : { - "String" : { - "type" : "string" - }, - "TestResponse" : { - "type" : "object", - "properties" : { - "c" : { - "$ref" : "#/components/schemas/String" - } - } - }, - "Int" : { - "type" : "integer", - "format" : "int32" - } - }, - "securitySchemes" : { - "jwt1" : { - "type" : "apiKey", - "name" : "x-api-key-1", - "in" : "header" - }, - "jwt2" : { - "type" : "apiKey", - "name" : "x-api-key-2", - "in" : "header" - } - } - }, - "security" : [ ], - "tags" : [ ] -} diff --git a/kompendium-auth/src/test/resources/notarized_oauth_all_flows.json b/kompendium-auth/src/test/resources/notarized_oauth_all_flows.json new file mode 100644 index 000000000..a530afb97 --- /dev/null +++ b/kompendium-auth/src/test/resources/notarized_oauth_all_flows.json @@ -0,0 +1,114 @@ +{ + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" + }, + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + } + }, + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/test": { + "get": { + "tags": [], + "summary": "Another get test", + "description": "testing more", + "parameters": [ + { + "name": "a", + "in": "path", + "schema": { + "type": "string" + }, + "required": true, + "deprecated": false + }, + { + "name": "aa", + "in": "query", + "schema": { + "format": "int32", + "type": "integer" + }, + "required": true, + "deprecated": false + } + ], + "responses": { + "200": { + "description": "A Successful Endeavor", + "content": { + "application/json": { + "schema": { + "properties": { + "c": { + "type": "string" + } + }, + "required": [ + "c" + ], + "type": "object" + } + } + } + } + }, + "deprecated": false, + "security": [ + { + "oauth": [] + } + ] + } + } + }, + "components": { + "securitySchemes": { + "oauth": { + "flows": { + "implicit": { + "authorizationUrl": "https://accounts.google.com/o/oauth2/auth", + "scopes": { + "test": "is a cool scope", + "this": "is also cool" + } + }, + "authorizationCode": { + "authorizationUrl": "https://accounts.google.com/o/oauth2/auth", + "scopes": {} + }, + "password": { + "tokenUrl": "https://accounts.google.com/o/oauth2/auth", + "scopes": {} + }, + "clientCredentials": { + "tokenUrl": "https://accounts.google.com/token", + "scopes": {} + } + }, + "type": "oauth2" + } + } + }, + "security": [], + "tags": [] +} diff --git a/kompendium-core/Module.md b/kompendium-core/Module.md new file mode 100644 index 000000000..d1d8a645c --- /dev/null +++ b/kompendium-core/Module.md @@ -0,0 +1,9 @@ +# Module kompendium-core + +This is where the magic happens. This module houses all the reflective goodness that powers Kompendium. + +It is also the only mandatory client-facing module for a basic setup. + +# Package io.bkbn.kompendium.core + +The root package contains several objects that power Kompendium diff --git a/kompendium-core/build.gradle.kts b/kompendium-core/build.gradle.kts index 2ddf3df4d..4de867895 100644 --- a/kompendium-core/build.gradle.kts +++ b/kompendium-core/build.gradle.kts @@ -1,77 +1,33 @@ plugins { - `java-library` - `maven-publish` - signing + id("io.bkbn.sourdough.library") + `java-test-fixtures` } dependencies { - implementation(platform("org.jetbrains.kotlin:kotlin-bom")) - implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8") - implementation(libs.jackson.module.kotlin) - implementation(libs.bundles.ktor) - testImplementation("org.jetbrains.kotlin:kotlin-test") - testImplementation("org.jetbrains.kotlin:kotlin-test-junit") - testImplementation(libs.ktor.serialization) - testImplementation(libs.kotlinx.serialization.json) - testImplementation(libs.ktor.jackson) - testImplementation(libs.ktor.server.test.host) -} + // IMPLEMENTATION -java { - withSourcesJar() - withJavadocJar() -} + api(projects.kompendiumOas) + api(projects.kompendiumAnnotations) -publishing { - repositories { - maven { - name = "GithubPackages" - url = uri("https://maven.pkg.github.com/bkbnio/kompendium") - credentials { - username = System.getenv("GITHUB_ACTOR") - password = System.getenv("GITHUB_TOKEN") - } - } - } - publications { - create("kompendium") { - from(components["kotlin"]) - artifact(tasks.sourcesJar) - artifact(tasks.javadocJar) - groupId = project.group.toString() - artifactId = project.name.toLowerCase() - version = project.version.toString() + val ktorVersion: String by project + val kotestVersion: String by project + implementation(group = "io.ktor", name = "ktor-server-core", version = ktorVersion) + implementation(group = "io.ktor", name = "ktor-html-builder", version = ktorVersion) - pom { - name.set("Kompendium") - description.set("A minimally invasive OpenAPI spec generator for Ktor") - url.set("https://github.com/bkbnio/Kompendium") - licenses { - license { - name.set("MIT License") - url.set("https://mit-license.org/") - } - } - developers { - developer { - id.set("bkbnio") - name.set("Ryan Brink") - email.set("admin@bkbn.io") - } - } - scm { - connection.set("scm:git:git://github.com/bkbnio/Kompendium.git") - developerConnection.set("scm:git:ssh://github.com/bkbnio/Kompendium.git") - url.set("https://github.com/bkbnio/Kompendium.git") - } - } - } - } -} + implementation(group = "com.fasterxml.jackson.module", name = "jackson-module-kotlin", version = "2.13.0") -signing { - val signingKey: String? by project - val signingPassword: String? by project - useInMemoryPgpKeys(signingKey, signingPassword) - sign(publishing.publications) + // TEST FIXTURES + + testFixturesApi(group = "io.kotest", name = "kotest-runner-junit5-jvm", version = kotestVersion) + testFixturesApi(group = "io.kotest", name = "kotest-assertions-core-jvm", version = kotestVersion) + testFixturesApi(group = "io.kotest", name = "kotest-property-jvm", version = kotestVersion) + testFixturesApi(group = "io.kotest", name = "kotest-assertions-json-jvm", version = kotestVersion) + testFixturesApi(group = "io.kotest", name = "kotest-assertions-ktor-jvm", version = "4.4.3") + + testFixturesApi(group = "io.ktor", name = "ktor-server-core", version = ktorVersion) + testFixturesApi(group = "io.ktor", name = "ktor-server-test-host", version = ktorVersion) + testFixturesApi(group = "io.ktor", name = "ktor-jackson", version = ktorVersion) + testFixturesApi(group = "io.ktor", name = "ktor-serialization", version = ktorVersion) + + testFixturesApi(group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-json", version = "1.3.1") } diff --git a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/Kompendium.kt b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/Kompendium.kt deleted file mode 100644 index 831d90608..000000000 --- a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/Kompendium.kt +++ /dev/null @@ -1,49 +0,0 @@ -package io.bkbn.kompendium - -import io.bkbn.kompendium.models.meta.ErrorMap -import io.bkbn.kompendium.models.meta.SchemaMap -import io.bkbn.kompendium.models.oas.OpenApiSpec -import io.bkbn.kompendium.models.oas.OpenApiSpecInfo -import io.bkbn.kompendium.models.oas.TypedSchema -import io.bkbn.kompendium.path.IPathCalculator -import io.bkbn.kompendium.path.PathCalculator -import io.ktor.routing.Route -import io.ktor.routing.RouteSelector -import kotlin.reflect.KClass - -/** - * Maintains all state for the Kompendium library - */ -object Kompendium { - - var errorMap: ErrorMap = emptyMap() - var cache: SchemaMap = emptyMap() - - var openApiSpec = OpenApiSpec( - info = OpenApiSpecInfo(), - servers = mutableListOf(), - paths = mutableMapOf() - ) - - fun calculatePath(route: Route) = PathCalculator.calculate(route) - - fun resetSchema() { - openApiSpec = OpenApiSpec( - info = OpenApiSpecInfo(), - servers = mutableListOf(), - paths = mutableMapOf() - ) - cache = emptyMap() - } - - fun addCustomTypeSchema(clazz: KClass<*>, schema: TypedSchema) { - cache = cache.plus(clazz.simpleName!! to schema) - } - - fun addCustomRouteHandler( - selector: KClass, - handler: IPathCalculator.(Route, String) -> String - ) { - PathCalculator.addCustomRouteHandler(selector, handler) - } -} diff --git a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/KompendiumPreFlight.kt b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/KompendiumPreFlight.kt deleted file mode 100644 index 982da3586..000000000 --- a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/KompendiumPreFlight.kt +++ /dev/null @@ -1,54 +0,0 @@ -package io.bkbn.kompendium - -import io.ktor.routing.Route -import kotlin.reflect.KType -import kotlin.reflect.typeOf - -/** - * Functions are considered preflight when they are used to intercept a method ahead of running. - */ -object KompendiumPreFlight { - - /** - * Performs all content analysis on the types provided to a notarized route and adds it to the top level spec - * @param TParam - * @param TReq - * @param TResp - * @param block The function to execute, provided type information of the parameters above - * @return [Route] - */ - @OptIn(ExperimentalStdlibApi::class) - inline fun methodNotarizationPreFlight( - block: (KType, KType, KType) -> Route - ): Route { - val requestType = typeOf() - val responseType = typeOf() - val paramType = typeOf() - addToCache(paramType, requestType, responseType) - Kompendium.openApiSpec.components.schemas.putAll(Kompendium.cache) - return block.invoke(paramType, requestType, responseType) - } - - /** - * Performs all content analysis on the types provided to a notarized error and adds them to the top level spec. - * @param TErr - * @param TResp - * @param block The function to execute, provided type information of the parameters above - */ - @OptIn(ExperimentalStdlibApi::class) - inline fun errorNotarizationPreFlight( - block: (KType, KType) -> Unit - ) { - val errorType = typeOf() - val responseType = typeOf() - addToCache(typeOf(), typeOf(), responseType) - Kompendium.openApiSpec.components.schemas.putAll(Kompendium.cache) - return block.invoke(errorType, responseType) - } - - fun addToCache(paramType: KType, requestType: KType, responseType: KType) { - Kompendium.cache = Kontent.generateKontent(requestType, Kompendium.cache) - Kompendium.cache = Kontent.generateKontent(responseType, Kompendium.cache) - Kompendium.cache = Kontent.generateParameterKontent(paramType, Kompendium.cache) - } -} diff --git a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/Kontent.kt b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/Kontent.kt deleted file mode 100644 index 88f1057f6..000000000 --- a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/Kontent.kt +++ /dev/null @@ -1,290 +0,0 @@ -package io.bkbn.kompendium - -import io.bkbn.kompendium.annotations.UndeclaredField -import io.bkbn.kompendium.models.meta.SchemaMap -import io.bkbn.kompendium.models.oas.AnyOfReferencedSchema -import io.bkbn.kompendium.models.oas.ArraySchema -import io.bkbn.kompendium.models.oas.DictionarySchema -import io.bkbn.kompendium.models.oas.EnumSchema -import io.bkbn.kompendium.models.oas.FormatSchema -import io.bkbn.kompendium.models.oas.ObjectSchema -import io.bkbn.kompendium.models.oas.ReferencedSchema -import io.bkbn.kompendium.models.oas.SimpleSchema -import io.bkbn.kompendium.util.Helpers.COMPONENT_SLUG -import io.bkbn.kompendium.util.Helpers.genericNameAdapter -import io.bkbn.kompendium.util.Helpers.getReferenceSlug -import io.bkbn.kompendium.util.Helpers.getSimpleSlug -import io.bkbn.kompendium.util.Helpers.logged -import org.slf4j.LoggerFactory -import java.math.BigDecimal -import java.math.BigInteger -import java.util.UUID -import kotlin.reflect.KClass -import kotlin.reflect.KType -import kotlin.reflect.full.createType -import kotlin.reflect.full.isSubclassOf -import kotlin.reflect.full.memberProperties -import kotlin.reflect.jvm.javaField -import kotlin.reflect.typeOf - -/** - * Responsible for generating the schema map that is used to power all object references across the API Spec. - */ -object Kontent { - - private val logger = LoggerFactory.getLogger(javaClass) - - /** - * Analyzes a type [T] for its top-level and any nested schemas, and adds them to a [SchemaMap], if provided - * @param T type to analyze - * @param cache Existing schema map to append to - * @return an updated schema map containing all type information for [T] - */ - @OptIn(ExperimentalStdlibApi::class) - inline fun generateKontent( - cache: SchemaMap = emptyMap() - ): SchemaMap { - val kontentType = typeOf() - return generateKTypeKontent(kontentType, cache) - } - - /** - * Analyzes a [KType] for its top-level and any nested schemas, and adds them to a [SchemaMap], if provided - * @param type [KType] to analyze - * @param cache Existing schema map to append to - * @return an updated schema map containing all type information for [KType] type - */ - fun generateKontent( - type: KType, - cache: SchemaMap = emptyMap() - ): SchemaMap { - var newCache = cache - gatherSubTypes(type).forEach { - newCache = generateKTypeKontent(it, newCache) - } - return newCache - } - - private fun gatherSubTypes(type: KType): List { - val classifier = type.classifier as KClass<*> - return if (classifier.isSealed) { - classifier.sealedSubclasses.map { - it.createType(type.arguments) - } - } else { - listOf(type) - } - } - - /** - * Analyze a type [T], but filters out the top-level type - * @param T type to analyze - * @param cache Existing schema map to append to - * @return an updated schema map containing all type information for [T] - */ - @OptIn(ExperimentalStdlibApi::class) - inline fun generateParameterKontent( - cache: SchemaMap = emptyMap() - ): SchemaMap { - val kontentType = typeOf() - return generateKTypeKontent(kontentType, cache) - .filterNot { (slug, _) -> slug == (kontentType.classifier as KClass<*>).simpleName } - } - - /** - * Analyze a type but filters out the top-level type - * @param type to analyze - * @param cache Existing schema map to append to - * @return an updated schema map containing all type information for [T] - */ - fun generateParameterKontent( - type: KType, - cache: SchemaMap = emptyMap() - ): SchemaMap { - return generateKTypeKontent(type, cache) - .filterNot { (slug, _) -> slug == (type.classifier as KClass<*>).simpleName } - } - - /** - * Recursively fills schema map depending on [KType] classifier - * @param type [KType] to parse - * @param cache Existing schema map to append to - */ - fun generateKTypeKontent( - type: KType, - cache: SchemaMap = emptyMap() - ): SchemaMap = logged(object {}.javaClass.enclosingMethod.name, mapOf("cache" to cache)) { - logger.debug("Parsing Kontent of $type") - when (val clazz = type.classifier as KClass<*>) { - Unit::class -> cache - Int::class -> cache.plus(clazz.simpleName!! to FormatSchema("int32", "integer")) - Long::class -> cache.plus(clazz.simpleName!! to FormatSchema("int64", "integer")) - Double::class -> cache.plus(clazz.simpleName!! to FormatSchema("double", "number")) - Float::class -> cache.plus(clazz.simpleName!! to FormatSchema("float", "number")) - String::class -> cache.plus(clazz.simpleName!! to SimpleSchema("string")) - Boolean::class -> cache.plus(clazz.simpleName!! to SimpleSchema("boolean")) - UUID::class -> cache.plus(clazz.simpleName!! to FormatSchema("uuid", "string")) - BigDecimal::class -> cache.plus(clazz.simpleName!! to FormatSchema("double", "number")) - BigInteger::class -> cache.plus(clazz.simpleName!! to FormatSchema("int64", "integer")) - ByteArray::class -> cache.plus(clazz.simpleName!! to FormatSchema("byte", "string")) - else -> when { - clazz.isSubclassOf(Collection::class) -> handleCollectionType(type, clazz, cache) - clazz.isSubclassOf(Enum::class) -> handleEnumType(clazz, cache) - clazz.isSubclassOf(Map::class) -> handleMapType(type, clazz, cache) - else -> handleComplexType(type, clazz, cache) - } - } - } - - /** - * In the event of an object type, this method will parse out individual fields to recursively aggregate object map. - * @param clazz Class of the object to analyze - * @param cache Existing schema map to append to - */ - // TODO Fix as part of this issue https://github.com/bkbnio/kompendium/issues/80 - @Suppress("LongMethod", "ComplexMethod") - private fun handleComplexType(type: KType, clazz: KClass<*>, cache: SchemaMap): SchemaMap { - // This needs to be simple because it will be stored under it's appropriate reference component implicitly - val slug = type.getSimpleSlug() - // Only analyze if component has not already been stored in the cache - return when (cache.containsKey(slug)) { - true -> { - logger.debug("Cache already contains $slug, returning cache untouched") - cache - } - false -> { - logger.debug("$slug was not found in cache, generating now") - var newCache = cache - // Grabs any type parameters as a zip with the corresponding type argument - val typeMap = clazz.typeParameters.zip(type.arguments).toMap() - // associates each member with a Pair of prop name to property schema - val fieldMap = clazz.memberProperties.associate { prop -> - logger.debug("Analyzing $prop in class $clazz") - // Grab the field of the current property - val field = prop.javaField?.type?.kotlin ?: error("Unable to parse field type from $prop") - logger.debug("Detected field $field") - // Yoinks any generic types from the type map should the field be a generic - val yoinkBaseType = if (typeMap.containsKey(prop.returnType.classifier)) { - logger.debug("Generic type detected") - typeMap[prop.returnType.classifier]?.type!! - } else { - prop.returnType - } - // converts the base type to a class - val yoinkedClassifier = yoinkBaseType.classifier as KClass<*> - // in the event of a sealed class, grab all sealed subclasses and create a type from the base args - val yoinkedTypes = if (yoinkedClassifier.isSealed) { - yoinkedClassifier.sealedSubclasses.map { it.createType(yoinkBaseType.arguments) } - } else { - listOf(yoinkBaseType) - } - // if the most up-to-date cache does not contain the content for this field, generate it and add to cache - if (!newCache.containsKey(field.simpleName)) { - logger.debug("Cache was missing ${field.simpleName}, adding now") - yoinkedTypes.forEach { - newCache = generateKTypeKontent(it, newCache) - } - } - // TODO This in particular is worthy of a refactor... just not very well written - // builds the appropriate property schema based on the property return type - val propSchema = if (typeMap.containsKey(prop.returnType.classifier)) { - if (yoinkedClassifier.isSealed) { - val refs = yoinkedClassifier.sealedSubclasses - .map { it.createType(yoinkBaseType.arguments) } - .map { ReferencedSchema(it.getReferenceSlug()) } - AnyOfReferencedSchema(refs) - } else { - ReferencedSchema(typeMap[prop.returnType.classifier]?.type!!.getReferenceSlug()) - } - } else { - if (yoinkedClassifier.isSealed) { - val refs = yoinkedClassifier.sealedSubclasses - .map { it.createType(yoinkBaseType.arguments) } - .map { ReferencedSchema(it.getReferenceSlug()) } - AnyOfReferencedSchema(refs) - } else { - ReferencedSchema(field.getReferenceSlug(prop)) - } - } - Pair(prop.name, propSchema) - } - logger.debug("Looking for undeclared fields") - val undeclaredFieldMap = clazz.annotations.filterIsInstance().associate { - val undeclaredType = it.clazz.createType() - newCache = generateKontent(undeclaredType, newCache) - it.field to ReferencedSchema(undeclaredType.getReferenceSlug()) - } - logger.debug("$slug contains $fieldMap") - val schema = ObjectSchema(fieldMap.plus(undeclaredFieldMap)) - logger.debug("$slug schema: $schema") - newCache.plus(slug to schema) - } - } - } - - /** - * Handler for when an [Enum] is encountered - * @param clazz Class of the object to analyze - * @param cache Existing schema map to append to - */ - private fun handleEnumType(clazz: KClass<*>, cache: SchemaMap): SchemaMap { - val options = clazz.java.enumConstants.map { it.toString() }.toSet() - return cache.plus(clazz.simpleName!! to EnumSchema(options)) - } - - /** - * Handler for when a [Map] is encountered - * @param type Map type information - * @param clazz Map class information - * @param cache Existing schema map to append to - */ - private fun handleMapType(type: KType, clazz: KClass<*>, cache: SchemaMap): SchemaMap { - logger.debug("Map detected for $type, generating schema and appending to cache") - val (keyType, valType) = type.arguments.map { it.type } - logger.debug("Obtained map types -> key: $keyType and value: $valType") - if (keyType?.classifier != String::class) { - error("Invalid Map $type: OpenAPI dictionaries must have keys of type String") - } - val valClass = valType?.classifier as KClass<*> - val valClassName = valClass.simpleName - val referenceName = genericNameAdapter(type, clazz) - val valueReference = when (valClass.isSealed) { - true -> { - val subTypes = gatherSubTypes(valType) - AnyOfReferencedSchema(subTypes.map { - ReferencedSchema(("$COMPONENT_SLUG/${it.getSimpleSlug()}")) - }) - } - false -> ReferencedSchema("$COMPONENT_SLUG/$valClassName") - } - val schema = DictionarySchema(additionalProperties = valueReference) - val updatedCache = generateKontent(valType, cache) - return updatedCache.plus(referenceName to schema) - } - - /** - * Handler for when a [Collection] is encountered - * @param type Collection type information - * @param clazz Collection class information - * @param cache Existing schema map to append to - */ - private fun handleCollectionType(type: KType, clazz: KClass<*>, cache: SchemaMap): SchemaMap { - logger.debug("Collection detected for $type, generating schema and appending to cache") - val collectionType = type.arguments.first().type!! - val collectionClass = collectionType.classifier as KClass<*> - logger.debug("Obtained collection class: $collectionClass") - val referenceName = genericNameAdapter(type, clazz) - val valueReference = when (collectionClass.isSealed) { - true -> { - val subTypes = gatherSubTypes(collectionType) - AnyOfReferencedSchema(subTypes.map { - ReferencedSchema(("$COMPONENT_SLUG/${it.getSimpleSlug()}")) - }) - } - false -> ReferencedSchema("$COMPONENT_SLUG/${collectionClass.simpleName}") - } - val schema = ArraySchema(items = valueReference) - val updatedCache = generateKontent(collectionType, cache) - return updatedCache.plus(referenceName to schema) - } -} diff --git a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/Notarized.kt b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/Notarized.kt deleted file mode 100644 index dd3945ec0..000000000 --- a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/Notarized.kt +++ /dev/null @@ -1,115 +0,0 @@ -package io.bkbn.kompendium - -import io.ktor.application.ApplicationCall -import io.ktor.features.StatusPages -import io.ktor.http.HttpMethod -import io.ktor.routing.Route -import io.ktor.routing.method -import io.ktor.util.pipeline.PipelineContext -import io.ktor.util.pipeline.PipelineInterceptor -import io.bkbn.kompendium.KompendiumPreFlight.errorNotarizationPreFlight -import io.bkbn.kompendium.MethodParser.parseErrorInfo -import io.bkbn.kompendium.MethodParser.parseMethodInfo -import io.bkbn.kompendium.models.meta.MethodInfo.GetInfo -import io.bkbn.kompendium.models.meta.MethodInfo.PostInfo -import io.bkbn.kompendium.models.meta.MethodInfo.PutInfo -import io.bkbn.kompendium.models.meta.MethodInfo.DeleteInfo -import io.bkbn.kompendium.models.meta.ResponseInfo -import io.bkbn.kompendium.models.oas.OpenApiSpecPathItem - -/** - * Notarization methods are the primary way that a Ktor API using Kompendium differentiates - * from a default Ktor application. On instantiation, a notarized route, provided with the proper metadata, - * will reflectively analyze all pertinent data to build a corresponding OpenAPI entry. - */ -object Notarized { - - /** - * Notarization for an HTTP GET request - * @param TParam The class containing all parameter fields. - * Each field must be annotated with @[io.bkbn.kompendium.annotations.KompendiumField] - * @param TResp Class detailing the expected API response - * @param info Route metadata - */ - inline fun Route.notarizedGet( - info: GetInfo, - noinline body: PipelineInterceptor - ): Route = - KompendiumPreFlight.methodNotarizationPreFlight() { paramType, requestType, responseType -> - val path = Kompendium.calculatePath(this) - Kompendium.openApiSpec.paths.getOrPut(path) { OpenApiSpecPathItem() } - Kompendium.openApiSpec.paths[path]?.get = parseMethodInfo(info, paramType, requestType, responseType) - return method(HttpMethod.Get) { handle(body) } - } - - /** - * Notarization for an HTTP POST request - * @param TParam The class containing all parameter fields. - * Each field must be annotated with @[io.bkbn.kompendium.annotations.KompendiumField] - * @param TReq Class detailing the expected API request body - * @param TResp Class detailing the expected API response - * @param info Route metadata - */ - inline fun Route.notarizedPost( - info: PostInfo, - noinline body: PipelineInterceptor - ): Route = - KompendiumPreFlight.methodNotarizationPreFlight() { paramType, requestType, responseType -> - val path = Kompendium.calculatePath(this) - Kompendium.openApiSpec.paths.getOrPut(path) { OpenApiSpecPathItem() } - Kompendium.openApiSpec.paths[path]?.post = parseMethodInfo(info, paramType, requestType, responseType) - return method(HttpMethod.Post) { handle(body) } - } - - /** - * Notarization for an HTTP Delete request - * @param TParam The class containing all parameter fields. - * Each field must be annotated with @[io.bkbn.kompendium.annotations.KompendiumField] - * @param TReq Class detailing the expected API request body - * @param TResp Class detailing the expected API response - * @param info Route metadata - */ - inline fun Route.notarizedPut( - info: PutInfo, - noinline body: PipelineInterceptor, - ): Route = - KompendiumPreFlight.methodNotarizationPreFlight() { paramType, requestType, responseType -> - val path = Kompendium.calculatePath(this) - Kompendium.openApiSpec.paths.getOrPut(path) { OpenApiSpecPathItem() } - Kompendium.openApiSpec.paths[path]?.put = - parseMethodInfo(info, paramType, requestType, responseType) - return method(HttpMethod.Put) { handle(body) } - } - - /** - * Notarization for an HTTP POST request - * @param TParam The class containing all parameter fields. - * Each field must be annotated with @[io.bkbn.kompendium.annotations.KompendiumField] - * @param TResp Class detailing the expected API response - * @param info Route metadata - */ - inline fun Route.notarizedDelete( - info: DeleteInfo, - noinline body: PipelineInterceptor - ): Route = - KompendiumPreFlight.methodNotarizationPreFlight { paramType, requestType, responseType -> - val path = Kompendium.calculatePath(this) - Kompendium.openApiSpec.paths.getOrPut(path) { OpenApiSpecPathItem() } - Kompendium.openApiSpec.paths[path]?.delete = parseMethodInfo(info, paramType, requestType, responseType) - return method(HttpMethod.Delete) { handle(body) } - } - - /** - * Notarization for a handled exception response - * @param TErr The [Throwable] that is being handled - * @param TResp Class detailing the expected API response when handled - * @param info Response metadata - */ - inline fun StatusPages.Configuration.notarizedException( - info: ResponseInfo, - noinline handler: suspend PipelineContext.(TErr) -> Unit - ) = errorNotarizationPreFlight() { errorType, responseType -> - info.parseErrorInfo(errorType, responseType) - exception(handler) - } -} diff --git a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/annotations/UndeclaredField.kt b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/annotations/UndeclaredField.kt deleted file mode 100644 index 692aa5b1b..000000000 --- a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/annotations/UndeclaredField.kt +++ /dev/null @@ -1,8 +0,0 @@ -package io.bkbn.kompendium.annotations - -import kotlin.reflect.KClass - -@Retention(AnnotationRetention.RUNTIME) -@Target(AnnotationTarget.CLASS) -@Repeatable -annotation class UndeclaredField(val field: String, val clazz: KClass<*>) diff --git a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/core/Kompendium.kt b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/core/Kompendium.kt new file mode 100644 index 000000000..36ba72379 --- /dev/null +++ b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/core/Kompendium.kt @@ -0,0 +1,55 @@ +package io.bkbn.kompendium.core + +import com.fasterxml.jackson.annotation.JsonInclude +import com.fasterxml.jackson.databind.ObjectMapper +import com.fasterxml.jackson.databind.SerializationFeature +import io.bkbn.kompendium.core.metadata.SchemaMap +import io.bkbn.kompendium.oas.OpenApiSpec +import io.bkbn.kompendium.oas.schema.TypedSchema +import io.ktor.application.Application +import io.ktor.application.ApplicationCallPipeline +import io.ktor.application.ApplicationFeature +import io.ktor.application.call +import io.ktor.http.HttpStatusCode +import io.ktor.request.path +import io.ktor.response.respondText +import io.ktor.util.AttributeKey +import kotlin.reflect.KClass + +class Kompendium(val config: Configuration) { + + class Configuration { + lateinit var spec: OpenApiSpec + + var cache: SchemaMap = emptyMap() + var specRoute = "/openapi.json" + + // TODO Add tests for this!! + fun addCustomTypeSchema(clazz: KClass<*>, schema: TypedSchema) { + cache = cache.plus(clazz.simpleName!! to schema) + } + + // TODO Add tests for this!! + var om: ObjectMapper = ObjectMapper() + .setSerializationInclusion(JsonInclude.Include.NON_NULL) + .enable(SerializationFeature.INDENT_OUTPUT) + + fun specToJson(): String = om.writeValueAsString(spec) + } + + companion object Feature : ApplicationFeature { + override val key: AttributeKey = AttributeKey("Kompendium") + override fun install(pipeline: Application, configure: Configuration.() -> Unit): Kompendium { + val configuration = Configuration().apply(configure) + + pipeline.intercept(ApplicationCallPipeline.Call) { + if (call.request.path() == configuration.specRoute) { + call.respondText { configuration.specToJson() } + call.response.status(HttpStatusCode.OK) + } + } + + return Kompendium(configuration) + } + } +} diff --git a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/core/KompendiumPreFlight.kt b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/core/KompendiumPreFlight.kt new file mode 100644 index 000000000..5c20aa6e4 --- /dev/null +++ b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/core/KompendiumPreFlight.kt @@ -0,0 +1,39 @@ +package io.bkbn.kompendium.core + +import io.ktor.application.feature +import io.ktor.routing.Route +import io.ktor.routing.application +import kotlin.reflect.KType +import kotlin.reflect.typeOf + +/** + * Functions are considered preflight when they are used to intercept a method ahead of running. + */ +object KompendiumPreFlight { + + /** + * Performs all content analysis on the types provided to a notarized route and adds it to the top level spec + * @param TParam + * @param TReq + * @param TResp + * @param block The function to execute, provided type information of the parameters above + * @return [Route] + */ + @OptIn(ExperimentalStdlibApi::class) + inline fun Route.methodNotarizationPreFlight( + block: (KType, KType, KType) -> Route + ): Route { + val feature = this.application.feature(Kompendium) + val requestType = typeOf() + val responseType = typeOf() + val paramType = typeOf() + addToCache(paramType, requestType, responseType, feature) + return block.invoke(paramType, requestType, responseType) + } + + fun addToCache(paramType: KType, requestType: KType, responseType: KType, feature: Kompendium) { + feature.config.cache = Kontent.generateKontent(requestType, feature.config.cache) + feature.config.cache = Kontent.generateKontent(responseType, feature.config.cache) + feature.config.cache = Kontent.generateKontent(paramType, feature.config.cache) + } +} diff --git a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/core/Kontent.kt b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/core/Kontent.kt new file mode 100644 index 000000000..f97dfd06b --- /dev/null +++ b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/core/Kontent.kt @@ -0,0 +1,457 @@ +package io.bkbn.kompendium.core + +import io.bkbn.kompendium.annotations.Field +import io.bkbn.kompendium.annotations.FreeFormObject +import io.bkbn.kompendium.annotations.UndeclaredField +import io.bkbn.kompendium.annotations.constraint.Format +import io.bkbn.kompendium.annotations.constraint.MaxItems +import io.bkbn.kompendium.annotations.constraint.MaxLength +import io.bkbn.kompendium.annotations.constraint.MaxProperties +import io.bkbn.kompendium.annotations.constraint.Maximum +import io.bkbn.kompendium.annotations.constraint.MinItems +import io.bkbn.kompendium.annotations.constraint.MinLength +import io.bkbn.kompendium.annotations.constraint.MinProperties +import io.bkbn.kompendium.annotations.constraint.Minimum +import io.bkbn.kompendium.annotations.constraint.MultipleOf +import io.bkbn.kompendium.annotations.constraint.Pattern +import io.bkbn.kompendium.annotations.constraint.UniqueItems +import io.bkbn.kompendium.core.metadata.SchemaMap +import io.bkbn.kompendium.core.metadata.TypeMap +import io.bkbn.kompendium.core.util.Helpers.genericNameAdapter +import io.bkbn.kompendium.core.util.Helpers.getSimpleSlug +import io.bkbn.kompendium.core.util.Helpers.logged +import io.bkbn.kompendium.core.util.Helpers.toNumber +import io.bkbn.kompendium.oas.schema.AnyOfSchema +import io.bkbn.kompendium.oas.schema.ArraySchema +import io.bkbn.kompendium.oas.schema.ComponentSchema +import io.bkbn.kompendium.oas.schema.DictionarySchema +import io.bkbn.kompendium.oas.schema.EnumSchema +import io.bkbn.kompendium.oas.schema.FormattedSchema +import io.bkbn.kompendium.oas.schema.FreeFormSchema +import io.bkbn.kompendium.oas.schema.ObjectSchema +import io.bkbn.kompendium.oas.schema.SimpleSchema +import kotlin.reflect.KClass +import kotlin.reflect.KClassifier +import kotlin.reflect.KProperty1 +import kotlin.reflect.KType +import kotlin.reflect.full.createType +import kotlin.reflect.full.findAnnotation +import kotlin.reflect.full.isSubclassOf +import kotlin.reflect.full.memberProperties +import kotlin.reflect.full.primaryConstructor +import kotlin.reflect.jvm.javaField +import kotlin.reflect.typeOf +import org.slf4j.LoggerFactory +import java.math.BigDecimal +import java.math.BigInteger +import java.util.UUID + +/** + * Responsible for generating the schema map that is used to power all object references across the API Spec. + */ +object Kontent { + + private val logger = LoggerFactory.getLogger(javaClass) + + /** + * Analyzes a type [T] for its top-level and any nested schemas, and adds them to a [SchemaMap], if provided + * @param T type to analyze + * @param cache Existing schema map to append to + * @return an updated schema map containing all type information for [T] + */ + @OptIn(ExperimentalStdlibApi::class) + inline fun generateKontent( + cache: SchemaMap = emptyMap() + ): SchemaMap { + val kontentType = typeOf() + return generateKTypeKontent(kontentType, cache) + } + + /** + * Analyzes a [KType] for its top-level and any nested schemas, and adds them to a [SchemaMap], if provided + * @param type [KType] to analyze + * @param cache Existing schema map to append to + * @return an updated schema map containing all type information for [KType] type + */ + fun generateKontent( + type: KType, + cache: SchemaMap = emptyMap() + ): SchemaMap { + var newCache = cache + gatherSubTypes(type).forEach { + newCache = generateKTypeKontent(it, newCache) + } + return newCache + } + + private fun gatherSubTypes(type: KType): List { + val classifier = type.classifier as KClass<*> + return if (classifier.isSealed) { + classifier.sealedSubclasses.map { + it.createType(type.arguments) + } + } else { + listOf(type) + } + } + + /** + * Recursively fills schema map depending on [KType] classifier + * @param type [KType] to parse + * @param cache Existing schema map to append to + */ + fun generateKTypeKontent( + type: KType, + cache: SchemaMap = emptyMap(), + ): SchemaMap = logged(object {}.javaClass.enclosingMethod.name, mapOf("cache" to cache)) { + logger.debug("Parsing Kontent of $type") + when (val clazz = type.classifier as KClass<*>) { + Unit::class -> cache + Int::class -> cache.plus(clazz.simpleName!! to FormattedSchema("int32", "integer")) + Long::class -> cache.plus(clazz.simpleName!! to FormattedSchema("int64", "integer")) + Double::class -> cache.plus(clazz.simpleName!! to FormattedSchema("double", "number")) + Float::class -> cache.plus(clazz.simpleName!! to FormattedSchema("float", "number")) + String::class -> cache.plus(clazz.simpleName!! to SimpleSchema("string")) + Boolean::class -> cache.plus(clazz.simpleName!! to SimpleSchema("boolean")) + UUID::class -> cache.plus(clazz.simpleName!! to FormattedSchema("uuid", "string")) + BigDecimal::class -> cache.plus(clazz.simpleName!! to FormattedSchema("double", "number")) + BigInteger::class -> cache.plus(clazz.simpleName!! to FormattedSchema("int64", "integer")) + ByteArray::class -> cache.plus(clazz.simpleName!! to FormattedSchema("byte", "string")) + else -> when { + clazz.isSubclassOf(Collection::class) -> handleCollectionType(type, clazz, cache) + clazz.isSubclassOf(Enum::class) -> handleEnumType(clazz, cache) + clazz.isSubclassOf(Map::class) -> handleMapType(type, clazz, cache) + else -> handleComplexType(type, clazz, cache) + } + } + } + + /** + * In the event of an object type, this method will parse out individual fields to recursively aggregate object map. + * @param clazz Class of the object to analyze + * @param cache Existing schema map to append to + */ + @Suppress("LongMethod", "ComplexMethod") + private fun handleComplexType(type: KType, clazz: KClass<*>, cache: SchemaMap): SchemaMap { + // This needs to be simple because it will be stored under its appropriate reference component implicitly + val slug = type.getSimpleSlug() + // Only analyze if component has not already been stored in the cache + return when (cache.containsKey(slug)) { + true -> { + logger.debug("Cache already contains $slug, returning cache untouched") + cache + } + false -> { + logger.debug("$slug was not found in cache, generating now") + var newCache = cache + // Grabs any type parameters mapped to the corresponding type argument(s) + val typeMap: TypeMap = clazz.typeParameters.zip(type.arguments).toMap() + // associates each member with a Pair of prop name to property schema + val fieldMap = clazz.memberProperties.associate { prop -> + logger.debug("Analyzing $prop in class $clazz") + // Grab the field of the current property + val field = prop.javaField?.type?.kotlin ?: error("Unable to parse field type from $prop") + // Short circuit if data is free form + val freeForm = prop.findAnnotation() + var name = prop.name + + // todo add method to clean up + when (freeForm) { + null -> { + val baseType = scanForGeneric(typeMap, prop) + val baseClazz = baseType.classifier as KClass<*> + val allTypes = scanForSealed(baseClazz, baseType) + newCache = updateCache(newCache, field, allTypes) + var propSchema = constructComponentSchema( + typeMap = typeMap, + prop = prop, + fieldClazz = field, + clazz = baseClazz, + type = baseType, + cache = newCache + ) + // todo move to helper + prop.findAnnotation()?.let { fieldOverrides -> + if (fieldOverrides.description.isNotBlank()) { + propSchema = propSchema.setDescription(fieldOverrides.description) + } + if (fieldOverrides.name.isNotBlank()) { + name = fieldOverrides.name + } + } + Pair(name, propSchema) + } + else -> { + val minProperties = prop.findAnnotation() + val maxProperties = prop.findAnnotation() + val schema = + FreeFormSchema(minProperties = minProperties?.properties, maxProperties = maxProperties?.properties) + Pair(name, schema) + } + } + } + logger.debug("Looking for undeclared fields") + val undeclaredFieldMap = clazz.annotations.filterIsInstance().associate { + val undeclaredType = it.clazz.createType() + newCache = generateKontent(undeclaredType, newCache) + it.field to newCache[undeclaredType.getSimpleSlug()]!! + } + logger.debug("$slug contains $fieldMap") + var schema = ObjectSchema(fieldMap.plus(undeclaredFieldMap)) + val requiredParams = clazz.primaryConstructor?.parameters?.filterNot { it.isOptional } ?: emptyList() + if (requiredParams.isNotEmpty()) { + schema = schema.copy(required = requiredParams.map { it.name!! }) + } + logger.debug("$slug schema: $schema") + newCache.plus(slug to schema) + } + } + } + + /** + * Takes the type information provided and adds any missing data to the schema map + */ + private fun updateCache(cache: SchemaMap, clazz: KClass<*>, types: List): SchemaMap { + var newCache = cache + if (!cache.containsKey(clazz.simpleName)) { + logger.debug("Cache was missing ${clazz.simpleName}, adding now") + types.forEach { + newCache = generateKTypeKontent(it, newCache) + } + } + return newCache + } + + /** + * Scans a class for sealed subclasses. If found, returns a list with all children. Otherwise, returns + * the base type + */ + private fun scanForSealed(clazz: KClass<*>, type: KType): List = if (clazz.isSealed) { + clazz.sealedSubclasses.map { it.createType(type.arguments) } + } else { + listOf(type) + } + + /** + * Yoinks any generic types from the type map should the field be a generic + */ + private fun scanForGeneric(typeMap: TypeMap, prop: KProperty1<*, *>): KType = + if (typeMap.containsKey(prop.returnType.classifier)) { + logger.debug("Generic type detected") + typeMap[prop.returnType.classifier]?.type!! + } else { + prop.returnType + } + + /** + * Constructs a [ComponentSchema] + */ + private fun constructComponentSchema( + typeMap: TypeMap, + clazz: KClass<*>, + fieldClazz: KClass<*>, + prop: KProperty1<*, *>, + type: KType, + cache: SchemaMap + ): ComponentSchema = + when (typeMap.containsKey(prop.returnType.classifier)) { + true -> handleGenericProperty(typeMap, clazz, type, prop.returnType.classifier, cache) + false -> handleStandardProperty(clazz, fieldClazz, prop, type, cache) + }.scanForConstraints(clazz, prop) + + private fun ComponentSchema.scanForConstraints(clazz: KClass<*>, prop: KProperty1<*, *>): ComponentSchema = + when (this) { + is AnyOfSchema -> AnyOfSchema(anyOf.map { it.scanForConstraints(clazz, prop) }) + is ArraySchema -> scanForConstraints(prop) + is DictionarySchema -> this // TODO Anything here? + is EnumSchema -> scanForConstraints(prop) + is FormattedSchema -> scanForConstraints(prop) + is FreeFormSchema -> this // todo anything here? + is ObjectSchema -> scanForConstraints(clazz, prop) + is SimpleSchema -> scanForConstraints(prop) + } + + private fun ArraySchema.scanForConstraints(prop: KProperty1<*, *>): ArraySchema { + val minItems = prop.findAnnotation() + val maxItems = prop.findAnnotation() + val uniqueItems = prop.findAnnotation() + + return this.copy( + minItems = minItems?.items, + maxItems = maxItems?.items, + uniqueItems = uniqueItems?.let { true } + ) + } + + private fun EnumSchema.scanForConstraints(prop: KProperty1<*, *>): EnumSchema { + if (prop.returnType.isMarkedNullable) { + return this.copy(nullable = true) + } + + return this + } + + private fun FormattedSchema.scanForConstraints(prop: KProperty1<*, *>): FormattedSchema { + val minimum = prop.findAnnotation() + val maximum = prop.findAnnotation() + val multipleOf = prop.findAnnotation() + + var schema = this + + if (prop.returnType.isMarkedNullable) { + schema = schema.copy(nullable = true) + } + + return schema.copy( + minimum = minimum?.min?.toNumber(), + maximum = maximum?.max?.toNumber(), + exclusiveMinimum = minimum?.exclusive, + exclusiveMaximum = maximum?.exclusive, + multipleOf = multipleOf?.multiple?.toNumber(), + ) + } + + private fun SimpleSchema.scanForConstraints(prop: KProperty1<*, *>): SimpleSchema { + val minLength = prop.findAnnotation() + val maxLength = prop.findAnnotation() + val pattern = prop.findAnnotation() + val format = prop.findAnnotation() + + var schema = this + + if (prop.returnType.isMarkedNullable) { + schema = schema.copy(nullable = true) + } + + return schema.copy( + minLength = minLength?.length, + maxLength = maxLength?.length, + pattern = pattern?.pattern, + format = format?.format + ) + } + + private fun ObjectSchema.scanForConstraints(clazz: KClass<*>, prop: KProperty1<*, *>): ObjectSchema { + val requiredParams = clazz.primaryConstructor?.parameters?.filterNot { it.isOptional } ?: emptyList() + var schema = this + + if (requiredParams.isNotEmpty()) { + schema = schema.copy(required = requiredParams.map { it.name!! }) + } + + if (prop.returnType.isMarkedNullable) { + schema = schema.copy(nullable = true) + } + + return schema + } + + /** + * If a field has no type parameters, build its [ComponentSchema] without referencing the [TypeMap] + */ + private fun handleStandardProperty( + clazz: KClass<*>, + fieldClazz: KClass<*>, + prop: KProperty1<*, *>, + type: KType, + cache: SchemaMap + ): ComponentSchema = if (clazz.isSealed) { + val refs = clazz.sealedSubclasses + .map { it.createType(type.arguments) } + .map { cache[it.getSimpleSlug()] ?: error("$it not found in cache") } + AnyOfSchema(refs) + } else { + val slug = fieldClazz.getSimpleSlug(prop) + cache[slug] ?: error("$slug not found in cache") + } + + /** + * If a field has type parameters, leverage the constructed [TypeMap] to construct the [ComponentSchema] + */ + private fun handleGenericProperty( + typeMap: TypeMap, + clazz: KClass<*>, + type: KType, + classifier: KClassifier?, + cache: SchemaMap + ): ComponentSchema = if (clazz.isSealed) { + val refs = clazz.sealedSubclasses + .map { it.createType(type.arguments) } + .map { it.getSimpleSlug() } + .map { cache[it] ?: error("$it not available in cache") } + AnyOfSchema(refs) + } else { + val slug = typeMap[classifier]?.type!!.getSimpleSlug() + cache[slug] ?: error("$slug not found in cache") + } + + /** + * Handler for when an [Enum] is encountered + * @param clazz Class of the object to analyze + * @param cache Existing schema map to append to + */ + private fun handleEnumType(clazz: KClass<*>, cache: SchemaMap): SchemaMap { + val options = clazz.java.enumConstants.map { it.toString() }.toSet() + return cache.plus(clazz.simpleName!! to EnumSchema(options)) + } + + /** + * Handler for when a [Map] is encountered + * @param type Map type information + * @param clazz Map class information + * @param cache Existing schema map to append to + */ + private fun handleMapType(type: KType, clazz: KClass<*>, cache: SchemaMap): SchemaMap { + logger.debug("Map detected for $type, generating schema and appending to cache") + val (keyType, valType) = type.arguments.map { it.type } + logger.debug("Obtained map types -> key: $keyType and value: $valType") + if (keyType?.classifier != String::class) { + error("Invalid Map $type: OpenAPI dictionaries must have keys of type String") + } + var updatedCache = generateKTypeKontent(valType!!, cache) + val valClass = valType.classifier as KClass<*> + val valClassName = valClass.simpleName + val referenceName = genericNameAdapter(type, clazz) + val valueReference = when (valClass.isSealed) { + true -> { + val subTypes = gatherSubTypes(valType) + AnyOfSchema(subTypes.map { + updatedCache = generateKTypeKontent(it, updatedCache) + updatedCache[it.getSimpleSlug()] ?: error("${it.getSimpleSlug()} not found") + }) + } + false -> updatedCache[valClassName] ?: error("$valClassName not found") + } + val schema = DictionarySchema(additionalProperties = valueReference) + updatedCache = generateKontent(valType, updatedCache) + return updatedCache.plus(referenceName to schema) + } + + /** + * Handler for when a [Collection] is encountered + * @param type Collection type information + * @param clazz Collection class information + * @param cache Existing schema map to append to + */ + private fun handleCollectionType(type: KType, clazz: KClass<*>, cache: SchemaMap): SchemaMap { + logger.debug("Collection detected for $type, generating schema and appending to cache") + val collectionType = type.arguments.first().type!! + val collectionClass = collectionType.classifier as KClass<*> + logger.debug("Obtained collection class: $collectionClass") + val referenceName = genericNameAdapter(type, clazz) + var updatedCache = generateKTypeKontent(collectionType, cache) + val valueReference = when (collectionClass.isSealed) { + true -> { + val subTypes = gatherSubTypes(collectionType) + AnyOfSchema(subTypes.map { + updatedCache = generateKTypeKontent(it, cache) + updatedCache[it.getSimpleSlug()] ?: error("${it.getSimpleSlug()} not found") + }) + } + false -> updatedCache[collectionClass.simpleName] ?: error("${collectionClass.simpleName} not found") + } + val schema = ArraySchema(items = valueReference) + updatedCache = generateKontent(collectionType, cache) + return updatedCache.plus(referenceName to schema) + } +} diff --git a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/MethodParser.kt b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/core/MethodParser.kt similarity index 55% rename from kompendium-core/src/main/kotlin/io/bkbn/kompendium/MethodParser.kt rename to kompendium-core/src/main/kotlin/io/bkbn/kompendium/core/MethodParser.kt index 0a8908586..117a17d75 100644 --- a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/MethodParser.kt +++ b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/core/MethodParser.kt @@ -1,23 +1,23 @@ -package io.bkbn.kompendium +package io.bkbn.kompendium.core -import io.bkbn.kompendium.annotations.KompendiumParam -import io.bkbn.kompendium.models.meta.MethodInfo -import io.bkbn.kompendium.models.meta.RequestInfo -import io.bkbn.kompendium.models.meta.ResponseInfo -import io.bkbn.kompendium.models.oas.ExampleWrapper -import io.bkbn.kompendium.models.oas.OpenApiAnyOf -import io.bkbn.kompendium.models.oas.OpenApiSpecMediaType -import io.bkbn.kompendium.models.oas.OpenApiSpecParameter -import io.bkbn.kompendium.models.oas.OpenApiSpecPathItemOperation -import io.bkbn.kompendium.models.oas.OpenApiSpecReferencable -import io.bkbn.kompendium.models.oas.OpenApiSpecReferenceObject -import io.bkbn.kompendium.models.oas.OpenApiSpecRequest -import io.bkbn.kompendium.models.oas.OpenApiSpecResponse -import io.bkbn.kompendium.util.Helpers -import io.bkbn.kompendium.util.Helpers.getReferenceSlug -import io.bkbn.kompendium.util.Helpers.getSimpleSlug -import java.util.Locale -import java.util.UUID +import io.bkbn.kompendium.annotations.Param +import io.bkbn.kompendium.core.Kontent.generateKontent +import io.bkbn.kompendium.core.metadata.ExceptionInfo +import io.bkbn.kompendium.core.metadata.RequestInfo +import io.bkbn.kompendium.core.metadata.ResponseInfo +import io.bkbn.kompendium.core.metadata.method.MethodInfo +import io.bkbn.kompendium.core.metadata.method.PostInfo +import io.bkbn.kompendium.core.metadata.method.PutInfo +import io.bkbn.kompendium.core.util.Helpers +import io.bkbn.kompendium.core.util.Helpers.capitalized +import io.bkbn.kompendium.core.util.Helpers.getSimpleSlug +import io.bkbn.kompendium.oas.path.PathOperation +import io.bkbn.kompendium.oas.payload.MediaType +import io.bkbn.kompendium.oas.payload.Parameter +import io.bkbn.kompendium.oas.payload.Request +import io.bkbn.kompendium.oas.payload.Response +import io.bkbn.kompendium.oas.schema.AnyOfSchema +import io.bkbn.kompendium.oas.schema.ObjectSchema import kotlin.reflect.KClass import kotlin.reflect.KParameter import kotlin.reflect.KProperty @@ -26,7 +26,8 @@ import kotlin.reflect.full.createType import kotlin.reflect.full.findAnnotation import kotlin.reflect.full.memberProperties import kotlin.reflect.full.primaryConstructor -import kotlin.reflect.jvm.javaField +import java.util.Locale +import java.util.UUID /** * The MethodParser is responsible for converting route metadata and types into an OpenAPI compatible data class. @@ -45,29 +46,19 @@ object MethodParser { info: MethodInfo<*, *>, paramType: KType, requestType: KType, - responseType: KType - ) = OpenApiSpecPathItemOperation( + responseType: KType, + feature: Kompendium + ) = PathOperation( summary = info.summary, description = info.description, operationId = info.operationId, tags = info.tags, deprecated = info.deprecated, - parameters = paramType.toParameterSpec(), - responses = responseType.toResponseSpec(info.responseInfo)?.let { mapOf(it) }.let { - when (it) { - null -> { - val throwables = parseThrowables(info.canThrow) - when (throwables.isEmpty()) { - true -> null - false -> throwables - } - } - else -> it.plus(parseThrowables(info.canThrow)) - } - }, + parameters = paramType.toParameterSpec(feature), + responses = parseResponse(responseType, info.responseInfo, feature).plus(parseExceptions(info.canThrow, feature)), requestBody = when (info) { - is MethodInfo.PutInfo<*, *, *> -> requestType.toRequestSpec(info.requestInfo) - is MethodInfo.PostInfo<*, *, *> -> requestType.toRequestSpec(info.requestInfo) + is PutInfo<*, *, *> -> requestType.toRequestSpec(info.requestInfo, feature) + is PostInfo<*, *, *> -> requestType.toRequestSpec(info.requestInfo, feature) else -> null }, security = if (info.securitySchemes.isNotEmpty()) listOf( @@ -76,57 +67,55 @@ object MethodParser { ) else null ) - /** - * Adds the error to the [Kompendium.errorMap] for reference in notarized routes. - * @param errorType [KType] of the throwable being handled - * @param responseType [KType] the type of the response sent in event of error - */ - fun ResponseInfo<*>.parseErrorInfo( - errorType: KType, - responseType: KType - ) { - Kompendium.errorMap = Kompendium.errorMap.plus(errorType to responseType.toResponseSpec(this)) + private fun parseResponse( + responseType: KType, + responseInfo: ResponseInfo<*>?, + feature: Kompendium + ): Map> = responseType.toResponseSpec(responseInfo, feature)?.let { mapOf(it) }.orEmpty() + + private fun parseExceptions( + exceptionInfo: Set>, + feature: Kompendium, + ): Map> = exceptionInfo.associate { info -> + feature.config.cache = generateKontent(info.responseType, feature.config.cache) + val response = Response( + description = info.description, + content = feature.resolveContent(info.responseType, info.mediaTypes, info.examples) + ) + Pair(info.status.value, response) } /** - * Parses possible errors thrown by a route - * @param throwables Set of classes that can be thrown - * @return Mapping of status codes to their corresponding error spec - */ - private fun parseThrowables(throwables: Set>): Map = throwables.mapNotNull { - Kompendium.errorMap[it.createType()] - }.toMap() - - /** - * Converts a [KType] to an [OpenApiSpecRequest] + * Converts a [KType] to an [Request] * @receiver [KType] to convert * @param requestInfo request metadata - * @return Will return a generated [OpenApiSpecRequest] if requestInfo is not null + * @return Will return a generated [Request] if requestInfo is not null */ - private fun KType.toRequestSpec(requestInfo: RequestInfo<*>?): OpenApiSpecRequest<*>? = + private fun KType.toRequestSpec(requestInfo: RequestInfo<*>?, feature: Kompendium): Request<*>? = when (requestInfo) { null -> null else -> { - OpenApiSpecRequest( + Request( description = requestInfo.description, - content = resolveContent(this, requestInfo.mediaTypes, requestInfo.examples) ?: mapOf() + content = feature.resolveContent(this, requestInfo.mediaTypes, requestInfo.examples) ?: mapOf(), + required = requestInfo.required ) } } /** - * Converts a [KType] to a pairing of http status code to [OpenApiSpecRequest] + * Converts a [KType] to a pairing of http status code to [Response] * @receiver [KType] to convert * @param responseInfo response metadata * @return Will return a generated [Pair] if responseInfo is not null */ - private fun KType.toResponseSpec(responseInfo: ResponseInfo<*>?): Pair>? = + private fun KType.toResponseSpec(responseInfo: ResponseInfo<*>?, feature: Kompendium): Pair>? = when (responseInfo) { null -> null else -> { - val specResponse = OpenApiSpecResponse( + val specResponse = Response( description = responseInfo.description, - content = resolveContent(this, responseInfo.mediaTypes, responseInfo.examples) + content = feature.resolveContent(this, responseInfo.mediaTypes, responseInfo.examples) ) Pair(responseInfo.status.value, specResponse) } @@ -139,27 +128,27 @@ object MethodParser { * @param examples Mapping of named examples of valid bodies. * @return Named mapping of media types. */ - private fun resolveContent( + private fun Kompendium.resolveContent( type: KType, mediaTypes: List, examples: Map - ): Map>? { + ): Map>? { val classifier = type.classifier as KClass<*> return if (type != Helpers.UNIT_TYPE && mediaTypes.isNotEmpty()) { mediaTypes.associateWith { val schema = if (classifier.isSealed) { val refs = classifier.sealedSubclasses .map { it.createType(type.arguments) } - .map { it.getReferenceSlug() } - .map { OpenApiSpecReferenceObject(it) } - OpenApiAnyOf(refs) + .map { it.getSimpleSlug() } + .map { config.cache[it] ?: error("$it not available") } + AnyOfSchema(refs) } else { - val ref = type.getReferenceSlug() - OpenApiSpecReferenceObject(ref) + val ref = type.getSimpleSlug() + config.cache[ref] ?: error("$ref not available") } - OpenApiSpecMediaType( + MediaType( schema = schema, - examples = examples.mapValues { (_, v) -> ExampleWrapper(v) }.ifEmpty { null } + examples = examples.mapValues { (_, v) -> MediaType.Example(v) }.ifEmpty { null } ) } } else null @@ -167,29 +156,28 @@ object MethodParser { /** * Parses a type for all parameter information. All fields in the receiver - * must be annotated with [io.bkbn.kompendium.annotations.KompendiumParam]. + * must be annotated with [io.bkbn.kompendium.annotations.Param]. * @receiver type * @return list of valid parameter specs as detailed by the [KType] members * @throws [IllegalStateException] if the class could not be parsed properly */ - private fun KType.toParameterSpec(): List { + private fun KType.toParameterSpec(feature: Kompendium): List { val clazz = classifier as KClass<*> return clazz.memberProperties.filter { prop -> - prop.findAnnotation() != null + prop.findAnnotation() != null }.map { prop -> - val field = prop.javaField?.type?.kotlin - ?: error("Unable to parse field type from $prop") - val anny = prop.findAnnotation() + val wrapperSchema = feature.config.cache[this.getSimpleSlug()]!! as ObjectSchema + val anny = prop.findAnnotation() ?: error("Field ${prop.name} is not annotated with KompendiumParam") - val schema = Kompendium.cache[field.getSimpleSlug(prop)] + val schema = wrapperSchema.properties[prop.name] ?: error("Could not find component type for $prop") val defaultValue = getDefaultParameterValue(clazz, prop) - OpenApiSpecParameter( + Parameter( name = prop.name, `in` = anny.type.name.lowercase(Locale.getDefault()), schema = schema.addDefault(defaultValue), - description = anny.description.ifBlank { null }, - required = !prop.returnType.isMarkedNullable + description = schema.description, + required = !prop.returnType.isMarkedNullable && defaultValue == null ) } } @@ -215,7 +203,7 @@ object MethodParser { .associateWith { defaultValueInjector(it) } val instance = constructor.callBy(values) val methods = clazz.java.methods - val getterName = "get${prop.name.capitalize()}" + val getterName = "get${prop.name.capitalized()}" val getterFunction = methods.find { it.name == getterName } ?: error("Could not associate ${prop.name} with a getter") return getterFunction.invoke(instance) diff --git a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/core/Notarized.kt b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/core/Notarized.kt new file mode 100644 index 000000000..897a7ac87 --- /dev/null +++ b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/core/Notarized.kt @@ -0,0 +1,114 @@ +package io.bkbn.kompendium.core + +import io.bkbn.kompendium.annotations.Param +import io.bkbn.kompendium.core.KompendiumPreFlight.methodNotarizationPreFlight +import io.bkbn.kompendium.core.MethodParser.parseMethodInfo +import io.bkbn.kompendium.core.metadata.method.DeleteInfo +import io.bkbn.kompendium.core.metadata.method.GetInfo +import io.bkbn.kompendium.core.metadata.method.PostInfo +import io.bkbn.kompendium.core.metadata.method.PutInfo +import io.bkbn.kompendium.oas.path.Path +import io.bkbn.kompendium.oas.path.PathOperation +import io.ktor.application.ApplicationCall +import io.ktor.application.feature +import io.ktor.http.HttpMethod +import io.ktor.routing.Route +import io.ktor.routing.application +import io.ktor.routing.method +import io.ktor.util.pipeline.PipelineInterceptor + +/** + * Notarization methods are the primary way that a Ktor API using Kompendium differentiates + * from a default Ktor application. On instantiation, a notarized route, provided with the proper metadata, + * will reflectively analyze all pertinent data to build a corresponding OpenAPI entry. + */ +object Notarized { + + /** + * Notarization for an HTTP GET request + * @param TParam The class containing all parameter fields. Each field must be annotated with @[Param] + * @param TResp Class detailing the expected API response + * @param info Route metadata + * @param postProcess Adds an optional callback hook to perform manual overrides on the generated [PathOperation] + */ + inline fun Route.notarizedGet( + info: GetInfo, + postProcess: (PathOperation) -> PathOperation = { p -> p }, + noinline body: PipelineInterceptor + ): Route = methodNotarizationPreFlight { paramType, requestType, responseType -> + val feature = this.application.feature(Kompendium) + val path = calculateRoutePath() + feature.config.spec.paths.getOrPut(path) { Path() } + val baseInfo = parseMethodInfo(info, paramType, requestType, responseType, feature) + feature.config.spec.paths[path]?.get = postProcess(baseInfo) + return method(HttpMethod.Get) { handle(body) } + } + + /** + * Notarization for an HTTP POST request + * @param TParam The class containing all parameter fields. Each field must be annotated with @[Param] + * @param TReq Class detailing the expected API request body + * @param TResp Class detailing the expected API response + * @param info Route metadata + * @param postProcess Adds an optional callback hook to perform manual overrides on the generated [PathOperation] + */ + inline fun Route.notarizedPost( + info: PostInfo, + postProcess: (PathOperation) -> PathOperation = { p -> p }, + noinline body: PipelineInterceptor + ): Route = methodNotarizationPreFlight { paramType, requestType, responseType -> + val feature = this.application.feature(Kompendium) + val path = calculateRoutePath() + feature.config.spec.paths.getOrPut(path) { Path() } + val baseInfo = parseMethodInfo(info, paramType, requestType, responseType, feature) + feature.config.spec.paths[path]?.post = postProcess(baseInfo) + return method(HttpMethod.Post) { handle(body) } + } + + /** + * Notarization for an HTTP Delete request + * @param TParam The class containing all parameter fields. Each field must be annotated with @[Param] + * @param TReq Class detailing the expected API request body + * @param TResp Class detailing the expected API response + * @param info Route metadata + * @param postProcess Adds an optional callback hook to perform manual overrides on the generated [PathOperation] + */ + inline fun Route.notarizedPut( + info: PutInfo, + postProcess: (PathOperation) -> PathOperation = { p -> p }, + noinline body: PipelineInterceptor, + ): Route = methodNotarizationPreFlight { paramType, requestType, responseType -> + val feature = this.application.feature(Kompendium) + val path = calculateRoutePath() + feature.config.spec.paths.getOrPut(path) { Path() } + val baseInfo = parseMethodInfo(info, paramType, requestType, responseType, feature) + feature.config.spec.paths[path]?.put = postProcess(baseInfo) + return method(HttpMethod.Put) { handle(body) } + } + + /** + * Notarization for an HTTP POST request + * @param TParam The class containing all parameter fields. Each field must be annotated with @[Param] + * @param TResp Class detailing the expected API response + * @param info Route metadata + * @param postProcess Adds an optional callback hook to perform manual overrides on the generated [PathOperation] + */ + inline fun Route.notarizedDelete( + info: DeleteInfo, + postProcess: (PathOperation) -> PathOperation = { p -> p }, + noinline body: PipelineInterceptor + ): Route = methodNotarizationPreFlight { paramType, requestType, responseType -> + val feature = this.application.feature(Kompendium) + val path = calculateRoutePath() + feature.config.spec.paths.getOrPut(path) { Path() } + val baseInfo = parseMethodInfo(info, paramType, requestType, responseType, feature) + feature.config.spec.paths[path]?.delete = postProcess(baseInfo) + return method(HttpMethod.Delete) { handle(body) } + } + + /** + * Uses the built-in Ktor route path [Route.toString] but cuts out any meta route such as authentication... anything + * that matches the RegEx pattern `/\\(.+\\)` + */ + fun Route.calculateRoutePath() = toString().replace(Regex("/\\(.+\\)"), "") +} diff --git a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/core/metadata/ExceptionInfo.kt b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/core/metadata/ExceptionInfo.kt new file mode 100644 index 000000000..44d8cb71a --- /dev/null +++ b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/core/metadata/ExceptionInfo.kt @@ -0,0 +1,12 @@ +package io.bkbn.kompendium.core.metadata + +import io.ktor.http.HttpStatusCode +import kotlin.reflect.KType + +data class ExceptionInfo( + val responseType: KType, + val status: HttpStatusCode, + val description: String, + val mediaTypes: List = listOf("application/json"), + val examples: Map = emptyMap() +) diff --git a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/meta/RequestInfo.kt b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/core/metadata/RequestInfo.kt similarity index 82% rename from kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/meta/RequestInfo.kt rename to kompendium-core/src/main/kotlin/io/bkbn/kompendium/core/metadata/RequestInfo.kt index f9c825427..1507cdd1d 100644 --- a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/meta/RequestInfo.kt +++ b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/core/metadata/RequestInfo.kt @@ -1,4 +1,4 @@ -package io.bkbn.kompendium.models.meta +package io.bkbn.kompendium.core.metadata data class RequestInfo( val description: String, diff --git a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/meta/ResponseInfo.kt b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/core/metadata/ResponseInfo.kt similarity index 85% rename from kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/meta/ResponseInfo.kt rename to kompendium-core/src/main/kotlin/io/bkbn/kompendium/core/metadata/ResponseInfo.kt index 78c3ce4af..e01bed823 100644 --- a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/meta/ResponseInfo.kt +++ b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/core/metadata/ResponseInfo.kt @@ -1,4 +1,4 @@ -package io.bkbn.kompendium.models.meta +package io.bkbn.kompendium.core.metadata import io.ktor.http.HttpStatusCode diff --git a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/core/metadata/SchemaMap.kt b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/core/metadata/SchemaMap.kt new file mode 100644 index 000000000..92889ca6e --- /dev/null +++ b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/core/metadata/SchemaMap.kt @@ -0,0 +1,5 @@ +package io.bkbn.kompendium.core.metadata + +import io.bkbn.kompendium.oas.schema.ComponentSchema + +typealias SchemaMap = Map diff --git a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/core/metadata/TypeMap.kt b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/core/metadata/TypeMap.kt new file mode 100644 index 000000000..bdfb5aa20 --- /dev/null +++ b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/core/metadata/TypeMap.kt @@ -0,0 +1,6 @@ +package io.bkbn.kompendium.core.metadata + +import kotlin.reflect.KTypeParameter +import kotlin.reflect.KTypeProjection + +typealias TypeMap = Map diff --git a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/core/metadata/method/DeleteInfo.kt b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/core/metadata/method/DeleteInfo.kt new file mode 100644 index 000000000..07548b36c --- /dev/null +++ b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/core/metadata/method/DeleteInfo.kt @@ -0,0 +1,16 @@ +package io.bkbn.kompendium.core.metadata.method + +import io.bkbn.kompendium.core.metadata.ExceptionInfo +import io.bkbn.kompendium.core.metadata.ResponseInfo + +data class DeleteInfo( + override val responseInfo: ResponseInfo, + override val summary: String, + override val description: String? = null, + override val tags: Set = emptySet(), + override val deprecated: Boolean = false, + override val securitySchemes: Set = emptySet(), + override val canThrow: Set> = emptySet(), + override val parameterExamples: Map = emptyMap(), + override val operationId: String? = null +) : MethodInfo diff --git a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/core/metadata/method/GetInfo.kt b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/core/metadata/method/GetInfo.kt new file mode 100644 index 000000000..420c83501 --- /dev/null +++ b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/core/metadata/method/GetInfo.kt @@ -0,0 +1,16 @@ +package io.bkbn.kompendium.core.metadata.method + +import io.bkbn.kompendium.core.metadata.ExceptionInfo +import io.bkbn.kompendium.core.metadata.ResponseInfo + +data class GetInfo( + override val responseInfo: ResponseInfo, + override val summary: String, + override val description: String? = null, + override val tags: Set = emptySet(), + override val deprecated: Boolean = false, + override val securitySchemes: Set = emptySet(), + override val canThrow: Set> = emptySet(), + override val parameterExamples: Map = emptyMap(), + override val operationId: String? = null +) : MethodInfo diff --git a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/core/metadata/method/MethodInfo.kt b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/core/metadata/method/MethodInfo.kt new file mode 100644 index 000000000..9ffe33a90 --- /dev/null +++ b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/core/metadata/method/MethodInfo.kt @@ -0,0 +1,24 @@ +package io.bkbn.kompendium.core.metadata.method + +import io.bkbn.kompendium.core.metadata.ExceptionInfo +import io.bkbn.kompendium.core.metadata.ResponseInfo + +sealed interface MethodInfo { + val summary: String + val description: String? + get() = null + val tags: Set + get() = emptySet() + val deprecated: Boolean + get() = false + val securitySchemes: Set + get() = emptySet() + val canThrow: Set> + get() = emptySet() + val responseInfo: ResponseInfo + // TODO Is this even used anywhere? + val parameterExamples: Map + get() = emptyMap() + val operationId: String? + get() = null +} diff --git a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/core/metadata/method/PostInfo.kt b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/core/metadata/method/PostInfo.kt new file mode 100644 index 000000000..25058686a --- /dev/null +++ b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/core/metadata/method/PostInfo.kt @@ -0,0 +1,18 @@ +package io.bkbn.kompendium.core.metadata.method + +import io.bkbn.kompendium.core.metadata.ExceptionInfo +import io.bkbn.kompendium.core.metadata.RequestInfo +import io.bkbn.kompendium.core.metadata.ResponseInfo + +data class PostInfo( + val requestInfo: RequestInfo?, + override val responseInfo: ResponseInfo, + override val summary: String, + override val description: String? = null, + override val tags: Set = emptySet(), + override val deprecated: Boolean = false, + override val securitySchemes: Set = emptySet(), + override val canThrow: Set> = emptySet(), + override val parameterExamples: Map = emptyMap(), + override val operationId: String? = null +) : MethodInfo diff --git a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/core/metadata/method/PutInfo.kt b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/core/metadata/method/PutInfo.kt new file mode 100644 index 000000000..9331ef2e9 --- /dev/null +++ b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/core/metadata/method/PutInfo.kt @@ -0,0 +1,18 @@ +package io.bkbn.kompendium.core.metadata.method + +import io.bkbn.kompendium.core.metadata.ExceptionInfo +import io.bkbn.kompendium.core.metadata.RequestInfo +import io.bkbn.kompendium.core.metadata.ResponseInfo + +data class PutInfo( + val requestInfo: RequestInfo, + override val responseInfo: ResponseInfo, + override val summary: String, + override val description: String? = null, + override val tags: Set = emptySet(), + override val deprecated: Boolean = false, + override val securitySchemes: Set = emptySet(), + override val canThrow: Set> = emptySet(), + override val parameterExamples: Map = emptyMap(), + override val operationId: String? = null +) : MethodInfo diff --git a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/routes/Redoc.kt b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/core/routes/Redoc.kt similarity index 85% rename from kompendium-core/src/main/kotlin/io/bkbn/kompendium/routes/Redoc.kt rename to kompendium-core/src/main/kotlin/io/bkbn/kompendium/core/routes/Redoc.kt index 53f7cc3b6..cfe22bf47 100644 --- a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/routes/Redoc.kt +++ b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/core/routes/Redoc.kt @@ -1,4 +1,4 @@ -package io.bkbn.kompendium.routes +package io.bkbn.kompendium.core.routes import io.ktor.application.call import io.ktor.html.respondHtml @@ -13,20 +13,19 @@ import kotlinx.html.script import kotlinx.html.style import kotlinx.html.title import kotlinx.html.unsafe -import io.bkbn.kompendium.models.oas.OpenApiSpec /** * Provides an out-of-the-box route to view docs using ReDoc - * @param oas spec to reference + * @param pageTitle Webpage title you wish to be displayed on your docs * @param specUrl url to point ReDoc to the OpenAPI json document */ -fun Routing.redoc(oas: OpenApiSpec, specUrl: String = "/openapi.json") { +fun Routing.redoc(pageTitle: String = "Docs", specUrl: String = "/openapi.json") { route("/docs") { get { call.respondHtml { head { title { - +"${oas.info.title}" + +"$pageTitle" } meta { charset = "utf-8" diff --git a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/util/Helpers.kt b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/core/util/Helpers.kt similarity index 83% rename from kompendium-core/src/main/kotlin/io/bkbn/kompendium/util/Helpers.kt rename to kompendium-core/src/main/kotlin/io/bkbn/kompendium/core/util/Helpers.kt index 19e2582de..9628ee4c1 100644 --- a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/util/Helpers.kt +++ b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/core/util/Helpers.kt @@ -1,6 +1,5 @@ -package io.bkbn.kompendium.util +package io.bkbn.kompendium.core.util -import io.bkbn.kompendium.util.Helpers.getReferenceSlug import java.lang.reflect.ParameterizedType import kotlin.reflect.KClass import kotlin.reflect.KProperty @@ -8,17 +7,18 @@ import kotlin.reflect.KType import kotlin.reflect.full.createType import kotlin.reflect.jvm.javaField import org.slf4j.LoggerFactory +import java.util.Locale object Helpers { private val logger = LoggerFactory.getLogger(javaClass) - const val COMPONENT_SLUG = "#/components/schemas" + private const val COMPONENT_SLUG = "#/components/schemas" val UNIT_TYPE by lazy { Unit::class.createType() } /** - * Higher order function that takes a map of names to objects and will log their state ahead of function invocation + * Higher order function that takes a map of names to object and will log their state ahead of function invocation * along with the result of the function invocation */ fun logged(functionName: String, entities: Map, block: () -> T): T { @@ -70,4 +70,16 @@ object Helpers { .map { it.simpleName } return classNames.joinToString(separator = "-", prefix = "${clazz.simpleName}-") } + + fun String.capitalized() = replaceFirstChar { + if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString() + } + + fun String.toNumber(): Number { + return try { + this.toInt() + } catch (e: NumberFormatException) { + this.toDouble() + } + } } diff --git a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/meta/ErrorMap.kt b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/meta/ErrorMap.kt deleted file mode 100644 index c9b02f345..000000000 --- a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/meta/ErrorMap.kt +++ /dev/null @@ -1,6 +0,0 @@ -package io.bkbn.kompendium.models.meta - -import kotlin.reflect.KType -import io.bkbn.kompendium.models.oas.OpenApiSpecResponse - -typealias ErrorMap = Map>?> diff --git a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/meta/MethodInfo.kt b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/meta/MethodInfo.kt deleted file mode 100644 index 0b54858f1..000000000 --- a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/meta/MethodInfo.kt +++ /dev/null @@ -1,104 +0,0 @@ -package io.bkbn.kompendium.models.meta - -import kotlin.reflect.KClass - -sealed class MethodInfo( - open val summary: String, - open val description: String? = null, - open val tags: Set = emptySet(), - open val deprecated: Boolean = false, - open val securitySchemes: Set = emptySet(), - open val canThrow: Set> = emptySet(), - open val responseInfo: ResponseInfo? = null, - open val parameterExamples: Map = emptyMap(), - open val operationId: String? = null -) { - - data class GetInfo( - override val responseInfo: ResponseInfo? = null, - override val summary: String, - override val description: String? = null, - override val tags: Set = emptySet(), - override val deprecated: Boolean = false, - override val securitySchemes: Set = emptySet(), - override val canThrow: Set> = emptySet(), - override val parameterExamples: Map = emptyMap(), - override val operationId: String? = null - ) : MethodInfo( - summary = summary, - description = description, - tags = tags, - deprecated = deprecated, - securitySchemes = securitySchemes, - canThrow = canThrow, - responseInfo = responseInfo, - parameterExamples = parameterExamples, - operationId = operationId - ) - - data class PostInfo( - val requestInfo: RequestInfo? = null, - override val responseInfo: ResponseInfo? = null, - override val summary: String, - override val description: String? = null, - override val tags: Set = emptySet(), - override val deprecated: Boolean = false, - override val securitySchemes: Set = emptySet(), - override val canThrow: Set> = emptySet(), - override val parameterExamples: Map = emptyMap(), - override val operationId: String? = null - ) : MethodInfo( - summary = summary, - description = description, - tags = tags, - deprecated = deprecated, - securitySchemes = securitySchemes, - canThrow = canThrow, - responseInfo = responseInfo, - parameterExamples = parameterExamples, - operationId = operationId - ) - - data class PutInfo( - val requestInfo: RequestInfo? = null, - override val responseInfo: ResponseInfo? = null, - override val summary: String, - override val description: String? = null, - override val tags: Set = emptySet(), - override val deprecated: Boolean = false, - override val securitySchemes: Set = emptySet(), - override val canThrow: Set> = emptySet(), - override val parameterExamples: Map = emptyMap(), - override val operationId: String? = null - ) : MethodInfo( - summary = summary, - description = description, - tags = tags, - deprecated = deprecated, - securitySchemes = securitySchemes, - canThrow = canThrow, - parameterExamples = parameterExamples, - operationId = operationId - ) - - data class DeleteInfo( - override val responseInfo: ResponseInfo? = null, - override val summary: String, - override val description: String? = null, - override val tags: Set = emptySet(), - override val deprecated: Boolean = false, - override val securitySchemes: Set = emptySet(), - override val canThrow: Set> = emptySet(), - override val parameterExamples: Map = emptyMap(), - override val operationId: String? = null - ) : MethodInfo( - summary = summary, - description = description, - tags = tags, - deprecated = deprecated, - securitySchemes = securitySchemes, - canThrow = canThrow, - parameterExamples = parameterExamples, - operationId = operationId - ) -} diff --git a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/meta/SchemaMap.kt b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/meta/SchemaMap.kt deleted file mode 100644 index 11e9b8372..000000000 --- a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/meta/SchemaMap.kt +++ /dev/null @@ -1,5 +0,0 @@ -package io.bkbn.kompendium.models.meta - -import io.bkbn.kompendium.models.oas.OpenApiSpecComponentSchema - -typealias SchemaMap = Map diff --git a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpec.kt b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpec.kt deleted file mode 100644 index 5eb07bcf7..000000000 --- a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpec.kt +++ /dev/null @@ -1,14 +0,0 @@ -package io.bkbn.kompendium.models.oas - -data class OpenApiSpec( - val openapi: String = "3.0.3", - val info: OpenApiSpecInfo, - // TODO Needs to default to server object with url of `/` - val servers: MutableList = mutableListOf(), - val paths: MutableMap = mutableMapOf(), - val components: OpenApiSpecComponents = OpenApiSpecComponents(), - // todo needs to reference objects in the components -> security scheme 🤔 - val security: MutableList>> = mutableListOf(), - val tags: MutableList = mutableListOf(), - val externalDocs: OpenApiSpecExternalDocumentation? = null -) diff --git a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpecComponentSchema.kt b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpecComponentSchema.kt deleted file mode 100644 index a54733bda..000000000 --- a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpecComponentSchema.kt +++ /dev/null @@ -1,42 +0,0 @@ -package io.bkbn.kompendium.models.oas - -sealed class OpenApiSpecComponentSchema(open val default: Any? = null) { - fun addDefault(default: Any?): OpenApiSpecComponentSchema = when (this) { - is AnyOfReferencedSchema -> error("Cannot add default to anyOf reference") - is ReferencedSchema -> this.copy(default = default) - is ObjectSchema -> this.copy(default = default) - is DictionarySchema -> this.copy(default = default) - is EnumSchema -> this.copy(default = default) - is SimpleSchema -> this.copy(default = default) - is FormatSchema -> this.copy(default = default) - is ArraySchema -> this.copy(default = default) - } -} - -sealed class TypedSchema(open val type: String, override val default: Any? = null) : OpenApiSpecComponentSchema(default) - -data class ReferencedSchema(val `$ref`: String, override val default: Any? = null) : OpenApiSpecComponentSchema(default) -data class AnyOfReferencedSchema(val anyOf: List) : OpenApiSpecComponentSchema() - -data class ObjectSchema( - val properties: Map, - override val default: Any? = null -) : TypedSchema("object", default) - -data class DictionarySchema( - val additionalProperties: OpenApiSpecComponentSchema, - override val default: Any? = null -) : TypedSchema("object", default) - -data class EnumSchema( - val `enum`: Set, override val default: Any? = null -) : TypedSchema("string", default) - -data class SimpleSchema(override val type: String, override val default: Any? = null) : TypedSchema(type, default) - -data class FormatSchema(val format: String, override val type: String, override val default: Any? = null) : - TypedSchema(type, default) - -data class ArraySchema(val items: OpenApiSpecComponentSchema, override val default: Any? = null) : - TypedSchema("array", default) - diff --git a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpecComponents.kt b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpecComponents.kt deleted file mode 100644 index 49c628a52..000000000 --- a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpecComponents.kt +++ /dev/null @@ -1,7 +0,0 @@ -package io.bkbn.kompendium.models.oas - -// TODO I *think* the only thing I need here is the security https://swagger.io/specification/#components-object -data class OpenApiSpecComponents( - val schemas: MutableMap = mutableMapOf(), - val securitySchemes: MutableMap = mutableMapOf() -) diff --git a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpecExternalDocumentation.kt b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpecExternalDocumentation.kt deleted file mode 100644 index 9b1704f3a..000000000 --- a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpecExternalDocumentation.kt +++ /dev/null @@ -1,8 +0,0 @@ -package io.bkbn.kompendium.models.oas - -import java.net.URI - -data class OpenApiSpecExternalDocumentation( - val url: URI, - val description: String? -) diff --git a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpecInfo.kt b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpecInfo.kt deleted file mode 100644 index 2ae05380d..000000000 --- a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpecInfo.kt +++ /dev/null @@ -1,12 +0,0 @@ -package io.bkbn.kompendium.models.oas - -import java.net.URI - -data class OpenApiSpecInfo( - var title: String? = null, - var version: String? = null, - var description: String? = null, - var termsOfService: URI? = null, - var contact: OpenApiSpecInfoContact? = null, - var license: OpenApiSpecInfoLicense? = null -) diff --git a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpecInfoLicense.kt b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpecInfoLicense.kt deleted file mode 100644 index e6d8a81c7..000000000 --- a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpecInfoLicense.kt +++ /dev/null @@ -1,8 +0,0 @@ -package io.bkbn.kompendium.models.oas - -import java.net.URI - -data class OpenApiSpecInfoLicense( - var name: String, - var url: URI? = null -) diff --git a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpecLink.kt b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpecLink.kt deleted file mode 100644 index ee7161527..000000000 --- a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpecLink.kt +++ /dev/null @@ -1,10 +0,0 @@ -package io.bkbn.kompendium.models.oas - -data class OpenApiSpecLink( - val operationRef: String?, // todo mutually exclusive with operationId - val operationId: String?, - val parameters: Map, // todo sheesh https://swagger.io/specification/#link-object - val requestBody: String, // todo same - val description: String?, - val server: OpenApiSpecServer? -) diff --git a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpecMediaType.kt b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpecMediaType.kt deleted file mode 100644 index fb7ea6e0f..000000000 --- a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpecMediaType.kt +++ /dev/null @@ -1,8 +0,0 @@ -package io.bkbn.kompendium.models.oas - -data class OpenApiSpecMediaType( - val schema: OpenApiSpecReferencable, - val examples: Map>? = null -) - -data class ExampleWrapper(val value: T) diff --git a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpecOAuthFlow.kt b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpecOAuthFlow.kt deleted file mode 100644 index a39ac0260..000000000 --- a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpecOAuthFlow.kt +++ /dev/null @@ -1,10 +0,0 @@ -package io.bkbn.kompendium.models.oas - -import java.net.URI - -data class OpenApiSpecOAuthFlow( - val authorizationUrl: URI? = null, - val tokenUrl: URI? = null, - val refreshUrl: URI? = null, - val scopes: Map? = null -) diff --git a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpecOAuthFlows.kt b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpecOAuthFlows.kt deleted file mode 100644 index 7921096e3..000000000 --- a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpecOAuthFlows.kt +++ /dev/null @@ -1,5 +0,0 @@ -package io.bkbn.kompendium.models.oas - -data class OpenApiSpecOAuthFlows( - val implicit: OpenApiSpecOAuthFlow?, -) diff --git a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpecPathItem.kt b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpecPathItem.kt deleted file mode 100644 index 5020f7869..000000000 --- a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpecPathItem.kt +++ /dev/null @@ -1,14 +0,0 @@ -package io.bkbn.kompendium.models.oas - -data class OpenApiSpecPathItem( - var get: OpenApiSpecPathItemOperation? = null, - var put: OpenApiSpecPathItemOperation? = null, - var post: OpenApiSpecPathItemOperation? = null, - var delete: OpenApiSpecPathItemOperation? = null, - var options: OpenApiSpecPathItemOperation? = null, - var head: OpenApiSpecPathItemOperation? = null, - var patch: OpenApiSpecPathItemOperation? = null, - var trace: OpenApiSpecPathItemOperation? = null, - var servers: List? = null, - var parameters: List? = null -) diff --git a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpecPathItemOperation.kt b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpecPathItemOperation.kt deleted file mode 100644 index f57b3151a..000000000 --- a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpecPathItemOperation.kt +++ /dev/null @@ -1,19 +0,0 @@ -package io.bkbn.kompendium.models.oas - -data class OpenApiSpecPathItemOperation( - var tags: Set = emptySet(), - var summary: String? = null, - var description: String? = null, - var externalDocs: OpenApiSpecExternalDocumentation? = null, - var operationId: String? = null, - var parameters: List? = null, - var requestBody: OpenApiSpecReferencable? = null, - // TODO How to enforce `default` requirement 🧐 - var responses: Map? = null, - var callbacks: Map? = null, - var deprecated: Boolean = false, - // todo big yikes... also needs to reference objects in the security scheme 🤔 - var security: List>>? = null, - var servers: List? = null, - var `x-codegen-request-body-name`: String? = null -) diff --git a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpecReferencable.kt b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpecReferencable.kt deleted file mode 100644 index 2a9f6c353..000000000 --- a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpecReferencable.kt +++ /dev/null @@ -1,31 +0,0 @@ -package io.bkbn.kompendium.models.oas - -sealed interface OpenApiSpecReferencable - -data class OpenApiAnyOf(val anyOf: List) : OpenApiSpecReferencable -data class OpenApiSpecReferenceObject(val `$ref`: String) : OpenApiSpecReferencable - -data class OpenApiSpecResponse( - val description: String? = null, - val headers: Map? = null, - val content: Map>? = null, - val links: Map? = null -) : OpenApiSpecReferencable - -data class OpenApiSpecParameter( - val name: String, - val `in`: String, // TODO Enum? "query", "header", "path" or "cookie" - val schema: OpenApiSpecComponentSchema, - val description: String? = null, - val required: Boolean = true, - val deprecated: Boolean = false, - val allowEmptyValue: Boolean? = null, - val style: String? = null, - val explode: Boolean? = null -) : OpenApiSpecReferencable - -data class OpenApiSpecRequest( - val description: String?, - val content: Map>, - val required: Boolean = false -) : OpenApiSpecReferencable diff --git a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpecSchemaSecurity.kt b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpecSchemaSecurity.kt deleted file mode 100644 index eca2d9c9d..000000000 --- a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpecSchemaSecurity.kt +++ /dev/null @@ -1,11 +0,0 @@ -package io.bkbn.kompendium.models.oas - -data class OpenApiSpecSchemaSecurity( - val type: String? = null, // TODO Enum? "apiKey", "http", "oauth2", "openIdConnect" - val name: String? = null, - val `in`: String? = null, - val scheme: String? = null, - val flows: OpenApiSpecOAuthFlows? = null, - val bearerFormat: String? = null, - val description: String? = null, -) diff --git a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpecServer.kt b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpecServer.kt deleted file mode 100644 index 3f9372229..000000000 --- a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpecServer.kt +++ /dev/null @@ -1,9 +0,0 @@ -package io.bkbn.kompendium.models.oas - -import java.net.URI - -data class OpenApiSpecServer( - val url: URI, - val description: String? = null, - var variables: Map? = null -) diff --git a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpecTag.kt b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpecTag.kt deleted file mode 100644 index 07af2e495..000000000 --- a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpecTag.kt +++ /dev/null @@ -1,7 +0,0 @@ -package io.bkbn.kompendium.models.oas - -data class OpenApiSpecTag( - val name: String, - val description: String? = null, - val externalDocs: OpenApiSpecExternalDocumentation? = null -) diff --git a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/path/IPathCalculator.kt b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/path/IPathCalculator.kt deleted file mode 100644 index 8c4c4478c..000000000 --- a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/path/IPathCalculator.kt +++ /dev/null @@ -1,13 +0,0 @@ -package io.bkbn.kompendium.path - -import io.ktor.routing.Route -import io.ktor.routing.RouteSelector -import kotlin.reflect.KClass - -interface IPathCalculator { - fun calculate(route: Route?, tail: String = ""): String - fun addCustomRouteHandler( - selector: KClass, - handler: IPathCalculator.(Route, String) -> String - ) -} diff --git a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/path/PathCalculator.kt b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/path/PathCalculator.kt deleted file mode 100644 index a7aef148d..000000000 --- a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/path/PathCalculator.kt +++ /dev/null @@ -1,54 +0,0 @@ -package io.bkbn.kompendium.path - -import io.ktor.routing.PathSegmentConstantRouteSelector -import io.ktor.routing.PathSegmentParameterRouteSelector -import io.ktor.routing.RootRouteSelector -import io.ktor.routing.Route -import io.ktor.routing.RouteSelector -import io.ktor.routing.TrailingSlashRouteSelector -import io.ktor.util.InternalAPI -import kotlin.reflect.KClass - -/** - * Responsible for calculating a url path from a provided [Route] - */ -@OptIn(InternalAPI::class) -internal object PathCalculator: IPathCalculator { - - private val pathHandler: RouteHandlerMap = mutableMapOf() - - init { - addCustomRouteHandler(RootRouteSelector::class) { _, tail -> tail } - addCustomRouteHandler(PathSegmentParameterRouteSelector::class) { route, tail -> - val newTail = "/${route.selector}$tail" - calculate(route.parent, newTail) - } - addCustomRouteHandler(PathSegmentConstantRouteSelector::class) { route, tail -> - val newTail = "/${route.selector}$tail" - calculate(route.parent, newTail) - } - addCustomRouteHandler(TrailingSlashRouteSelector::class) { route, tail -> - val newTail = tail.ifBlank { "/" } - calculate(route.parent, newTail) - } - } - - @OptIn(InternalAPI::class) - override fun calculate( - route: Route?, - tail: String - ): String = when (route) { - null -> tail - else -> when (pathHandler.containsKey(route.selector::class)) { - true -> pathHandler[route.selector::class]!!.invoke(this, route, tail) - else -> error("No handler has been registered for ${route.selector}") - } - } - - override fun addCustomRouteHandler( - selector: KClass, - handler: IPathCalculator.(Route, String) -> String - ) { - pathHandler[selector] = handler - } -} diff --git a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/path/RouteHandlerMap.kt b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/path/RouteHandlerMap.kt deleted file mode 100644 index 16bce03f2..000000000 --- a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/path/RouteHandlerMap.kt +++ /dev/null @@ -1,7 +0,0 @@ -package io.bkbn.kompendium.path - -import io.ktor.routing.Route -import io.ktor.routing.RouteSelector -import kotlin.reflect.KClass - -typealias RouteHandlerMap = MutableMap, IPathCalculator.(Route, String) -> String> diff --git a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/routes/OpenApiRoute.kt b/kompendium-core/src/main/kotlin/io/bkbn/kompendium/routes/OpenApiRoute.kt deleted file mode 100644 index 298010c24..000000000 --- a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/routes/OpenApiRoute.kt +++ /dev/null @@ -1,31 +0,0 @@ -package io.bkbn.kompendium.routes - -import com.fasterxml.jackson.annotation.JsonInclude -import com.fasterxml.jackson.databind.ObjectMapper -import com.fasterxml.jackson.databind.SerializationFeature -import io.bkbn.kompendium.models.oas.OpenApiSpec -import io.ktor.application.call -import io.ktor.response.respondText -import io.ktor.routing.Routing -import io.ktor.routing.get -import io.ktor.routing.route - -/** - * Provides an out-of-the-box route to return the generated [OpenApiSpec] - * @param oas spec that is returned - * @param om provider for Jackson - */ -fun Routing.openApi( - oas: OpenApiSpec, - om: ObjectMapper = objectMapper -) { - route("/openapi.json") { - get { - call.respondText { om.writeValueAsString(oas) } - } - } -} - -private val objectMapper = ObjectMapper() - .setSerializationInclusion(JsonInclude.Include.NON_NULL) - .enable(SerializationFeature.INDENT_OUTPUT) diff --git a/kompendium-core/src/test/kotlin/io/bkbn/kompendium/KompendiumTest.kt b/kompendium-core/src/test/kotlin/io/bkbn/kompendium/KompendiumTest.kt deleted file mode 100644 index 03bc09d76..000000000 --- a/kompendium-core/src/test/kotlin/io/bkbn/kompendium/KompendiumTest.kt +++ /dev/null @@ -1,643 +0,0 @@ -package io.bkbn.kompendium - -import io.ktor.application.Application -import io.ktor.http.HttpMethod -import io.ktor.http.HttpStatusCode -import io.ktor.routing.routing -import io.ktor.server.testing.handleRequest -import io.ktor.server.testing.withTestApplication -import java.net.URI -import kotlin.test.AfterTest -import kotlin.test.Test -import kotlin.test.assertEquals -import io.bkbn.kompendium.models.oas.OpenApiSpecInfo -import io.bkbn.kompendium.models.oas.OpenApiSpecInfoContact -import io.bkbn.kompendium.models.oas.OpenApiSpecInfoLicense -import io.bkbn.kompendium.models.oas.OpenApiSpecServer -import io.bkbn.kompendium.routes.openApi -import io.bkbn.kompendium.routes.redoc -import io.bkbn.kompendium.util.TestHelpers.getFileSnapshot -import io.bkbn.kompendium.util.complexType -import io.bkbn.kompendium.util.jacksonConfigModule -import io.bkbn.kompendium.util.emptyGet -import io.bkbn.kompendium.util.genericPolymorphicResponse -import io.bkbn.kompendium.util.genericPolymorphicResponseMultipleImpls -import io.bkbn.kompendium.util.headerParameter -import io.bkbn.kompendium.util.kotlinxConfigModule -import io.bkbn.kompendium.util.nestedUnderRootModule -import io.bkbn.kompendium.util.nonRequiredParamsGet -import io.bkbn.kompendium.util.notarizedDeleteModule -import io.bkbn.kompendium.util.notarizedGetModule -import io.bkbn.kompendium.util.notarizedGetWithMultipleThrowables -import io.bkbn.kompendium.util.notarizedGetWithNotarizedException -import io.bkbn.kompendium.util.notarizedPostModule -import io.bkbn.kompendium.util.notarizedPutModule -import io.bkbn.kompendium.util.pathParsingTestModule -import io.bkbn.kompendium.util.polymorphicCollectionResponse -import io.bkbn.kompendium.util.polymorphicInterfaceResponse -import io.bkbn.kompendium.util.polymorphicMapResponse -import io.bkbn.kompendium.util.polymorphicResponse -import io.bkbn.kompendium.util.primitives -import io.bkbn.kompendium.util.returnsList -import io.bkbn.kompendium.util.rootModule -import io.bkbn.kompendium.util.simpleGenericResponse -import io.bkbn.kompendium.util.statusPageModule -import io.bkbn.kompendium.util.statusPageMultiExceptions -import io.bkbn.kompendium.util.trailingSlash -import io.bkbn.kompendium.util.undeclaredType -import io.bkbn.kompendium.util.withDefaultParameter -import io.bkbn.kompendium.util.withExamples -import io.bkbn.kompendium.util.withOperationId - -internal class KompendiumTest { - - @AfterTest - fun `reset kompendium`() { - Kompendium.resetSchema() - } - - @Test - fun `Kompendium can be instantiated with no details`() { - assertEquals(Kompendium.openApiSpec.openapi, "3.0.3", "Kompendium has a default spec version of 3.0.3") - } - - @Test - fun `Notarized Get records all expected information`() { - withTestApplication({ - kotlinxConfigModule() - docs() - notarizedGetModule() - }) { - // do - val json = handleRequest(HttpMethod.Get, "/openapi.json").response.content - - // expect - val expected = getFileSnapshot("notarized_get.json").trim() - assertEquals(expected, json, "The received json spec should match the expected content") - } - } - - @Test - fun `Notarized Get does not interrupt the pipeline`() { - withTestApplication({ - jacksonConfigModule() - docs() - notarizedGetModule() - }) { - // do - val json = handleRequest(HttpMethod.Get, "/test").response.content - - // expect - val expected = "hey dude ‼️ congratz on the get request" - assertEquals(expected, json, "The received json spec should match the expected content") - } - } - - @Test - fun `Notarized Post records all expected information`() { - withTestApplication({ - jacksonConfigModule() - docs() - notarizedPostModule() - }) { - // do - val json = handleRequest(HttpMethod.Get, "/openapi.json").response.content - - // expect - val expected = getFileSnapshot("notarized_post.json").trim() - assertEquals(expected, json, "The received json spec should match the expected content") - } - } - - @Test - fun `Notarized post does not interrupt the pipeline`() { - withTestApplication({ - kotlinxConfigModule() - docs() - notarizedPostModule() - }) { - // do - val json = handleRequest(HttpMethod.Post, "/test").response.content - - // expect - val expected = "hey dude ✌️ congratz on the post request" - assertEquals(expected, json, "The received json spec should match the expected content") - } - } - - @Test - fun `Notarized Put records all expected information`() { - withTestApplication({ - jacksonConfigModule() - docs() - notarizedPutModule() - }) { - // do - val json = handleRequest(HttpMethod.Get, "/openapi.json").response.content - - // expect - val expected = getFileSnapshot("notarized_put.json").trim() - assertEquals(expected, json, "The received json spec should match the expected content") - } - } - - @Test - fun `Notarized put does not interrupt the pipeline`() { - withTestApplication({ - jacksonConfigModule() - docs() - notarizedPutModule() - }) { - // do - val json = handleRequest(HttpMethod.Put, "/test").response.content - - // expect - val expected = "hey pal 🌝 whatcha doin' here?" - assertEquals(expected, json, "The received json spec should match the expected content") - } - } - - @Test - fun `Notarized delete records all expected information`() { - withTestApplication({ - jacksonConfigModule() - docs() - notarizedDeleteModule() - }) { - // do - val json = handleRequest(HttpMethod.Get, "/openapi.json").response.content - - // expect - val expected = getFileSnapshot("notarized_delete.json").trim() - assertEquals(expected, json, "The received json spec should match the expected content") - } - } - - @Test - fun `Notarized delete does not interrupt the pipeline`() { - withTestApplication({ - jacksonConfigModule() - docs() - notarizedDeleteModule() - }) { - // do - val status = handleRequest(HttpMethod.Delete, "/test").response.status() - - // expect - assertEquals(HttpStatusCode.NoContent, status, "No content status should be received") - } - } - - @Test - fun `Path parser stores the expected path`() { - withTestApplication({ - jacksonConfigModule() - docs() - pathParsingTestModule() - }) { - // do - val json = handleRequest(HttpMethod.Get, "/openapi.json").response.content - - // expect - val expected = getFileSnapshot("path_parser.json").trim() - assertEquals(expected, json, "The received json spec should match the expected content") - } - } - - @Test - fun `Can notarize the root route`() { - withTestApplication({ - jacksonConfigModule() - docs() - rootModule() - }) { - // do - val json = handleRequest(HttpMethod.Get, "/openapi.json").response.content - - // expect - val expected = getFileSnapshot("root_route.json").trim() - assertEquals(expected, json, "The received json spec should match the expected content") - } - } - - @Test - fun `Can call the root route`() { - withTestApplication({ - kotlinxConfigModule() - docs() - rootModule() - }) { - // do - val result = handleRequest(HttpMethod.Get, "/").response.content - - // expect - val expected = "☎️🏠🌲" - assertEquals(expected, result, "Should be the same") - } - } - - @Test - fun `Nested under root module does not append trailing slash`() { - withTestApplication({ - jacksonConfigModule() - docs() - nestedUnderRootModule() - }) { - // do - val json = handleRequest(HttpMethod.Get, "/openapi.json").response.content - - // expect - val expected = getFileSnapshot("nested_under_root.json").trim() - assertEquals(expected, json, "The received json spec should match the expected content") - } - } - - @Test - fun `Can notarize a trailing slash route`() { - withTestApplication({ - jacksonConfigModule() - docs() - trailingSlash() - }) { - // do - val json = handleRequest(HttpMethod.Get, "/openapi.json").response.content - - // expect - val expected = getFileSnapshot("trailing_slash.json").trim() - assertEquals(expected, json, "The received json spec should match the expected content") - } - } - - @Test - fun `Can call a trailing slash route`() { - withTestApplication({ - jacksonConfigModule() - docs() - trailingSlash() - }) { - // do - val result = handleRequest(HttpMethod.Get, "/test/").response.content - - // expect - val expected = "🙀👾" - assertEquals(expected, result, "Should be the same") - } - } - - @Test - fun `Can notarize a complex type`() { - withTestApplication({ - jacksonConfigModule() - docs() - complexType() - }) { - // do - val json = handleRequest(HttpMethod.Get, "/openapi.json").response.content - - // expect - val expected = getFileSnapshot("complex_type.json").trim() - assertEquals(expected, json, "The received json spec should match the expected content") - } - } - - @Test - fun `Can notarize primitives`() { - withTestApplication({ - jacksonConfigModule() - docs() - primitives() - }) { - // do - val json = handleRequest(HttpMethod.Get, "/openapi.json").response.content - - // expect - val expected = getFileSnapshot("notarized_primitives.json").trim() - assertEquals(expected, json, "The received json spec should match the expected content") - } - } - - @Test - fun `Can notarize a top level list response`() { - withTestApplication({ - jacksonConfigModule() - docs() - returnsList() - }) { - // do - val json = handleRequest(HttpMethod.Get, "/openapi.json").response.content - - // expect - val expected = getFileSnapshot("response_list.json").trim() - assertEquals(expected, json, "The received json spec should match the expected content") - } - } - - @Test - fun `Can notarize route with no request params and no response body`() { - withTestApplication({ - kotlinxConfigModule() - docs() - emptyGet() - }) { - // do - val json = handleRequest(HttpMethod.Get, "/openapi.json").response.content - - // expect - val expected = getFileSnapshot("no_request_params_and_no_response_body.json").trim() - assertEquals(expected, json, "The received json spec should match the expected content") - } - } - - @Test - fun `Can notarize route with non-required params`() { - withTestApplication({ - jacksonConfigModule() - docs() - nonRequiredParamsGet() - }) { - // do - val json = handleRequest(HttpMethod.Get, "/openapi.json").response.content - - // expect - val expected = getFileSnapshot("non_required_params.json").trim() - assertEquals(expected, json, "The received json spec should match the expected content") - } - } - - @Test - fun `Can add operationId`() { - withTestApplication({ - jacksonConfigModule() - docs() - withOperationId() - }) { - // do - val json = handleRequest(HttpMethod.Get, "/openapi.json").response.content - - // expect - val expected = getFileSnapshot("notarized_get_with_operation_id.json").trim() - assertEquals(expected, json, "The received json spec should match the expected content") - } - } - - @Test - fun `Generates the expected redoc`() { - withTestApplication({ - jacksonConfigModule() - docs() - returnsList() - }) { - // do - val html = handleRequest(HttpMethod.Get, "/docs").response.content - - // expected - val expected = getFileSnapshot("redoc.html") - assertEquals(expected, html) - } - } - - @Test - fun `Generates additional responses when passed a throwable`() { - withTestApplication({ - statusPageModule() - jacksonConfigModule() - docs() - notarizedGetWithNotarizedException() - }) { - // do - val json = handleRequest(HttpMethod.Get, "/openapi.json").response.content - - // expect - val expected = getFileSnapshot("notarized_get_with_exception_response.json").trim() - assertEquals(expected, json, "The received json spec should match the expected content") - } - } - - @Test - fun `Generates additional responses when passed multiple throwables`() { - withTestApplication({ - statusPageMultiExceptions() - jacksonConfigModule() - docs() - notarizedGetWithMultipleThrowables() - }) { - // do - val json = handleRequest(HttpMethod.Get, "/openapi.json").response.content - - // expect - val expected = getFileSnapshot("notarized_get_with_multiple_exception_responses.json").trim() - assertEquals(expected, json, "The received json spec should match the expected content") - } - } - - @Test - fun `Can generate example response and request bodies`() { - withTestApplication({ - kotlinxConfigModule() - docs() - withExamples() - }) { - // do - val json = handleRequest(HttpMethod.Get, "/openapi.json").response.content - - // expect - val expected = getFileSnapshot("example_req_and_resp.json").trim() - assertEquals(expected, json, "The received json spec should match the expected content") - } - } - - @Test - fun `Can generate a default parameter value`() { - withTestApplication({ - jacksonConfigModule() - docs() - withDefaultParameter() - }) { - // do - val json = handleRequest(HttpMethod.Get, "/openapi.json").response.content - - // expect - val expected = getFileSnapshot("query_with_default_parameter.json").trim() - assertEquals(expected, json, "The received json spec should match the expected content") - } - } - - @Test - fun `Can generate a polymorphic response type`() { - withTestApplication({ - jacksonConfigModule() - docs() - polymorphicResponse() - }) { - // do - val json = handleRequest(HttpMethod.Get, "/openapi.json").response.content - - // expect - val expected = getFileSnapshot("polymorphic_response.json").trim() - assertEquals(expected, json, "The received json spec should match the expected content") - } - } - - @Test - fun `Can generate a collection with polymorphic response type`() { - withTestApplication({ - jacksonConfigModule() - docs() - polymorphicCollectionResponse() - }) { - // do - val json = handleRequest(HttpMethod.Get, "/openapi.json").response.content - - // expect - val expected = getFileSnapshot("polymorphic_list_response.json").trim() - assertEquals(expected, json, "The received json spec should match the expected content") - } - } - - @Test - fun `Can generate a map with a polymorphic response type`() { - withTestApplication({ - jacksonConfigModule() - docs() - polymorphicMapResponse() - }) { - // do - val json = handleRequest(HttpMethod.Get, "/openapi.json").response.content - - // expect - val expected = getFileSnapshot("polymorphic_map_response.json").trim() - assertEquals(expected, json, "The received json spec should match the expected content") - } - } - - @Test - fun `Can generate a polymorphic response from a sealed interface`() { - withTestApplication({ - jacksonConfigModule() - docs() - polymorphicInterfaceResponse() - }) { - // do - val json = handleRequest(HttpMethod.Get, "/openapi.json").response.content - - // expect - val expected = getFileSnapshot("sealed_interface_response.json").trim() - assertEquals(expected, json, "The received json spec should match the expected content") - } - } - - @Test - fun `Can generate a response type with a generic type`() { - withTestApplication({ - jacksonConfigModule() - docs() - simpleGenericResponse() - }) { - // do - val json = handleRequest(HttpMethod.Get, "/openapi.json").response.content - - // expect - val expected = getFileSnapshot("generic_response.json").trim() - assertEquals(expected, json, "The received json spec should match the expected content") - } - } - - @Test - fun `Can generate a polymorphic response type with generics`() { - withTestApplication({ - jacksonConfigModule() - docs() - genericPolymorphicResponse() - }) { - // do - val json = handleRequest(HttpMethod.Get, "/openapi.json").response.content - - // expect - val expected = getFileSnapshot("polymorphic_response_with_generics.json").trim() - assertEquals(expected, json, "The received json spec should match the expected content") - } - } - - @Test - fun `Absolute Psycho Inheritance Test`() { - withTestApplication({ - kotlinxConfigModule() - docs() - genericPolymorphicResponseMultipleImpls() - }) { - // do - val json = handleRequest(HttpMethod.Get, "/openapi.json").response.content - - // expect - val expected = getFileSnapshot("crazy_polymorphic_example.json").trim() - assertEquals(expected, json, "The received json spec should match the expected content") - } - } - - @Test - fun `Can add an undeclared field`() { - withTestApplication({ - kotlinxConfigModule() - docs() - undeclaredType() - }) { - // do - val json = handleRequest(HttpMethod.Get, "/openapi.json").response.content - - // expect - val expected = getFileSnapshot("undeclared_field.json").trim() - assertEquals(expected, json, "The received json spec should match the expected content") - } - } - - @Test - fun `Can add a custom header parameter with a name override`() { - withTestApplication({ - jacksonConfigModule() - docs() - headerParameter() - }) { - // do - val json = handleRequest(HttpMethod.Get, "/openapi.json").response.content - - // expect - val expected = getFileSnapshot("override_parameter_name.json").trim() - assertEquals(expected, json, "The received json spec should match the expected content") - } - } - - private val oas = Kompendium.openApiSpec.copy( - info = OpenApiSpecInfo( - title = "Test API", - version = "1.33.7", - description = "An amazing, fully-ish 😉 generated API spec", - termsOfService = URI("https://example.com"), - contact = OpenApiSpecInfoContact( - name = "Homer Simpson", - email = "chunkylover53@aol.com", - url = URI("https://gph.is/1NPUDiM") - ), - license = OpenApiSpecInfoLicense( - name = "MIT", - url = URI("https://github.com/bkbnio/kompendium/blob/main/LICENSE") - ) - ), - servers = mutableListOf( - OpenApiSpecServer( - url = URI("https://myawesomeapi.com"), - description = "Production instance of my API" - ), - OpenApiSpecServer( - url = URI("https://staging.myawesomeapi.com"), - description = "Where the fun stuff happens" - ) - ) - ) - - private fun Application.docs() { - routing { - openApi(oas) - redoc(oas) - } - } -} diff --git a/kompendium-core/src/test/kotlin/io/bkbn/kompendium/KontentTest.kt b/kompendium-core/src/test/kotlin/io/bkbn/kompendium/KontentTest.kt deleted file mode 100644 index 13da2c6f2..000000000 --- a/kompendium-core/src/test/kotlin/io/bkbn/kompendium/KontentTest.kt +++ /dev/null @@ -1,204 +0,0 @@ -package io.bkbn.kompendium - -import java.util.UUID -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFailsWith -import kotlin.test.assertFalse -import kotlin.test.assertNotNull -import kotlin.test.assertTrue -import io.bkbn.kompendium.Kontent.generateKontent -import io.bkbn.kompendium.Kontent.generateParameterKontent -import io.bkbn.kompendium.models.oas.DictionarySchema -import io.bkbn.kompendium.models.oas.FormatSchema -import io.bkbn.kompendium.models.oas.ObjectSchema -import io.bkbn.kompendium.models.oas.ReferencedSchema -import io.bkbn.kompendium.util.* - -@ExperimentalStdlibApi -internal class KontentTest { - - @Test - fun `Unit returns empty map on generate`() { - // do - val result = generateKontent() - - // expect - assertTrue { result.isEmpty() } - } - - @Test - fun `Primitive types return a single map result`() { - // do - val result = generateKontent() - - // expect - assertEquals(1, result.count(), "Should have a single result") - assertEquals(FormatSchema("int64", "integer"), result["Long"]) - } - - @Test - fun `Object with BigDecimal and BigInteger types`() { - // do - val result = generateKontent() - - // expect - assertEquals(3, result.count()) - assertTrue { result.containsKey(TestBigNumberModel::class.simpleName) } - assertEquals(FormatSchema("double", "number"), result["BigDecimal"]) - assertEquals(FormatSchema("int64", "integer"), result["BigInteger"]) - } - - @Test - fun `Object with ByteArray type`() { - // do - val result = generateKontent() - - // expect - assertEquals(2, result.count()) - assertTrue { result.containsKey(TestByteArrayModel::class.simpleName) } - assertEquals(FormatSchema("byte", "string"), result["ByteArray"]) - } - - @Test - fun `Objects reference their base types in the cache`() { - // do - val result = generateKontent() - - // expect - assertNotNull(result) - assertEquals(3, result.count()) - assertTrue { result.containsKey(TestSimpleModel::class.simpleName) } - } - - @Test - fun `generation works for nested object types`() { - // do - val result = generateKontent() - - // expect - assertNotNull(result) - assertEquals(4, result.count()) - assertTrue { result.containsKey(TestNestedModel::class.simpleName) } - assertTrue { result.containsKey(TestSimpleModel::class.simpleName) } - } - - @Test - fun `generation does not repeat for cached items`() { - // when - val clazz = TestNestedModel::class - val initialCache = generateKontent() - - // do - val result = generateKontent(initialCache) - - // expect TODO Spy to check invocation count? - assertNotNull(result) - assertEquals(4, result.count()) - assertTrue { result.containsKey(clazz.simpleName) } - assertTrue { result.containsKey(TestSimpleModel::class.simpleName) } - } - - @Test - fun `generation allows for enum fields`() { - // do - val result = generateKontent() - - // expect - assertNotNull(result) - assertEquals(3, result.count()) - assertTrue { result.containsKey(TestSimpleWithEnums::class.simpleName) } - } - - @Test - fun `generation allows for map fields`() { - // do - val result = generateKontent() - - // expect - assertNotNull(result) - assertEquals(5, result.count()) - assertTrue { result.containsKey("Map-String-TestSimpleModel") } - assertTrue { result.containsKey(TestSimpleWithMap::class.simpleName) } - - val os = result[TestSimpleWithMap::class.simpleName] as ObjectSchema - val expectedRef = ReferencedSchema("#/components/schemas/Map-String-TestSimpleModel") - assertEquals(expectedRef, os.properties["b"]) - } - - @Test - fun `map fields that are not string result in error`() { - // expect - assertFailsWith { generateKontent() } - } - - @Test - fun `generation allows for collection fields`() { - // do - val result = generateKontent() - - // expect - assertNotNull(result) - assertEquals(6, result.count()) - assertTrue { result.containsKey("List-TestSimpleModel") } - assertTrue { result.containsKey(TestSimpleWithList::class.simpleName) } - } - - @Test - fun `Can parse enum list as a field`() { - // do - val result = generateKontent() - - // expect - assertNotNull(result) - } - - @Test - fun `UUID schema support`() { - // do - val result = generateKontent() - - // expect - assertNotNull(result) - assertEquals(2, result.count()) - assertTrue { result.containsKey(UUID::class.simpleName) } - assertTrue { result.containsKey(TestWithUUID::class.simpleName) } - val expectedSchema = result[UUID::class.simpleName] as FormatSchema - assertEquals(FormatSchema("uuid", "string"), expectedSchema) - } - - @Test - fun `Generate top level list response`() { - // do - val result = generateKontent>() - - // expect - assertNotNull(result) - } - - @Test - fun `Can handle a complex type`() { - // do - val result = generateKontent() - - // expect - assertNotNull(result) - assertEquals(7, result.count()) - assertTrue { result.containsKey("Map-String-CrazyItem") } - val ds = result["Map-String-CrazyItem"] as DictionarySchema - val rs = ds.additionalProperties as ReferencedSchema - assertEquals(ReferencedSchema("#/components/schemas/CrazyItem"), rs) - } - - @Test - fun `Parameter kontent filters out top level declaration`() { - // do - val result = generateParameterKontent() - - // expect - assertNotNull(result) - assertEquals(2, result.count()) - assertFalse { result.containsKey(TestSimpleModel::class.simpleName) } - } - -} diff --git a/kompendium-core/src/test/kotlin/io/bkbn/kompendium/core/KompendiumTest.kt b/kompendium-core/src/test/kotlin/io/bkbn/kompendium/core/KompendiumTest.kt new file mode 100644 index 000000000..e4475368d --- /dev/null +++ b/kompendium-core/src/test/kotlin/io/bkbn/kompendium/core/KompendiumTest.kt @@ -0,0 +1,276 @@ +package io.bkbn.kompendium.core + +import io.bkbn.kompendium.core.fixtures.TestHelpers.apiFunctionalityTest +import io.bkbn.kompendium.core.fixtures.TestHelpers.getFileSnapshot +import io.bkbn.kompendium.core.fixtures.TestHelpers.openApiTest +import io.bkbn.kompendium.core.util.complexType +import io.bkbn.kompendium.core.util.constrainedDoubleInfo +import io.bkbn.kompendium.core.util.constrainedIntInfo +import io.bkbn.kompendium.core.util.defaultField +import io.bkbn.kompendium.core.util.defaultParameter +import io.bkbn.kompendium.core.util.exclusiveMinMax +import io.bkbn.kompendium.core.util.formattedParam +import io.bkbn.kompendium.core.util.freeFormObject +import io.bkbn.kompendium.core.util.genericPolymorphicResponse +import io.bkbn.kompendium.core.util.genericPolymorphicResponseMultipleImpls +import io.bkbn.kompendium.core.util.headerParameter +import io.bkbn.kompendium.core.util.minMaxArray +import io.bkbn.kompendium.core.util.minMaxFreeForm +import io.bkbn.kompendium.core.util.minMaxString +import io.bkbn.kompendium.core.util.multipleOfDouble +import io.bkbn.kompendium.core.util.multipleOfInt +import io.bkbn.kompendium.core.util.nestedUnderRootModule +import io.bkbn.kompendium.core.util.nonRequiredParamsGet +import io.bkbn.kompendium.core.util.notarizedDeleteModule +import io.bkbn.kompendium.core.util.notarizedGetModule +import io.bkbn.kompendium.core.util.notarizedGetWithGenericErrorResponse +import io.bkbn.kompendium.core.util.notarizedGetWithMultipleThrowables +import io.bkbn.kompendium.core.util.notarizedGetWithNotarizedException +import io.bkbn.kompendium.core.util.notarizedGetWithPolymorphicErrorResponse +import io.bkbn.kompendium.core.util.notarizedPostModule +import io.bkbn.kompendium.core.util.notarizedPutModule +import io.bkbn.kompendium.core.util.nullableField +import io.bkbn.kompendium.core.util.overrideFieldInfo +import io.bkbn.kompendium.core.util.pathParsingTestModule +import io.bkbn.kompendium.core.util.polymorphicCollectionResponse +import io.bkbn.kompendium.core.util.polymorphicInterfaceResponse +import io.bkbn.kompendium.core.util.polymorphicMapResponse +import io.bkbn.kompendium.core.util.polymorphicResponse +import io.bkbn.kompendium.core.util.primitives +import io.bkbn.kompendium.core.util.regexString +import io.bkbn.kompendium.core.util.requiredParameter +import io.bkbn.kompendium.core.util.returnsList +import io.bkbn.kompendium.core.util.rootModule +import io.bkbn.kompendium.core.util.simpleGenericResponse +import io.bkbn.kompendium.core.util.trailingSlash +import io.bkbn.kompendium.core.util.undeclaredType +import io.bkbn.kompendium.core.util.uniqueArray +import io.bkbn.kompendium.core.util.withDefaultParameter +import io.bkbn.kompendium.core.util.withExamples +import io.bkbn.kompendium.core.util.withOperationId +import io.kotest.core.spec.style.DescribeSpec +import io.ktor.http.HttpMethod +import io.ktor.http.HttpStatusCode + +class KompendiumTest : DescribeSpec({ + describe("Notarized Open API Metadata Tests") { + it("Can notarize a get request") { + // act + openApiTest("notarized_get.json") { notarizedGetModule() } + } + it("Can notarize a post request") { + // act + openApiTest("notarized_post.json") { notarizedPostModule() } + } + it("Can notarize a put request") { + // act + openApiTest("notarized_put.json") { notarizedPutModule() } + } + it("Can notarize a delete request") { + // act + openApiTest("notarized_delete.json") { notarizedDeleteModule() } + } + it("Can notarize a complex type") { + // act + openApiTest("complex_type.json") { complexType() } + } + it("Can notarize primitives") { + // act + openApiTest("notarized_primitives.json") { primitives() } + } + it("Can notarize a top level list response") { + // act + openApiTest("response_list.json") { returnsList() } + } + it("Can notarize a route with non-required params") { + // act + openApiTest("non_required_params.json") { nonRequiredParamsGet() } + } + } + describe("Notarized Ktor Functionality Tests") { + it("Can notarized a get request and return the expected result") { + // act + apiFunctionalityTest("hey dude ‼️ congratz on the get request") { notarizedGetModule() } + } + it("Can notarize a post request and return the expected result") { + // act + apiFunctionalityTest( + "hey dude ✌️ congratz on the post request", + httpMethod = HttpMethod.Post + ) { notarizedPostModule() } + } + it("Can notarize a put request and return the expected result") { + // act + apiFunctionalityTest("hey pal 🌝 whatcha doin' here?", httpMethod = HttpMethod.Put) { notarizedPutModule() } + } + it("Can notarize a delete request and return the expected result") { + // act + apiFunctionalityTest( + null, + httpMethod = HttpMethod.Delete, + expectedStatusCode = HttpStatusCode.NoContent + ) { notarizedDeleteModule() } + } + it("Can notarize the root route and return the expected result") { + // act + apiFunctionalityTest("☎️🏠🌲", "/") { rootModule() } + } + it("Can notarize a trailing slash route and return the expected result") { + // act + apiFunctionalityTest("🙀👾", "/test/") { trailingSlash() } + } + } + describe("Route Parsing") { + it("Can parse a simple path and store it under the expected route") { + // act + openApiTest("path_parser.json") { pathParsingTestModule() } + } + it("Can notarize the root route") { + // act + openApiTest("root_route.json") { rootModule() } + } + it("Can notarize a route under the root module without appending trailing slash") { + // act + openApiTest("nested_under_root.json") { nestedUnderRootModule() } + } + it("Can notarize a route with a trailing slash") { + // act + openApiTest("trailing_slash.json") { trailingSlash() } + } + } + describe("Exceptions") { + it("Can add an exception status code to a response") { + // act + openApiTest("notarized_get_with_exception_response.json") { notarizedGetWithNotarizedException() } + } + it("Can support multiple response codes") { + // act + openApiTest("notarized_get_with_multiple_exception_responses.json") { notarizedGetWithMultipleThrowables() } + } + it("Can add a polymorphic exception response") { + // act + openApiTest("polymorphic_error_status_codes.json") { notarizedGetWithPolymorphicErrorResponse() } + } + it("Can add a generic exception response") { + // act + openApiTest("generic_exception.json") { notarizedGetWithGenericErrorResponse() } + } + } + describe("Examples") { + it("Can generate example response and request bodies") { + // act + openApiTest("example_req_and_resp.json") { withExamples() } + } + } + describe("Defaults") { + it("Can generate a default parameter values") { + // act + openApiTest("query_with_default_parameter.json") { withDefaultParameter() } + } + } + describe("Required Fields") { + it("Marks a parameter required if there is no default and it is not marked nullable") { + openApiTest("required_param.json") { requiredParameter() } + } + it("Does not mark a parameter as required if a default value is provided") { + openApiTest("default_param.json") { defaultParameter() } + } + it("Does not mark a field as required if a default value is provided") { + openApiTest("default_field.json") { defaultField() } + } + it("Marks a field as nullable when expected") { + openApiTest("nullable_field.json") { nullableField() } + } + } + describe("Polymorphism and Generics") { + it("can generate a polymorphic response type") { + // act + openApiTest("polymorphic_response.json") { polymorphicResponse() } + } + it("Can generate a collection with polymorphic response type") { + // act + openApiTest("polymorphic_list_response.json") { polymorphicCollectionResponse() } + } + it("Can generate a map with a polymorphic response type") { + // act + openApiTest("polymorphic_map_response.json") { polymorphicMapResponse() } + } + it("Can generate a polymorphic response from a sealed interface") { + // act + openApiTest("sealed_interface_response.json") { polymorphicInterfaceResponse() } + } + it("Can generate a response type with a generic type") { + // act + openApiTest("generic_response.json") { simpleGenericResponse() } + } + it("Can generate a polymorphic response type with generics") { + // act + openApiTest("polymorphic_response_with_generics.json") { genericPolymorphicResponse() } + } + it("Can handle an absolutely psycho inheritance test") { + // act + openApiTest("crazy_polymorphic_example.json") { genericPolymorphicResponseMultipleImpls() } + } + } + describe("Miscellaneous") { + it("Can generate the necessary ReDoc home page") { + // act + apiFunctionalityTest(getFileSnapshot("redoc.html"), "/docs") { returnsList() } + } + it("Can add an operation id to a notarized route") { + // act + openApiTest("notarized_get_with_operation_id.json") { withOperationId() } + } + it("Can add an undeclared field") { + // act + openApiTest("undeclared_field.json") { undeclaredType() } + } + it("Can add a custom header parameter with a name override") { + // act + openApiTest("override_parameter_name.json") { headerParameter() } + } + it("Can override field values via annotation") { + openApiTest("field_override.json") { overrideFieldInfo() } + } + } + describe("Constraints") { + it("Can set a minimum and maximum integer value") { + openApiTest("min_max_int_field.json") { constrainedIntInfo() } + } + it("Can set a minimum and maximum double value") { + openApiTest("min_max_double_field.json") { constrainedDoubleInfo() } + } + it("Can set an exclusive min and exclusive max integer value") { + openApiTest("exclusive_min_max.json") { exclusiveMinMax() } + } + it("Can add a custom format to a string field") { + openApiTest("formatted_param_type.json") { formattedParam() } + } + it("Can set a minimum and maximum length on a string field") { + openApiTest("min_max_string.json") { minMaxString() } + } + it("Can set a custom regex pattern on a string field") { + openApiTest("regex_string.json") { regexString() } + } + it("Can set a minimum and maximum item count on an array field") { + openApiTest("min_max_array.json") { minMaxArray() } + } + it("Can set a unique items constraint on an array field") { + openApiTest("unique_array.json") { uniqueArray() } + } + it("Can set a multiple-of constraint on an int field") { + openApiTest("multiple_of_int.json") { multipleOfInt() } + } + it("Can set a multiple of constraint on an double field") { + openApiTest("multiple_of_double.json") { multipleOfDouble() } + } + it("Can set a minimum and maximum number of properties on a free-form type") { + openApiTest("min_max_free_form.json") { minMaxFreeForm() } + } + } + describe("Free Form") { + it("Can create a free-form field") { + openApiTest("free_form_object.json") { freeFormObject() } + } + } +}) diff --git a/kompendium-core/src/test/kotlin/io/bkbn/kompendium/core/KontentTest.kt b/kompendium-core/src/test/kotlin/io/bkbn/kompendium/core/KontentTest.kt new file mode 100644 index 000000000..c2ccf22b9 --- /dev/null +++ b/kompendium-core/src/test/kotlin/io/bkbn/kompendium/core/KontentTest.kt @@ -0,0 +1,173 @@ +package io.bkbn.kompendium.core + +import io.bkbn.kompendium.core.Kontent.generateKontent +import io.bkbn.kompendium.core.fixtures.ComplexRequest +import io.bkbn.kompendium.core.fixtures.TestBigNumberModel +import io.bkbn.kompendium.core.fixtures.TestByteArrayModel +import io.bkbn.kompendium.core.fixtures.TestInvalidMap +import io.bkbn.kompendium.core.fixtures.TestNestedModel +import io.bkbn.kompendium.core.fixtures.TestSimpleModel +import io.bkbn.kompendium.core.fixtures.TestSimpleWithEnumList +import io.bkbn.kompendium.core.fixtures.TestSimpleWithEnums +import io.bkbn.kompendium.core.fixtures.TestSimpleWithList +import io.bkbn.kompendium.core.fixtures.TestSimpleWithMap +import io.bkbn.kompendium.core.fixtures.TestWithUUID +import io.bkbn.kompendium.oas.schema.DictionarySchema +import io.bkbn.kompendium.oas.schema.FormattedSchema +import io.bkbn.kompendium.oas.schema.ObjectSchema +import io.kotest.assertions.throwables.shouldThrow +import io.kotest.core.spec.style.DescribeSpec +import io.kotest.matchers.maps.beEmpty +import io.kotest.matchers.maps.shouldContainKey +import io.kotest.matchers.maps.shouldHaveKey +import io.kotest.matchers.maps.shouldHaveSize +import io.kotest.matchers.maps.shouldNotHaveKey +import io.kotest.matchers.should +import io.kotest.matchers.shouldBe +import io.kotest.matchers.shouldNotBe +import java.util.UUID + +class KontentTest : DescribeSpec({ + describe("Kontent analysis") { + it("Can return an empty map when passed Unit") { + // act + val result = generateKontent() + + // assert + result should beEmpty() + } + it("Can return a single map result when analyzing a primitive") { + // act + val result = generateKontent() + + // assert + result shouldHaveSize 1 + result["Long"] shouldBe FormattedSchema("int64", "integer") + } + it("Can handle BigDecimal and BigInteger Types") { + // act + val result = generateKontent() + + // assert + result shouldHaveSize 3 + result shouldContainKey TestBigNumberModel::class.simpleName!! + result["BigDecimal"] shouldBe FormattedSchema("double", "number") + result["BigInteger"] shouldBe FormattedSchema("int64", "integer") + } + it("Can handle ByteArray type") { + // act + val result = generateKontent() + + // assert + result shouldHaveSize 2 + result shouldContainKey TestByteArrayModel::class.simpleName!! + result["ByteArray"] shouldBe FormattedSchema("byte", "string") + } + it("Allows objects to reference their base type in the cache") { + // act + val result = generateKontent() + + // assert + result shouldNotBe null + result shouldHaveSize 3 + result shouldContainKey TestSimpleModel::class.simpleName!! + } + it("Can generate cache for nested object types") { + // act + val result = generateKontent() + + // assert + result shouldNotBe null + result shouldHaveSize 4 + result shouldContainKey TestNestedModel::class.simpleName!! + result shouldContainKey TestSimpleModel::class.simpleName!! + } + it("Does not repeat generation for cached items") { + // arrange + val clazz = TestNestedModel::class + val initialCache = generateKontent() + + // act + val result = generateKontent(initialCache) + + // assert TODO Spy to check invocation count? + result shouldNotBe null + result shouldHaveSize 4 + result shouldContainKey clazz.simpleName!! + result shouldContainKey TestSimpleModel::class.simpleName!! + } + it("allows for generation of enum types") { + // act + val result = generateKontent() + + // assert + result shouldNotBe null + result shouldHaveSize 3 + result shouldContainKey TestSimpleWithEnums::class.simpleName!! + } + it("Allows for generation of map fields") { + // act + val result = generateKontent() + + // assert + result shouldNotBe null + result shouldHaveSize 5 + result shouldContainKey "Map-String-TestSimpleModel" + result shouldContainKey TestSimpleWithMap::class.simpleName!! + result[TestSimpleWithMap::class.simpleName] as ObjectSchema shouldNotBe null // TODO Improve + } + it("Throws an error if a map is of an invalid type") { + // assert + shouldThrow { generateKontent() } + } + it("Can generate for collection fields") { + // act + val result = generateKontent() + + // assert + result shouldNotBe null + result shouldHaveSize 6 + result shouldContainKey "List-TestSimpleModel" + result shouldContainKey TestSimpleWithList::class.simpleName!! + } + it("Can parse an enum list as a field") { + // act + val result = generateKontent() + + // assert + result shouldNotBe null + result shouldHaveSize 4 + result shouldHaveKey "List-SimpleEnum" + } + it("Can support UUIDs") { + // act + val result = generateKontent() + + // assert + result shouldNotBe null + result shouldHaveSize 2 + result shouldContainKey UUID::class.simpleName!! + result shouldContainKey TestWithUUID::class.simpleName!! + result[UUID::class.simpleName] as FormattedSchema shouldBe FormattedSchema("uuid", "string") + } + it("Can generate a top level list response") { + // act + val result = generateKontent>() + + // assert + result shouldNotBe null + result shouldHaveSize 4 + result shouldContainKey "List-TestSimpleModel" + } + it("Can handle a complex type") { + // act + val result = generateKontent() + + // assert + result shouldNotBe null + result shouldHaveSize 7 + result shouldContainKey "Map-String-CrazyItem" + result["Map-String-CrazyItem"] as DictionarySchema shouldNotBe null + } + } +}) diff --git a/kompendium-core/src/test/kotlin/io/bkbn/kompendium/util/TestModules.kt b/kompendium-core/src/test/kotlin/io/bkbn/kompendium/core/util/TestModules.kt similarity index 53% rename from kompendium-core/src/test/kotlin/io/bkbn/kompendium/util/TestModules.kt rename to kompendium-core/src/test/kotlin/io/bkbn/kompendium/core/util/TestModules.kt index 913eaefc7..67c89d3e5 100644 --- a/kompendium-core/src/test/kotlin/io/bkbn/kompendium/util/TestModules.kt +++ b/kompendium-core/src/test/kotlin/io/bkbn/kompendium/core/util/TestModules.kt @@ -1,73 +1,39 @@ -package io.bkbn.kompendium.util +package io.bkbn.kompendium.core.util -import com.fasterxml.jackson.annotation.JsonInclude -import com.fasterxml.jackson.databind.SerializationFeature -import io.bkbn.kompendium.Notarized.notarizedDelete -import io.bkbn.kompendium.Notarized.notarizedException -import io.bkbn.kompendium.Notarized.notarizedGet -import io.bkbn.kompendium.Notarized.notarizedPost -import io.bkbn.kompendium.Notarized.notarizedPut -import io.bkbn.kompendium.models.meta.MethodInfo -import io.bkbn.kompendium.models.meta.RequestInfo -import io.bkbn.kompendium.models.meta.ResponseInfo +import io.bkbn.kompendium.core.Notarized.notarizedDelete +import io.bkbn.kompendium.core.Notarized.notarizedGet +import io.bkbn.kompendium.core.Notarized.notarizedPost +import io.bkbn.kompendium.core.Notarized.notarizedPut +import io.bkbn.kompendium.core.fixtures.Bibbity +import io.bkbn.kompendium.core.fixtures.ComplexGibbit +import io.bkbn.kompendium.core.fixtures.DefaultParameter +import io.bkbn.kompendium.core.fixtures.Gibbity +import io.bkbn.kompendium.core.fixtures.Mysterious +import io.bkbn.kompendium.core.fixtures.SimpleGibbit +import io.bkbn.kompendium.core.fixtures.TestFieldOverride +import io.bkbn.kompendium.core.fixtures.TestHelpers.DEFAULT_TEST_ENDPOINT +import io.bkbn.kompendium.core.fixtures.TestNested +import io.bkbn.kompendium.core.fixtures.TestRequest +import io.bkbn.kompendium.core.fixtures.TestResponse +import io.bkbn.kompendium.core.fixtures.TestResponseInfo +import io.bkbn.kompendium.core.fixtures.TestResponseInfo.defaultField +import io.bkbn.kompendium.core.fixtures.TestResponseInfo.defaultParam +import io.bkbn.kompendium.core.fixtures.TestResponseInfo.formattedParam +import io.bkbn.kompendium.core.fixtures.TestResponseInfo.minMaxString +import io.bkbn.kompendium.core.fixtures.TestResponseInfo.nullableField +import io.bkbn.kompendium.core.fixtures.TestResponseInfo.regexString +import io.bkbn.kompendium.core.fixtures.TestResponseInfo.requiredParam +import io.bkbn.kompendium.core.metadata.RequestInfo +import io.bkbn.kompendium.core.metadata.ResponseInfo +import io.bkbn.kompendium.core.metadata.method.GetInfo +import io.bkbn.kompendium.core.metadata.method.PostInfo import io.ktor.application.Application import io.ktor.application.call -import io.ktor.application.install -import io.ktor.features.ContentNegotiation -import io.ktor.features.StatusPages import io.ktor.http.HttpStatusCode -import io.ktor.jackson.jackson import io.ktor.response.respond import io.ktor.response.respondText import io.ktor.routing.route import io.ktor.routing.routing -import io.ktor.serialization.json - -fun Application.jacksonConfigModule() { - install(ContentNegotiation) { - jackson { - enable(SerializationFeature.INDENT_OUTPUT) - setSerializationInclusion(JsonInclude.Include.NON_NULL) - } - } -} - -fun Application.kotlinxConfigModule() { - install(ContentNegotiation) { - json() - } -} - -fun Application.statusPageModule() { - install(StatusPages) { - notarizedException( - info = ResponseInfo( - HttpStatusCode.BadRequest, - "Bad Things Happened" - ) - ) { - call.respond(HttpStatusCode.BadRequest, ExceptionResponse("Why you do dis?")) - } - } -} - -fun Application.statusPageMultiExceptions() { - install(StatusPages) { - notarizedException( - info = ResponseInfo(HttpStatusCode.Forbidden, "New API who dis?") - ) { - call.respond(HttpStatusCode.Forbidden) - } - notarizedException( - info = ResponseInfo( - HttpStatusCode.BadRequest, - "Bad Things Happened" - ) - ) { - call.respond(HttpStatusCode.BadRequest, ExceptionResponse("Why you do dis?")) - } - } -} fun Application.notarizedGetWithNotarizedException() { routing { @@ -89,6 +55,26 @@ fun Application.notarizedGetWithMultipleThrowables() { } } +fun Application.notarizedGetWithPolymorphicErrorResponse() { + routing { + route(DEFAULT_TEST_ENDPOINT) { + notarizedGet(TestResponseInfo.testGetWithPolymorphicException) { + error("something terrible has happened!") + } + } + } +} + +fun Application.notarizedGetWithGenericErrorResponse() { + routing { + route(DEFAULT_TEST_ENDPOINT) { + notarizedGet(TestResponseInfo.testGetWithGenericException) { + error("something terrible has happened!") + } + } + } +} + fun Application.notarizedGetModule() { routing { route("/test") { @@ -213,21 +199,11 @@ fun Application.primitives() { } } -fun Application.emptyGet() { - routing { - route("/test/empty") { - notarizedGet(TestResponseInfo.trulyEmptyTestGetInfo) { - call.respond(HttpStatusCode.OK) - } - } - } -} - fun Application.withExamples() { routing { route("/test/examples") { notarizedPost( - info = MethodInfo.PostInfo( + info = PostInfo( summary = "Example Parameters", description = "A test for setting parameter examples", requestInfo = RequestInfo( @@ -254,9 +230,13 @@ fun Application.withDefaultParameter() { routing { route("/test") { notarizedGet( - info = MethodInfo.GetInfo( + info = GetInfo( summary = "Testing Default Params", - description = "Should have a default parameter value" + description = "Should have a default parameter value", + responseInfo = ResponseInfo( + HttpStatusCode.OK, + "A good response" + ) ) ) { call.respond(TestResponse("hey")) @@ -280,7 +260,7 @@ fun Application.withOperationId(){ fun Application.nonRequiredParamsGet() { routing { route("/test/optional") { - notarizedGet(TestResponseInfo.emptyTestGetInfo) { + notarizedGet(TestResponseInfo.testOptionalParams) { call.respond(HttpStatusCode.OK) } } @@ -381,3 +361,173 @@ fun Application.simpleGenericResponse() { } } } + +fun Application.overrideFieldInfo() { + routing { + route("/test/field_override") { + notarizedGet(TestResponseInfo.fieldOverride) { + call.respond(HttpStatusCode.OK, TestFieldOverride(true)) + } + } + } +} + +fun Application.constrainedIntInfo() { + routing { + route("/test/constrained_int") { + notarizedGet(TestResponseInfo.minMaxInt) { + call.respond(HttpStatusCode.OK, TestResponse("hi")) + } + } + } +} + +fun Application.constrainedDoubleInfo() { + routing { + route("/test/constrained_int") { + notarizedGet(TestResponseInfo.minMaxDouble) { + call.respond(HttpStatusCode.OK, TestResponse("hi")) + } + } + } +} + +fun Application.exclusiveMinMax() { + routing { + route("/test/constrained_int") { + notarizedGet(TestResponseInfo.exclusiveMinMax) { + call.respond(HttpStatusCode.OK, TestResponse("hi")) + } + } + } +} + +fun Application.requiredParameter() { + routing { + route("/test/required_param") { + notarizedGet(requiredParam) { + call.respond(HttpStatusCode.OK, TestResponse("hi")) + } + } + } +} + +fun Application.defaultParameter() { + routing { + route("/test/required_param") { + notarizedGet(defaultParam) { + call.respond(HttpStatusCode.OK, TestResponse("hi")) + } + } + } +} + +fun Application.defaultField() { + routing { + route("/test/required_param") { + notarizedPost(defaultField) { + call.respond(HttpStatusCode.OK, TestResponse("hi")) + } + } + } +} + +fun Application.nullableField() { + routing { + route("/test/required_param") { + notarizedPost(nullableField) { + call.respond(HttpStatusCode.OK, TestResponse("hi")) + } + } + } +} + +fun Application.formattedParam() { + routing { + route("/test/required_param") { + notarizedGet(formattedParam) { + call.respond(HttpStatusCode.OK, TestResponse("hi")) + } + } + } +} + +fun Application.minMaxString() { + routing { + route("/test/required_param") { + notarizedGet(minMaxString) { + call.respond(HttpStatusCode.OK, TestResponse("hi")) + } + } + } +} + +fun Application.regexString() { + routing { + route("/test/required_param") { + notarizedGet(regexString) { + call.respond(HttpStatusCode.OK, TestResponse("hi")) + } + } + } +} + +fun Application.minMaxArray() { + routing { + route("/test/required_param") { + notarizedGet(TestResponseInfo.minMaxArray) { + call.respond(HttpStatusCode.OK, TestResponse("hi")) + } + } + } +} + +fun Application.uniqueArray() { + routing { + route("/test/required_param") { + notarizedGet(TestResponseInfo.uniqueArray) { + call.respond(HttpStatusCode.OK, TestResponse("hi")) + } + } + } +} + +fun Application.multipleOfInt() { + routing { + route("/test/required_param") { + notarizedGet(TestResponseInfo.multipleOfInt) { + call.respond(HttpStatusCode.OK, TestResponse("hi")) + } + } + } +} + +fun Application.multipleOfDouble() { + routing { + route("/test/required_param") { + notarizedGet(TestResponseInfo.multipleOfDouble) { + call.respond(HttpStatusCode.OK, TestResponse("hi")) + } + } + } +} + +fun Application.freeFormObject() { + routing { + route("/test/required_param") { + notarizedGet(TestResponseInfo.freeFormObject) { + call.respond(HttpStatusCode.OK, TestResponse("hi")) + } + } + } +} + +fun Application.minMaxFreeForm() { + routing { + route("/test/required_param") { + notarizedGet(TestResponseInfo.minMaxFreeForm) { + call.respond(HttpStatusCode.OK, TestResponse("hi")) + } + } + } +} diff --git a/kompendium-core/src/test/kotlin/io/bkbn/kompendium/util/TestHelpers.kt b/kompendium-core/src/test/kotlin/io/bkbn/kompendium/util/TestHelpers.kt deleted file mode 100644 index 9a37276d6..000000000 --- a/kompendium-core/src/test/kotlin/io/bkbn/kompendium/util/TestHelpers.kt +++ /dev/null @@ -1,11 +0,0 @@ -package io.bkbn.kompendium.util - -import java.io.File - -object TestHelpers { - fun getFileSnapshot(fileName: String): String { - val snapshotPath = "src/test/resources" - val file = File("$snapshotPath/$fileName") - return file.readText() - } -} diff --git a/kompendium-core/src/test/kotlin/io/bkbn/kompendium/util/TestModels.kt b/kompendium-core/src/test/kotlin/io/bkbn/kompendium/util/TestModels.kt deleted file mode 100644 index 0f738d072..000000000 --- a/kompendium-core/src/test/kotlin/io/bkbn/kompendium/util/TestModels.kt +++ /dev/null @@ -1,111 +0,0 @@ -package io.bkbn.kompendium.util - -import java.util.UUID -import io.bkbn.kompendium.annotations.KompendiumField -import io.bkbn.kompendium.annotations.KompendiumParam -import io.bkbn.kompendium.annotations.ParamType -import io.bkbn.kompendium.annotations.UndeclaredField -import java.math.BigDecimal -import java.math.BigInteger - -data class TestSimpleModel(val a: String, val b: Int) - -data class TestBigNumberModel(val a: BigDecimal, val b: BigInteger) - -data class TestByteArrayModel(val a: ByteArray) - -data class TestNestedModel(val inner: TestSimpleModel) - -data class TestSimpleWithEnums(val a: String, val b: SimpleEnum) - -data class TestSimpleWithMap(val a: String, val b: Map) - -data class TestSimpleWithList(val a: Boolean, val b: List) - -data class TestSimpleWithEnumList(val a: Double, val b: List) - -data class TestInvalidMap(val a: Map) - -data class TestParams( - @KompendiumParam(ParamType.PATH) val a: String, - @KompendiumParam(ParamType.QUERY) val aa: Int -) - -data class TestNested(val nesty: String) - -data class TestWithUUID(val id: UUID) - -data class TestRequest( - @KompendiumField(name = "field_name") - val fieldName: TestNested, - val b: Double, - val aaa: List -) - -data class TestResponse(val c: String) - -data class TestGeneric(val messy: String, val potato: T) - -data class TestCreatedResponse(val id: Int, val c: String) - -data class ComplexRequest( - val org: String, - @KompendiumField("amazing_field") - val amazingField: String, - val tables: List -) - -data class NestedComplexItem( - val name: String, - val alias: CustomAlias -) - -typealias CustomAlias = Map - -data class CrazyItem(val enumeration: SimpleEnum) - -enum class SimpleEnum { - ONE, - TWO -} - -data class DefaultParameter( - @KompendiumParam(ParamType.QUERY) val a: Int = 100, - @KompendiumParam(ParamType.PATH) val b: String?, - @KompendiumParam(ParamType.PATH) val c: Boolean -) - -data class ExceptionResponse(val message: String) - -data class OptionalParams( - @KompendiumParam(ParamType.QUERY) val required: String, - @KompendiumParam(ParamType.QUERY) val notRequired: String? -) - -sealed class FlibbityGibbit - -data class SimpleGibbit(val a: String) : FlibbityGibbit() -data class ComplexGibbit(val b: String, val c: Int) : FlibbityGibbit() - -sealed interface SlammaJamma - -data class OneJamma(val a: Int) : SlammaJamma -data class AnothaJamma(val b: Float) : SlammaJamma -//data class InsaneJamma(val c: SlammaJamma) : SlammaJamma // 👀 - -sealed interface Flibbity - -data class Gibbity(val a: T) : Flibbity -data class Bibbity(val b: String, val f: T) : Flibbity - -enum class Hehe { - HAHA, - HOHO -} - -@UndeclaredField("nowYouDont", Hehe::class) -data class Mysterious(val nowYouSeeMe: String) - -data class HeaderNameTest( - @KompendiumParam(type = ParamType.HEADER) val `X-UserEmail`: String -) diff --git a/kompendium-core/src/test/kotlin/io/bkbn/kompendium/util/TestResponseInfo.kt b/kompendium-core/src/test/kotlin/io/bkbn/kompendium/util/TestResponseInfo.kt deleted file mode 100644 index 028d57844..000000000 --- a/kompendium-core/src/test/kotlin/io/bkbn/kompendium/util/TestResponseInfo.kt +++ /dev/null @@ -1,123 +0,0 @@ -package io.bkbn.kompendium.util - -import io.bkbn.kompendium.models.meta.MethodInfo.DeleteInfo -import io.bkbn.kompendium.models.meta.MethodInfo.GetInfo -import io.bkbn.kompendium.models.meta.MethodInfo.PostInfo -import io.bkbn.kompendium.models.meta.MethodInfo.PutInfo -import io.bkbn.kompendium.models.meta.RequestInfo -import io.bkbn.kompendium.models.meta.ResponseInfo -import io.ktor.http.HttpStatusCode - -object TestResponseInfo { - private val testGetResponse = ResponseInfo(HttpStatusCode.OK, "A Successful Endeavor") - private val testGetListResponse = - ResponseInfo>(HttpStatusCode.OK, "A Successful List-y Endeavor") - private val testPostResponse = ResponseInfo(HttpStatusCode.Created, "A Successful Endeavor") - private val testPostResponseAgain = ResponseInfo(HttpStatusCode.Created, "A Successful Endeavor") - private val testDeleteResponse = - ResponseInfo(HttpStatusCode.NoContent, "A Successful Endeavor", mediaTypes = emptyList()) - private val testRequest = RequestInfo("A Test request") - private val testRequestAgain = RequestInfo("A Test request") - private val complexRequest = RequestInfo("A Complex request") - val testGetInfo = GetInfo( - summary = "Another get test", - description = "testing more", - responseInfo = testGetResponse - ) - val testGetInfoAgain = GetInfo>( - summary = "Another get test", - description = "testing more", - responseInfo = testGetListResponse - ) - val testGetWithException = testGetInfo.copy( - canThrow = setOf(Exception::class) - ) - val testGetWithMultipleExceptions = testGetInfo.copy( - canThrow = setOf(AccessDeniedException::class, Exception::class) - ) - val testPostInfo = PostInfo( - summary = "Test post endpoint", - description = "Post your tests here!", - responseInfo = testPostResponse, - requestInfo = testRequest - ) - val testPutInfo = PutInfo( - summary = "Test put endpoint", - description = "Put your tests here!", - responseInfo = testPostResponse, - requestInfo = complexRequest - ) - val testPutInfoAlso = PutInfo( - summary = "Test put endpoint", - description = "Put your tests here!", - responseInfo = testPostResponse, - requestInfo = testRequest - ) - val testPutInfoAgain = PutInfo( - summary = "Test put endpoint", - description = "Put your tests here!", - responseInfo = testPostResponseAgain, - requestInfo = testRequestAgain - ) - val testDeleteInfo = DeleteInfo( - summary = "Test delete endpoint", - description = "testing my deletes", - responseInfo = testDeleteResponse - ) - val emptyTestGetInfo = - GetInfo( - summary = "No request params and response body", - description = "testing more" - ) - val trulyEmptyTestGetInfo = GetInfo( - summary = "No request params and response body", - description = "testing more" - ) - val polymorphicResponse = GetInfo( - summary = "All the gibbits", - description = "Polymorphic response", - responseInfo = simpleOkResponse() - ) - val polymorphicListResponse = GetInfo>( - summary = "Oh so many gibbits", - description = "Polymorphic list response", - responseInfo = simpleOkResponse() - ) - val polymorphicMapResponse = GetInfo>( - summary = "By gawd that's a lot of gibbits", - description = "Polymorphic list response", - responseInfo = simpleOkResponse() - ) - val polymorphicInterfaceResponse = GetInfo( - summary = "Come on and slam", - description = "and welcome to the jam", - responseInfo = simpleOkResponse() - ) - val genericPolymorphicResponse = GetInfo>( - summary = "More flibbity", - description = "Polymorphic with generics", - responseInfo = simpleOkResponse() - ) - val anotherGenericPolymorphicResponse = GetInfo>( - summary = "The Most Flibbity", - description = "Polymorphic with generics but like... crazier", - responseInfo = simpleOkResponse() - ) - val undeclaredResponseType = GetInfo( - summary = "spooky class", - description = "break this glass in scenario of emergency", - responseInfo = simpleOkResponse() - ) - val headerParam = GetInfo( - summary = "testing header stuffs", - description = "Good for many things", - responseInfo = simpleOkResponse() - ) - val genericResponse = GetInfo>( - summary = "Single Generic", - description = "Simple generic data class", - responseInfo = simpleOkResponse() - ) - - private fun simpleOkResponse() = ResponseInfo(HttpStatusCode.OK, "A successful endeavor") -} diff --git a/kompendium-core/src/test/resources/complex_type.json b/kompendium-core/src/test/resources/complex_type.json index 75039002c..89726ce09 100644 --- a/kompendium-core/src/test/resources/complex_type.json +++ b/kompendium-core/src/test/resources/complex_type.json @@ -1,133 +1,126 @@ { - "openapi" : "3.0.3", - "info" : { - "title" : "Test API", - "version" : "1.33.7", - "description" : "An amazing, fully-ish 😉 generated API spec", - "termsOfService" : "https://example.com", - "contact" : { - "name" : "Homer Simpson", - "url" : "https://gph.is/1NPUDiM", - "email" : "chunkylover53@aol.com" + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" }, - "license" : { - "name" : "MIT", - "url" : "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" } }, - "servers" : [ { - "url" : "https://myawesomeapi.com", - "description" : "Production instance of my API" - }, { - "url" : "https://staging.myawesomeapi.com", - "description" : "Where the fun stuff happens" - } ], - "paths" : { - "/test" : { - "put" : { - "tags" : [ ], - "summary" : "Test put endpoint", - "description" : "Put your tests here!", - "parameters" : [ ], - "requestBody" : { - "description" : "A Complex request", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/ComplexRequest" + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/test": { + "put": { + "tags": [], + "summary": "Test put endpoint", + "description": "Put your tests here!", + "parameters": [], + "requestBody": { + "description": "A Complex request", + "content": { + "application/json": { + "schema": { + "properties": { + "amazing_field": { + "type": "string" + }, + "org": { + "type": "string" + }, + "tables": { + "items": { + "properties": { + "alias": { + "additionalProperties": { + "properties": { + "enumeration": { + "enum": [ + "ONE", + "TWO" + ], + "type": "string" + } + }, + "required": [ + "enumeration" + ], + "type": "object" + }, + "type": "object" + }, + "name": { + "type": "string" + } + }, + "required": [ + "name", + "alias" + ], + "type": "object" + }, + "type": "array" + } + }, + "required": [ + "org", + "amazingField", + "tables" + ], + "type": "object" } } }, - "required" : false + "required": true }, - "responses" : { - "201" : { - "description" : "A Successful Endeavor", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/TestCreatedResponse" + "responses": { + "201": { + "description": "A Successful Endeavor", + "content": { + "application/json": { + "schema": { + "properties": { + "c": { + "type": "string" + }, + "id": { + "format": "int32", + "type": "integer" + } + }, + "required": [ + "id", + "c" + ], + "type": "object" } } } } }, - "deprecated" : false + "deprecated": false } } }, - "components" : { - "schemas" : { - "String" : { - "type" : "string" - }, - "SimpleEnum" : { - "type" : "string", - "enum" : [ "ONE", "TWO" ] - }, - "CrazyItem" : { - "type" : "object", - "properties" : { - "enumeration" : { - "$ref" : "#/components/schemas/SimpleEnum" - } - } - }, - "Map-String-CrazyItem" : { - "type" : "object", - "additionalProperties" : { - "$ref" : "#/components/schemas/CrazyItem" - } - }, - "NestedComplexItem" : { - "type" : "object", - "properties" : { - "alias" : { - "$ref" : "#/components/schemas/Map-String-CrazyItem" - }, - "name" : { - "$ref" : "#/components/schemas/String" - } - } - }, - "List-NestedComplexItem" : { - "type" : "array", - "items" : { - "$ref" : "#/components/schemas/NestedComplexItem" - } - }, - "ComplexRequest" : { - "type" : "object", - "properties" : { - "amazingField" : { - "$ref" : "#/components/schemas/String" - }, - "org" : { - "$ref" : "#/components/schemas/String" - }, - "tables" : { - "$ref" : "#/components/schemas/List-NestedComplexItem" - } - } - }, - "Int" : { - "type" : "integer", - "format" : "int32" - }, - "TestCreatedResponse" : { - "type" : "object", - "properties" : { - "c" : { - "$ref" : "#/components/schemas/String" - }, - "id" : { - "$ref" : "#/components/schemas/Int" - } - } - } - }, - "securitySchemes" : { } + "components": { + "securitySchemes": {} }, - "security" : [ ], - "tags" : [ ] + "security": [], + "tags": [] } diff --git a/kompendium-core/src/test/resources/crazy_polymorphic_example.json b/kompendium-core/src/test/resources/crazy_polymorphic_example.json index d6be07cbc..d80f6640b 100644 --- a/kompendium-core/src/test/resources/crazy_polymorphic_example.json +++ b/kompendium-core/src/test/resources/crazy_polymorphic_example.json @@ -1,164 +1,203 @@ { - "openapi" : "3.0.3", - "info" : { - "title" : "Test API", - "version" : "1.33.7", - "description" : "An amazing, fully-ish 😉 generated API spec", - "termsOfService" : "https://example.com", - "contact" : { - "name" : "Homer Simpson", - "url" : "https://gph.is/1NPUDiM", - "email" : "chunkylover53@aol.com" + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" }, - "license" : { - "name" : "MIT", - "url" : "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" } }, - "servers" : [ { - "url" : "https://myawesomeapi.com", - "description" : "Production instance of my API" - }, { - "url" : "https://staging.myawesomeapi.com", - "description" : "Where the fun stuff happens" - } ], - "paths" : { - "/test/polymorphic" : { - "get" : { - "tags" : [ ], - "summary" : "More flibbity", - "description" : "Polymorphic with generics", - "parameters" : [ ], - "responses" : { - "200" : { - "description" : "A successful endeavor", - "content" : { - "application/json" : { - "schema" : { - "anyOf" : [ { - "$ref" : "#/components/schemas/Gibbity-TestNested" - }, { - "$ref" : "#/components/schemas/Bibbity-TestNested" - } ] + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/test/polymorphic": { + "get": { + "tags": [], + "summary": "More flibbity", + "description": "Polymorphic with generics", + "parameters": [], + "responses": { + "200": { + "description": "A successful endeavor", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "properties": { + "a": { + "properties": { + "nesty": { + "type": "string" + } + }, + "required": [ + "nesty" + ], + "type": "object" + } + }, + "required": [ + "a" + ], + "type": "object" + }, + { + "properties": { + "b": { + "type": "string" + }, + "f": { + "properties": { + "nesty": { + "type": "string" + } + }, + "required": [ + "nesty" + ], + "type": "object" + } + }, + "required": [ + "b", + "f" + ], + "type": "object" + } + ] } } } } }, - "deprecated" : false + "deprecated": false } }, - "/test/also/poly" : { - "get" : { - "tags" : [ ], - "summary" : "The Most Flibbity", - "description" : "Polymorphic with generics but like... crazier", - "parameters" : [ ], - "responses" : { - "200" : { - "description" : "A successful endeavor", - "content" : { - "application/json" : { - "schema" : { - "anyOf" : [ { - "$ref" : "#/components/schemas/Gibbity-FlibbityGibbit" - }, { - "$ref" : "#/components/schemas/Bibbity-FlibbityGibbit" - } ] + "/test/also/poly": { + "get": { + "tags": [], + "summary": "The Most Flibbity", + "description": "Polymorphic with generics but like... crazier", + "parameters": [], + "responses": { + "200": { + "description": "A successful endeavor", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "properties": { + "a": { + "anyOf": [ + { + "properties": { + "a": { + "type": "string" + } + }, + "required": [ + "a" + ], + "type": "object" + }, + { + "properties": { + "b": { + "type": "string" + }, + "c": { + "format": "int32", + "type": "integer" + } + }, + "required": [ + "b", + "c" + ], + "type": "object" + } + ] + } + }, + "required": [ + "a" + ], + "type": "object" + }, + { + "properties": { + "b": { + "type": "string" + }, + "f": { + "anyOf": [ + { + "properties": { + "a": { + "type": "string" + } + }, + "required": [ + "a" + ], + "type": "object" + }, + { + "properties": { + "b": { + "type": "string" + }, + "c": { + "format": "int32", + "type": "integer" + } + }, + "required": [ + "b", + "c" + ], + "type": "object" + } + ] + } + }, + "required": [ + "b", + "f" + ], + "type": "object" + } + ] } } } } }, - "deprecated" : false + "deprecated": false } } }, - "components" : { - "schemas" : { - "String" : { - "type" : "string" - }, - "TestNested" : { - "type" : "object", - "properties" : { - "nesty" : { - "$ref" : "#/components/schemas/String" - } - } - }, - "Gibbity-TestNested" : { - "type" : "object", - "properties" : { - "a" : { - "$ref" : "#/components/schemas/TestNested" - } - } - }, - "Bibbity-TestNested" : { - "type" : "object", - "properties" : { - "b" : { - "$ref" : "#/components/schemas/String" - }, - "f" : { - "$ref" : "#/components/schemas/TestNested" - } - } - }, - "SimpleGibbit" : { - "type" : "object", - "properties" : { - "a" : { - "$ref" : "#/components/schemas/String" - } - } - }, - "Int" : { - "type" : "integer", - "format" : "int32" - }, - "ComplexGibbit" : { - "type" : "object", - "properties" : { - "b" : { - "$ref" : "#/components/schemas/String" - }, - "c" : { - "$ref" : "#/components/schemas/Int" - } - } - }, - "Gibbity-FlibbityGibbit" : { - "type" : "object", - "properties" : { - "a" : { - "anyOf" : [ { - "$ref" : "#/components/schemas/SimpleGibbit" - }, { - "$ref" : "#/components/schemas/ComplexGibbit" - } ] - } - } - }, - "Bibbity-FlibbityGibbit" : { - "type" : "object", - "properties" : { - "b" : { - "$ref" : "#/components/schemas/String" - }, - "f" : { - "anyOf" : [ { - "$ref" : "#/components/schemas/SimpleGibbit" - }, { - "$ref" : "#/components/schemas/ComplexGibbit" - } ] - } - } - } - }, - "securitySchemes" : { } + "components": { + "securitySchemes": {} }, - "security" : [ ], - "tags" : [ ] + "security": [], + "tags": [] } diff --git a/kompendium-core/src/test/resources/default_field.json b/kompendium-core/src/test/resources/default_field.json new file mode 100644 index 000000000..f31bcb362 --- /dev/null +++ b/kompendium-core/src/test/resources/default_field.json @@ -0,0 +1,87 @@ +{ + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" + }, + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + } + }, + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/test/required_param": { + "post": { + "tags": [], + "summary": "default param", + "description": "Cool stuff", + "parameters": [], + "requestBody": { + "description": "cool", + "content": { + "application/json": { + "schema": { + "properties": { + "a": { + "type": "string" + }, + "b": { + "format": "int32", + "type": "integer" + } + }, + "required": [ + "b" + ], + "type": "object" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "A successful endeavor", + "content": { + "application/json": { + "schema": { + "properties": { + "c": { + "type": "string" + } + }, + "required": [ + "c" + ], + "type": "object" + } + } + } + } + }, + "deprecated": false + } + } + }, + "components": { + "securitySchemes": {} + }, + "security": [], + "tags": [] +} diff --git a/kompendium-core/src/test/resources/default_param.json b/kompendium-core/src/test/resources/default_param.json new file mode 100644 index 000000000..05934e56b --- /dev/null +++ b/kompendium-core/src/test/resources/default_param.json @@ -0,0 +1,75 @@ +{ + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" + }, + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + } + }, + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/test/required_param": { + "get": { + "tags": [], + "summary": "default param", + "description": "Cool stuff", + "parameters": [ + { + "name": "b", + "in": "query", + "schema": { + "type": "string", + "default": "heyo" + }, + "required": false, + "deprecated": false + } + ], + "responses": { + "200": { + "description": "A successful endeavor", + "content": { + "application/json": { + "schema": { + "properties": { + "c": { + "type": "string" + } + }, + "required": [ + "c" + ], + "type": "object" + } + } + } + } + }, + "deprecated": false + } + } + }, + "components": { + "securitySchemes": {} + }, + "security": [], + "tags": [] +} diff --git a/kompendium-core/src/test/resources/example_req_and_resp.json b/kompendium-core/src/test/resources/example_req_and_resp.json index 4070d701d..3346486ae 100644 --- a/kompendium-core/src/test/resources/example_req_and_resp.json +++ b/kompendium-core/src/test/resources/example_req_and_resp.json @@ -1,77 +1,119 @@ { - "openapi" : "3.0.3", - "info" : { - "title" : "Test API", - "version" : "1.33.7", - "description" : "An amazing, fully-ish 😉 generated API spec", - "termsOfService" : "https://example.com", - "contact" : { - "name" : "Homer Simpson", - "url" : "https://gph.is/1NPUDiM", - "email" : "chunkylover53@aol.com" + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" }, - "license" : { - "name" : "MIT", - "url" : "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" } }, - "servers" : [ { - "url" : "https://myawesomeapi.com", - "description" : "Production instance of my API" - }, { - "url" : "https://staging.myawesomeapi.com", - "description" : "Where the fun stuff happens" - } ], - "paths" : { - "/test/examples" : { - "post" : { - "tags" : [ ], - "summary" : "Example Parameters", - "description" : "A test for setting parameter examples", - "parameters" : [ ], - "requestBody" : { - "description" : "Test", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/TestRequest" - }, - "examples" : { - "one" : { - "value" : { - "fieldName" : { - "nesty" : "hey" + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/test/examples": { + "post": { + "tags": [], + "summary": "Example Parameters", + "description": "A test for setting parameter examples", + "parameters": [], + "requestBody": { + "description": "Test", + "content": { + "application/json": { + "schema": { + "properties": { + "aaa": { + "items": { + "format": "int64", + "type": "integer" }, - "b" : 4.0, - "aaa" : [ ] + "type": "array" + }, + "b": { + "format": "double", + "type": "number" + }, + "field_name": { + "properties": { + "nesty": { + "type": "string" + } + }, + "required": [ + "nesty" + ], + "type": "object" } }, - "two" : { - "value" : { - "fieldName" : { - "nesty" : "hello" + "required": [ + "fieldName", + "b", + "aaa" + ], + "type": "object" + }, + "examples": { + "one": { + "value": { + "fieldName": { + "nesty": "hey" }, - "b" : 3.8, - "aaa" : [ 31324234 ] + "b": 4.0, + "aaa": [] + } + }, + "two": { + "value": { + "fieldName": { + "nesty": "hello" + }, + "b": 3.8, + "aaa": [ + 31324234 + ] } } } } }, - "required" : false + "required": true }, - "responses" : { - "201" : { - "description" : "nice", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/TestResponse" + "responses": { + "201": { + "description": "nice", + "content": { + "application/json": { + "schema": { + "properties": { + "c": { + "type": "string" + } + }, + "required": [ + "c" + ], + "type": "object" }, - "examples" : { - "test" : { - "value" : { - "c" : "spud" + "examples": { + "test": { + "value": { + "c": "spud" } } } @@ -79,62 +121,13 @@ } } }, - "deprecated" : false + "deprecated": false } } }, - "components" : { - "schemas" : { - "Long" : { - "type" : "integer", - "format" : "int64" - }, - "List-Long" : { - "type" : "array", - "items" : { - "$ref" : "#/components/schemas/Long" - } - }, - "Double" : { - "type" : "number", - "format" : "double" - }, - "String" : { - "type" : "string" - }, - "TestNested" : { - "type" : "object", - "properties" : { - "nesty" : { - "$ref" : "#/components/schemas/String" - } - } - }, - "TestRequest" : { - "type" : "object", - "properties" : { - "aaa" : { - "$ref" : "#/components/schemas/List-Long" - }, - "b" : { - "$ref" : "#/components/schemas/Double" - }, - "fieldName" : { - "$ref" : "#/components/schemas/TestNested" - } - } - }, - "TestResponse" : { - "type" : "object", - "properties" : { - "c" : { - "$ref" : "#/components/schemas/String" - } - } - } - }, - "securitySchemes" : { } + "components": { + "securitySchemes": {} }, - "security" : [ ], - "tags" : [ ] + "security": [], + "tags": [] } diff --git a/kompendium-core/src/test/resources/exclusive_min_max.json b/kompendium-core/src/test/resources/exclusive_min_max.json new file mode 100644 index 000000000..898f2449b --- /dev/null +++ b/kompendium-core/src/test/resources/exclusive_min_max.json @@ -0,0 +1,69 @@ +{ + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" + }, + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + } + }, + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/test/constrained_int": { + "get": { + "tags": [], + "summary": "Constrained int field", + "description": "Cool stuff", + "parameters": [], + "responses": { + "200": { + "description": "A successful endeavor", + "content": { + "application/json": { + "schema": { + "properties": { + "a": { + "format": "int32", + "type": "integer", + "minimum": 5, + "maximum": 100, + "exclusiveMinimum": true, + "exclusiveMaximum": true + } + }, + "required": [ + "a" + ], + "type": "object" + } + } + } + } + }, + "deprecated": false + } + } + }, + "components": { + "securitySchemes": {} + }, + "security": [], + "tags": [] +} diff --git a/kompendium-core/src/test/resources/field_override.json b/kompendium-core/src/test/resources/field_override.json new file mode 100644 index 000000000..984c3e14a --- /dev/null +++ b/kompendium-core/src/test/resources/field_override.json @@ -0,0 +1,65 @@ +{ + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" + }, + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + } + }, + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/test/field_override": { + "get": { + "tags": [], + "summary": "A Response with a spicy field", + "description": "Important info within!", + "parameters": [], + "responses": { + "200": { + "description": "A successful endeavor", + "content": { + "application/json": { + "schema": { + "properties": { + "real_name": { + "type": "boolean", + "description": "A Field that is super important!" + } + }, + "required": [ + "b" + ], + "type": "object" + } + } + } + } + }, + "deprecated": false + } + } + }, + "components": { + "securitySchemes": {} + }, + "security": [], + "tags": [] +} diff --git a/kompendium-core/src/test/resources/formatted_param_type.json b/kompendium-core/src/test/resources/formatted_param_type.json new file mode 100644 index 000000000..076280f34 --- /dev/null +++ b/kompendium-core/src/test/resources/formatted_param_type.json @@ -0,0 +1,75 @@ +{ + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" + }, + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + } + }, + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/test/required_param": { + "get": { + "tags": [], + "summary": "required param", + "description": "Cool stuff", + "parameters": [ + { + "name": "a", + "in": "query", + "schema": { + "type": "string", + "format": "password" + }, + "required": true, + "deprecated": false + } + ], + "responses": { + "200": { + "description": "A successful endeavor", + "content": { + "application/json": { + "schema": { + "properties": { + "c": { + "type": "string" + } + }, + "required": [ + "c" + ], + "type": "object" + } + } + } + } + }, + "deprecated": false + } + } + }, + "components": { + "securitySchemes": {} + }, + "security": [], + "tags": [] +} diff --git a/kompendium-core/src/test/resources/free_form_object.json b/kompendium-core/src/test/resources/free_form_object.json new file mode 100644 index 000000000..87aa0e387 --- /dev/null +++ b/kompendium-core/src/test/resources/free_form_object.json @@ -0,0 +1,65 @@ +{ + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" + }, + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + } + }, + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/test/required_param": { + "get": { + "tags": [], + "summary": "required param", + "description": "Cool stuff", + "parameters": [], + "responses": { + "200": { + "description": "A successful endeavor", + "content": { + "application/json": { + "schema": { + "properties": { + "data": { + "additionalProperties": true, + "type": "object" + } + }, + "required": [ + "data" + ], + "type": "object" + } + } + } + } + }, + "deprecated": false + } + } + }, + "components": { + "securitySchemes": {} + }, + "security": [], + "tags": [] +} diff --git a/kompendium-core/src/test/resources/generic_exception.json b/kompendium-core/src/test/resources/generic_exception.json new file mode 100644 index 000000000..a98f3900c --- /dev/null +++ b/kompendium-core/src/test/resources/generic_exception.json @@ -0,0 +1,121 @@ +{ + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" + }, + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + } + }, + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/test": { + "get": { + "tags": [], + "summary": "Another get test", + "description": "testing more", + "parameters": [ + { + "name": "a", + "in": "path", + "schema": { + "type": "string" + }, + "required": true, + "deprecated": false + }, + { + "name": "aa", + "in": "query", + "schema": { + "format": "int32", + "type": "integer" + }, + "required": true, + "deprecated": false + } + ], + "responses": { + "200": { + "description": "A Successful Endeavor", + "content": { + "application/json": { + "schema": { + "properties": { + "c": { + "type": "string" + } + }, + "required": [ + "c" + ], + "type": "object" + } + } + } + }, + "400": { + "description": "Wow serious things went wrong", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "properties": { + "a": { + "type": "string" + } + }, + "required": [ + "a" + ], + "type": "object" + }, + { + "properties": { + "b": { + "type": "string" + }, + "f": { + "type": "string" + } + }, + "required": [ + "b", + "f" + ], + "type": "object" + } + ] + } + } + } + } + }, + "deprecated": false + } + } + }, + "components": { + "securitySchemes": {} + }, + "security": [], + "tags": [] +} diff --git a/kompendium-core/src/test/resources/generic_response.json b/kompendium-core/src/test/resources/generic_response.json index 06760aa09..a4755e772 100644 --- a/kompendium-core/src/test/resources/generic_response.json +++ b/kompendium-core/src/test/resources/generic_response.json @@ -1,73 +1,69 @@ { - "openapi" : "3.0.3", - "info" : { - "title" : "Test API", - "version" : "1.33.7", - "description" : "An amazing, fully-ish 😉 generated API spec", - "termsOfService" : "https://example.com", - "contact" : { - "name" : "Homer Simpson", - "url" : "https://gph.is/1NPUDiM", - "email" : "chunkylover53@aol.com" + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" }, - "license" : { - "name" : "MIT", - "url" : "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" } }, - "servers" : [ { - "url" : "https://myawesomeapi.com", - "description" : "Production instance of my API" - }, { - "url" : "https://staging.myawesomeapi.com", - "description" : "Where the fun stuff happens" - } ], - "paths" : { - "/test/polymorphic" : { - "get" : { - "tags" : [ ], - "summary" : "Single Generic", - "description" : "Simple generic data class", - "parameters" : [ ], - "responses" : { - "200" : { - "description" : "A successful endeavor", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/TestGeneric-Int" + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/test/polymorphic": { + "get": { + "tags": [], + "summary": "Single Generic", + "description": "Simple generic data class", + "parameters": [], + "responses": { + "200": { + "description": "A successful endeavor", + "content": { + "application/json": { + "schema": { + "properties": { + "messy": { + "type": "string" + }, + "potato": { + "format": "int32", + "type": "integer" + } + }, + "required": [ + "messy", + "potato" + ], + "type": "object" } } } } }, - "deprecated" : false + "deprecated": false } } }, - "components" : { - "schemas" : { - "String" : { - "type" : "string" - }, - "Int" : { - "type" : "integer", - "format" : "int32" - }, - "TestGeneric-Int" : { - "type" : "object", - "properties" : { - "messy" : { - "$ref" : "#/components/schemas/String" - }, - "potato" : { - "$ref" : "#/components/schemas/Int" - } - } - } - }, - "securitySchemes" : { } + "components": { + "securitySchemes": {} }, - "security" : [ ], - "tags" : [ ] + "security": [], + "tags": [] } diff --git a/kompendium-core/src/test/resources/min_max_array.json b/kompendium-core/src/test/resources/min_max_array.json new file mode 100644 index 000000000..11dd22b6f --- /dev/null +++ b/kompendium-core/src/test/resources/min_max_array.json @@ -0,0 +1,69 @@ +{ + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" + }, + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + } + }, + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/test/required_param": { + "get": { + "tags": [], + "summary": "required param", + "description": "Cool stuff", + "parameters": [], + "responses": { + "200": { + "description": "A successful endeavor", + "content": { + "application/json": { + "schema": { + "properties": { + "a": { + "items": { + "type": "string" + }, + "minItems": 1, + "maxItems": 10, + "type": "array" + } + }, + "required": [ + "a" + ], + "type": "object" + } + } + } + } + }, + "deprecated": false + } + } + }, + "components": { + "securitySchemes": {} + }, + "security": [], + "tags": [] +} diff --git a/kompendium-core/src/test/resources/min_max_double_field.json b/kompendium-core/src/test/resources/min_max_double_field.json new file mode 100644 index 000000000..746392257 --- /dev/null +++ b/kompendium-core/src/test/resources/min_max_double_field.json @@ -0,0 +1,69 @@ +{ + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" + }, + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + } + }, + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/test/constrained_int": { + "get": { + "tags": [], + "summary": "Constrained int field", + "description": "Cool stuff", + "parameters": [], + "responses": { + "200": { + "description": "A successful endeavor", + "content": { + "application/json": { + "schema": { + "properties": { + "a": { + "format": "double", + "type": "number", + "minimum": 5.5, + "maximum": 13.37, + "exclusiveMinimum": false, + "exclusiveMaximum": false + } + }, + "required": [ + "a" + ], + "type": "object" + } + } + } + } + }, + "deprecated": false + } + } + }, + "components": { + "securitySchemes": {} + }, + "security": [], + "tags": [] +} diff --git a/kompendium-core/src/test/resources/min_max_free_form.json b/kompendium-core/src/test/resources/min_max_free_form.json new file mode 100644 index 000000000..9a1b07406 --- /dev/null +++ b/kompendium-core/src/test/resources/min_max_free_form.json @@ -0,0 +1,67 @@ +{ + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" + }, + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + } + }, + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/test/required_param": { + "get": { + "tags": [], + "summary": "required param", + "description": "Cool stuff", + "parameters": [], + "responses": { + "200": { + "description": "A successful endeavor", + "content": { + "application/json": { + "schema": { + "properties": { + "data": { + "minProperties": 5, + "maxProperties": 10, + "additionalProperties": true, + "type": "object" + } + }, + "required": [ + "data" + ], + "type": "object" + } + } + } + } + }, + "deprecated": false + } + } + }, + "components": { + "securitySchemes": {} + }, + "security": [], + "tags": [] +} diff --git a/kompendium-core/src/test/resources/min_max_int_field.json b/kompendium-core/src/test/resources/min_max_int_field.json new file mode 100644 index 000000000..37b1afcae --- /dev/null +++ b/kompendium-core/src/test/resources/min_max_int_field.json @@ -0,0 +1,69 @@ +{ + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" + }, + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + } + }, + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/test/constrained_int": { + "get": { + "tags": [], + "summary": "Constrained int field", + "description": "Cool stuff", + "parameters": [], + "responses": { + "200": { + "description": "A successful endeavor", + "content": { + "application/json": { + "schema": { + "properties": { + "a": { + "format": "int32", + "type": "integer", + "minimum": 5, + "maximum": 100, + "exclusiveMinimum": false, + "exclusiveMaximum": false + } + }, + "required": [ + "a" + ], + "type": "object" + } + } + } + } + }, + "deprecated": false + } + } + }, + "components": { + "securitySchemes": {} + }, + "security": [], + "tags": [] +} diff --git a/kompendium-core/src/test/resources/min_max_string.json b/kompendium-core/src/test/resources/min_max_string.json new file mode 100644 index 000000000..482dcbbfa --- /dev/null +++ b/kompendium-core/src/test/resources/min_max_string.json @@ -0,0 +1,66 @@ +{ + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" + }, + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + } + }, + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/test/required_param": { + "get": { + "tags": [], + "summary": "required param", + "description": "Cool stuff", + "parameters": [], + "responses": { + "200": { + "description": "A successful endeavor", + "content": { + "application/json": { + "schema": { + "properties": { + "a": { + "type": "string", + "minLength": 42, + "maxLength": 1337 + } + }, + "required": [ + "a" + ], + "type": "object" + } + } + } + } + }, + "deprecated": false + } + } + }, + "components": { + "securitySchemes": {} + }, + "security": [], + "tags": [] +} diff --git a/kompendium-core/src/test/resources/multiple_of_double.json b/kompendium-core/src/test/resources/multiple_of_double.json new file mode 100644 index 000000000..22b293a23 --- /dev/null +++ b/kompendium-core/src/test/resources/multiple_of_double.json @@ -0,0 +1,66 @@ +{ + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" + }, + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + } + }, + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/test/required_param": { + "get": { + "tags": [], + "summary": "required param", + "description": "Cool stuff", + "parameters": [], + "responses": { + "200": { + "description": "A successful endeavor", + "content": { + "application/json": { + "schema": { + "properties": { + "a": { + "format": "double", + "type": "number", + "multipleOf": 2.5 + } + }, + "required": [ + "a" + ], + "type": "object" + } + } + } + } + }, + "deprecated": false + } + } + }, + "components": { + "securitySchemes": {} + }, + "security": [], + "tags": [] +} diff --git a/kompendium-core/src/test/resources/multiple_of_int.json b/kompendium-core/src/test/resources/multiple_of_int.json new file mode 100644 index 000000000..a1350fc21 --- /dev/null +++ b/kompendium-core/src/test/resources/multiple_of_int.json @@ -0,0 +1,66 @@ +{ + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" + }, + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + } + }, + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/test/required_param": { + "get": { + "tags": [], + "summary": "required param", + "description": "Cool stuff", + "parameters": [], + "responses": { + "200": { + "description": "A successful endeavor", + "content": { + "application/json": { + "schema": { + "properties": { + "a": { + "format": "int32", + "type": "integer", + "multipleOf": 5 + } + }, + "required": [ + "a" + ], + "type": "object" + } + } + } + } + }, + "deprecated": false + } + } + }, + "components": { + "securitySchemes": {} + }, + "security": [], + "tags": [] +} diff --git a/kompendium-core/src/test/resources/nested_under_root.json b/kompendium-core/src/test/resources/nested_under_root.json index f9f9784cb..c3d4d1b45 100644 --- a/kompendium-core/src/test/resources/nested_under_root.json +++ b/kompendium-core/src/test/resources/nested_under_root.json @@ -1,87 +1,84 @@ { - "openapi" : "3.0.3", - "info" : { - "title" : "Test API", - "version" : "1.33.7", - "description" : "An amazing, fully-ish 😉 generated API spec", - "termsOfService" : "https://example.com", - "contact" : { - "name" : "Homer Simpson", - "url" : "https://gph.is/1NPUDiM", - "email" : "chunkylover53@aol.com" + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" }, - "license" : { - "name" : "MIT", - "url" : "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" } }, - "servers" : [ { - "url" : "https://myawesomeapi.com", - "description" : "Production instance of my API" - }, { - "url" : "https://staging.myawesomeapi.com", - "description" : "Where the fun stuff happens" - } ], - "paths" : { - "/testerino" : { - "get" : { - "tags" : [ ], - "summary" : "Another get test", - "description" : "testing more", - "parameters" : [ { - "name" : "a", - "in" : "path", - "schema" : { - "type" : "string" + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/testerino": { + "get": { + "tags": [], + "summary": "Another get test", + "description": "testing more", + "parameters": [ + { + "name": "a", + "in": "path", + "schema": { + "type": "string" + }, + "required": true, + "deprecated": false }, - "required" : true, - "deprecated" : false - }, { - "name" : "aa", - "in" : "query", - "schema" : { - "type" : "integer", - "format" : "int32" - }, - "required" : true, - "deprecated" : false - } ], - "responses" : { - "200" : { - "description" : "A Successful Endeavor", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/TestResponse" + { + "name": "aa", + "in": "query", + "schema": { + "format": "int32", + "type": "integer" + }, + "required": true, + "deprecated": false + } + ], + "responses": { + "200": { + "description": "A Successful Endeavor", + "content": { + "application/json": { + "schema": { + "properties": { + "c": { + "type": "string" + } + }, + "required": [ + "c" + ], + "type": "object" } } } } }, - "deprecated" : false + "deprecated": false } } }, - "components" : { - "schemas" : { - "String" : { - "type" : "string" - }, - "TestResponse" : { - "type" : "object", - "properties" : { - "c" : { - "$ref" : "#/components/schemas/String" - } - } - }, - "Int" : { - "type" : "integer", - "format" : "int32" - } - }, - "securitySchemes" : { } + "components": { + "securitySchemes": {} }, - "security" : [ ], - "tags" : [ ] + "security": [], + "tags": [] } diff --git a/kompendium-core/src/test/resources/no_request_params_and_no_response_body.json b/kompendium-core/src/test/resources/no_request_params_and_no_response_body.json deleted file mode 100644 index 1de45f46c..000000000 --- a/kompendium-core/src/test/resources/no_request_params_and_no_response_body.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "openapi" : "3.0.3", - "info" : { - "title" : "Test API", - "version" : "1.33.7", - "description" : "An amazing, fully-ish 😉 generated API spec", - "termsOfService" : "https://example.com", - "contact" : { - "name" : "Homer Simpson", - "url" : "https://gph.is/1NPUDiM", - "email" : "chunkylover53@aol.com" - }, - "license" : { - "name" : "MIT", - "url" : "https://github.com/bkbnio/kompendium/blob/main/LICENSE" - } - }, - "servers" : [ { - "url" : "https://myawesomeapi.com", - "description" : "Production instance of my API" - }, { - "url" : "https://staging.myawesomeapi.com", - "description" : "Where the fun stuff happens" - } ], - "paths" : { - "/test/empty" : { - "get" : { - "tags" : [ ], - "summary" : "No request params and response body", - "description" : "testing more", - "parameters" : [ ], - "deprecated" : false - } - } - }, - "components" : { - "schemas" : { }, - "securitySchemes" : { } - }, - "security" : [ ], - "tags" : [ ] -} diff --git a/kompendium-core/src/test/resources/non_required_params.json b/kompendium-core/src/test/resources/non_required_params.json index 225018964..88586e6d8 100644 --- a/kompendium-core/src/test/resources/non_required_params.json +++ b/kompendium-core/src/test/resources/non_required_params.json @@ -1,62 +1,69 @@ { - "openapi" : "3.0.3", - "info" : { - "title" : "Test API", - "version" : "1.33.7", - "description" : "An amazing, fully-ish 😉 generated API spec", - "termsOfService" : "https://example.com", - "contact" : { - "name" : "Homer Simpson", - "url" : "https://gph.is/1NPUDiM", - "email" : "chunkylover53@aol.com" + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" }, - "license" : { - "name" : "MIT", - "url" : "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" } }, - "servers" : [ { - "url" : "https://myawesomeapi.com", - "description" : "Production instance of my API" - }, { - "url" : "https://staging.myawesomeapi.com", - "description" : "Where the fun stuff happens" - } ], - "paths" : { - "/test/optional" : { - "get" : { - "tags" : [ ], - "summary" : "No request params and response body", - "description" : "testing more", - "parameters" : [ { - "name" : "notRequired", - "in" : "query", - "schema" : { - "type" : "string" + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/test/optional": { + "get": { + "tags": [], + "summary": "No request params and response body", + "description": "testing more", + "parameters": [ + { + "name": "notRequired", + "in": "query", + "schema": { + "type": "string", + "nullable": true + }, + "required": false, + "deprecated": false }, - "required" : false, - "deprecated" : false - }, { - "name" : "required", - "in" : "query", - "schema" : { - "type" : "string" - }, - "required" : true, - "deprecated" : false - } ], - "deprecated" : false + { + "name": "required", + "in": "query", + "schema": { + "type": "string" + }, + "required": true, + "deprecated": false + } + ], + "responses": { + "204": { + "description": "Empty" + } + }, + "deprecated": false } } }, - "components" : { - "schemas" : { - "String" : { - "type" : "string" - } - }, - "securitySchemes" : { } + "components": { + "securitySchemes": {} }, - "security" : [ ], - "tags" : [ ] + "security": [], + "tags": [] } diff --git a/kompendium-core/src/test/resources/notarized_delete.json b/kompendium-core/src/test/resources/notarized_delete.json index d48e3b660..db1a8ce35 100644 --- a/kompendium-core/src/test/resources/notarized_delete.json +++ b/kompendium-core/src/test/resources/notarized_delete.json @@ -40,8 +40,8 @@ "name" : "aa", "in" : "query", "schema" : { - "type" : "integer", - "format" : "int32" + "format" : "int32", + "type" : "integer" }, "required" : true, "deprecated" : false @@ -56,15 +56,6 @@ } }, "components" : { - "schemas" : { - "String" : { - "type" : "string" - }, - "Int" : { - "type" : "integer", - "format" : "int32" - } - }, "securitySchemes" : { } }, "security" : [ ], diff --git a/kompendium-core/src/test/resources/notarized_get.json b/kompendium-core/src/test/resources/notarized_get.json index 3ea783cf5..32f18d138 100644 --- a/kompendium-core/src/test/resources/notarized_get.json +++ b/kompendium-core/src/test/resources/notarized_get.json @@ -1,87 +1,84 @@ { - "openapi" : "3.0.3", - "info" : { - "title" : "Test API", - "version" : "1.33.7", - "description" : "An amazing, fully-ish 😉 generated API spec", - "termsOfService" : "https://example.com", - "contact" : { - "name" : "Homer Simpson", - "url" : "https://gph.is/1NPUDiM", - "email" : "chunkylover53@aol.com" + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" }, - "license" : { - "name" : "MIT", - "url" : "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" } }, - "servers" : [ { - "url" : "https://myawesomeapi.com", - "description" : "Production instance of my API" - }, { - "url" : "https://staging.myawesomeapi.com", - "description" : "Where the fun stuff happens" - } ], - "paths" : { - "/test" : { - "get" : { - "tags" : [ ], - "summary" : "Another get test", - "description" : "testing more", - "parameters" : [ { - "name" : "a", - "in" : "path", - "schema" : { - "type" : "string" + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/test": { + "get": { + "tags": [], + "summary": "Another get test", + "description": "testing more", + "parameters": [ + { + "name": "a", + "in": "path", + "schema": { + "type": "string" + }, + "required": true, + "deprecated": false }, - "required" : true, - "deprecated" : false - }, { - "name" : "aa", - "in" : "query", - "schema" : { - "type" : "integer", - "format" : "int32" - }, - "required" : true, - "deprecated" : false - } ], - "responses" : { - "200" : { - "description" : "A Successful Endeavor", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/TestResponse" + { + "name": "aa", + "in": "query", + "schema": { + "format": "int32", + "type": "integer" + }, + "required": true, + "deprecated": false + } + ], + "responses": { + "200": { + "description": "A Successful Endeavor", + "content": { + "application/json": { + "schema": { + "properties": { + "c": { + "type": "string" + } + }, + "required": [ + "c" + ], + "type": "object" } } } } }, - "deprecated" : false + "deprecated": false } } }, - "components" : { - "schemas" : { - "String" : { - "type" : "string" - }, - "TestResponse" : { - "type" : "object", - "properties" : { - "c" : { - "$ref" : "#/components/schemas/String" - } - } - }, - "Int" : { - "type" : "integer", - "format" : "int32" - } - }, - "securitySchemes" : { } + "components": { + "securitySchemes": {} }, - "security" : [ ], - "tags" : [ ] + "security": [], + "tags": [] } diff --git a/kompendium-core/src/test/resources/notarized_get_with_exception_response.json b/kompendium-core/src/test/resources/notarized_get_with_exception_response.json index eb9e502ab..78c597928 100644 --- a/kompendium-core/src/test/resources/notarized_get_with_exception_response.json +++ b/kompendium-core/src/test/resources/notarized_get_with_exception_response.json @@ -1,105 +1,102 @@ { - "openapi" : "3.0.3", - "info" : { - "title" : "Test API", - "version" : "1.33.7", - "description" : "An amazing, fully-ish 😉 generated API spec", - "termsOfService" : "https://example.com", - "contact" : { - "name" : "Homer Simpson", - "url" : "https://gph.is/1NPUDiM", - "email" : "chunkylover53@aol.com" + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" }, - "license" : { - "name" : "MIT", - "url" : "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" } }, - "servers" : [ { - "url" : "https://myawesomeapi.com", - "description" : "Production instance of my API" - }, { - "url" : "https://staging.myawesomeapi.com", - "description" : "Where the fun stuff happens" - } ], - "paths" : { - "/test" : { - "get" : { - "tags" : [ ], - "summary" : "Another get test", - "description" : "testing more", - "parameters" : [ { - "name" : "a", - "in" : "path", - "schema" : { - "type" : "string" + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/test": { + "get": { + "tags": [], + "summary": "Another get test", + "description": "testing more", + "parameters": [ + { + "name": "a", + "in": "path", + "schema": { + "type": "string" + }, + "required": true, + "deprecated": false }, - "required" : true, - "deprecated" : false - }, { - "name" : "aa", - "in" : "query", - "schema" : { - "type" : "integer", - "format" : "int32" - }, - "required" : true, - "deprecated" : false - } ], - "responses" : { - "200" : { - "description" : "A Successful Endeavor", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/TestResponse" + { + "name": "aa", + "in": "query", + "schema": { + "format": "int32", + "type": "integer" + }, + "required": true, + "deprecated": false + } + ], + "responses": { + "200": { + "description": "A Successful Endeavor", + "content": { + "application/json": { + "schema": { + "properties": { + "c": { + "type": "string" + } + }, + "required": [ + "c" + ], + "type": "object" } } } }, - "400" : { - "description" : "Bad Things Happened", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/ExceptionResponse" + "400": { + "description": "Bad Things Happened", + "content": { + "application/json": { + "schema": { + "properties": { + "message": { + "type": "string" + } + }, + "required": [ + "message" + ], + "type": "object" } } } } }, - "deprecated" : false + "deprecated": false } } }, - "components" : { - "schemas" : { - "String" : { - "type" : "string" - }, - "ExceptionResponse" : { - "type" : "object", - "properties" : { - "message" : { - "$ref" : "#/components/schemas/String" - } - } - }, - "TestResponse" : { - "type" : "object", - "properties" : { - "c" : { - "$ref" : "#/components/schemas/String" - } - } - }, - "Int" : { - "type" : "integer", - "format" : "int32" - } - }, - "securitySchemes" : { } + "components": { + "securitySchemes": {} }, - "security" : [ ], - "tags" : [ ] + "security": [], + "tags": [] } diff --git a/kompendium-core/src/test/resources/notarized_get_with_multiple_exception_responses.json b/kompendium-core/src/test/resources/notarized_get_with_multiple_exception_responses.json index 3d3e0c1f3..a603b8815 100644 --- a/kompendium-core/src/test/resources/notarized_get_with_multiple_exception_responses.json +++ b/kompendium-core/src/test/resources/notarized_get_with_multiple_exception_responses.json @@ -1,108 +1,120 @@ { - "openapi" : "3.0.3", - "info" : { - "title" : "Test API", - "version" : "1.33.7", - "description" : "An amazing, fully-ish 😉 generated API spec", - "termsOfService" : "https://example.com", - "contact" : { - "name" : "Homer Simpson", - "url" : "https://gph.is/1NPUDiM", - "email" : "chunkylover53@aol.com" + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" }, - "license" : { - "name" : "MIT", - "url" : "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" } }, - "servers" : [ { - "url" : "https://myawesomeapi.com", - "description" : "Production instance of my API" - }, { - "url" : "https://staging.myawesomeapi.com", - "description" : "Where the fun stuff happens" - } ], - "paths" : { - "/test" : { - "get" : { - "tags" : [ ], - "summary" : "Another get test", - "description" : "testing more", - "parameters" : [ { - "name" : "a", - "in" : "path", - "schema" : { - "type" : "string" + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/test": { + "get": { + "tags": [], + "summary": "Another get test", + "description": "testing more", + "parameters": [ + { + "name": "a", + "in": "path", + "schema": { + "type": "string" + }, + "required": true, + "deprecated": false }, - "required" : true, - "deprecated" : false - }, { - "name" : "aa", - "in" : "query", - "schema" : { - "type" : "integer", - "format" : "int32" - }, - "required" : true, - "deprecated" : false - } ], - "responses" : { - "200" : { - "description" : "A Successful Endeavor", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/TestResponse" + { + "name": "aa", + "in": "query", + "schema": { + "format": "int32", + "type": "integer" + }, + "required": true, + "deprecated": false + } + ], + "responses": { + "200": { + "description": "A Successful Endeavor", + "content": { + "application/json": { + "schema": { + "properties": { + "c": { + "type": "string" + } + }, + "required": [ + "c" + ], + "type": "object" } } } }, - "403" : { - "description" : "New API who dis?" + "403": { + "description": "Access Denied", + "content": { + "application/json": { + "schema": { + "properties": { + "message": { + "type": "string" + } + }, + "required": [ + "message" + ], + "type": "object" + } + } + } }, - "400" : { - "description" : "Bad Things Happened", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/ExceptionResponse" + "400": { + "description": "Bad Things Happened", + "content": { + "application/json": { + "schema": { + "properties": { + "message": { + "type": "string" + } + }, + "required": [ + "message" + ], + "type": "object" } } } } }, - "deprecated" : false + "deprecated": false } } }, - "components" : { - "schemas" : { - "String" : { - "type" : "string" - }, - "ExceptionResponse" : { - "type" : "object", - "properties" : { - "message" : { - "$ref" : "#/components/schemas/String" - } - } - }, - "TestResponse" : { - "type" : "object", - "properties" : { - "c" : { - "$ref" : "#/components/schemas/String" - } - } - }, - "Int" : { - "type" : "integer", - "format" : "int32" - } - }, - "securitySchemes" : { } + "components": { + "securitySchemes": {} }, - "security" : [ ], - "tags" : [ ] + "security": [], + "tags": [] } diff --git a/kompendium-core/src/test/resources/notarized_get_with_operation_id.json b/kompendium-core/src/test/resources/notarized_get_with_operation_id.json index 416d7fe29..c3880a913 100644 --- a/kompendium-core/src/test/resources/notarized_get_with_operation_id.json +++ b/kompendium-core/src/test/resources/notarized_get_with_operation_id.json @@ -1,88 +1,85 @@ { - "openapi" : "3.0.3", - "info" : { - "title" : "Test API", - "version" : "1.33.7", - "description" : "An amazing, fully-ish 😉 generated API spec", - "termsOfService" : "https://example.com", - "contact" : { - "name" : "Homer Simpson", - "url" : "https://gph.is/1NPUDiM", - "email" : "chunkylover53@aol.com" + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" }, - "license" : { - "name" : "MIT", - "url" : "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" } }, - "servers" : [ { - "url" : "https://myawesomeapi.com", - "description" : "Production instance of my API" - }, { - "url" : "https://staging.myawesomeapi.com", - "description" : "Where the fun stuff happens" - } ], - "paths" : { - "/test" : { - "get" : { - "tags" : [ ], - "summary" : "Another get test", - "description" : "testing more", - "operationId" : "getTest", - "parameters" : [ { - "name" : "a", - "in" : "path", - "schema" : { - "type" : "string" + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/test": { + "get": { + "tags": [], + "summary": "Another get test", + "description": "testing more", + "operationId": "getTest", + "parameters": [ + { + "name": "a", + "in": "path", + "schema": { + "type": "string" + }, + "required": true, + "deprecated": false }, - "required" : true, - "deprecated" : false - }, { - "name" : "aa", - "in" : "query", - "schema" : { - "type" : "integer", - "format" : "int32" - }, - "required" : true, - "deprecated" : false - } ], - "responses" : { - "200" : { - "description" : "A Successful Endeavor", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/TestResponse" + { + "name": "aa", + "in": "query", + "schema": { + "format": "int32", + "type": "integer" + }, + "required": true, + "deprecated": false + } + ], + "responses": { + "200": { + "description": "A Successful Endeavor", + "content": { + "application/json": { + "schema": { + "properties": { + "c": { + "type": "string" + } + }, + "required": [ + "c" + ], + "type": "object" } } } } }, - "deprecated" : false + "deprecated": false } } }, - "components" : { - "schemas" : { - "String" : { - "type" : "string" - }, - "TestResponse" : { - "type" : "object", - "properties" : { - "c" : { - "$ref" : "#/components/schemas/String" - } - } - }, - "Int" : { - "type" : "integer", - "format" : "int32" - } - }, - "securitySchemes" : { } + "components": { + "securitySchemes": {} }, - "security" : [ ], - "tags" : [ ] + "security": [], + "tags": [] } diff --git a/kompendium-core/src/test/resources/notarized_post.json b/kompendium-core/src/test/resources/notarized_post.json index 61d6a2344..c66447151 100644 --- a/kompendium-core/src/test/resources/notarized_post.json +++ b/kompendium-core/src/test/resources/notarized_post.json @@ -1,137 +1,129 @@ { - "openapi" : "3.0.3", - "info" : { - "title" : "Test API", - "version" : "1.33.7", - "description" : "An amazing, fully-ish 😉 generated API spec", - "termsOfService" : "https://example.com", - "contact" : { - "name" : "Homer Simpson", - "url" : "https://gph.is/1NPUDiM", - "email" : "chunkylover53@aol.com" + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" }, - "license" : { - "name" : "MIT", - "url" : "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" } }, - "servers" : [ { - "url" : "https://myawesomeapi.com", - "description" : "Production instance of my API" - }, { - "url" : "https://staging.myawesomeapi.com", - "description" : "Where the fun stuff happens" - } ], - "paths" : { - "/test" : { - "post" : { - "tags" : [ ], - "summary" : "Test post endpoint", - "description" : "Post your tests here!", - "parameters" : [ { - "name" : "a", - "in" : "path", - "schema" : { - "type" : "string" + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/test": { + "post": { + "tags": [], + "summary": "Test post endpoint", + "description": "Post your tests here!", + "parameters": [ + { + "name": "a", + "in": "path", + "schema": { + "type": "string" + }, + "required": true, + "deprecated": false }, - "required" : true, - "deprecated" : false - }, { - "name" : "aa", - "in" : "query", - "schema" : { - "type" : "integer", - "format" : "int32" - }, - "required" : true, - "deprecated" : false - } ], - "requestBody" : { - "description" : "A Test request", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/TestRequest" + { + "name": "aa", + "in": "query", + "schema": { + "format": "int32", + "type": "integer" + }, + "required": true, + "deprecated": false + } + ], + "requestBody": { + "description": "A Test request", + "content": { + "application/json": { + "schema": { + "properties": { + "aaa": { + "items": { + "format": "int64", + "type": "integer" + }, + "type": "array" + }, + "b": { + "format": "double", + "type": "number" + }, + "field_name": { + "properties": { + "nesty": { + "type": "string" + } + }, + "required": [ + "nesty" + ], + "type": "object" + } + }, + "required": [ + "fieldName", + "b", + "aaa" + ], + "type": "object" } } }, - "required" : false + "required": true }, - "responses" : { - "201" : { - "description" : "A Successful Endeavor", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/TestCreatedResponse" + "responses": { + "201": { + "description": "A Successful Endeavor", + "content": { + "application/json": { + "schema": { + "properties": { + "c": { + "type": "string" + }, + "id": { + "format": "int32", + "type": "integer" + } + }, + "required": [ + "id", + "c" + ], + "type": "object" } } } } }, - "deprecated" : false + "deprecated": false } } }, - "components" : { - "schemas" : { - "Long" : { - "type" : "integer", - "format" : "int64" - }, - "List-Long" : { - "type" : "array", - "items" : { - "$ref" : "#/components/schemas/Long" - } - }, - "Double" : { - "type" : "number", - "format" : "double" - }, - "String" : { - "type" : "string" - }, - "TestNested" : { - "type" : "object", - "properties" : { - "nesty" : { - "$ref" : "#/components/schemas/String" - } - } - }, - "TestRequest" : { - "type" : "object", - "properties" : { - "aaa" : { - "$ref" : "#/components/schemas/List-Long" - }, - "b" : { - "$ref" : "#/components/schemas/Double" - }, - "fieldName" : { - "$ref" : "#/components/schemas/TestNested" - } - } - }, - "Int" : { - "type" : "integer", - "format" : "int32" - }, - "TestCreatedResponse" : { - "type" : "object", - "properties" : { - "c" : { - "$ref" : "#/components/schemas/String" - }, - "id" : { - "$ref" : "#/components/schemas/Int" - } - } - } - }, - "securitySchemes" : { } + "components": { + "securitySchemes": {} }, - "security" : [ ], - "tags" : [ ] + "security": [], + "tags": [] } diff --git a/kompendium-core/src/test/resources/notarized_primitives.json b/kompendium-core/src/test/resources/notarized_primitives.json index 0d9271515..a237b2488 100644 --- a/kompendium-core/src/test/resources/notarized_primitives.json +++ b/kompendium-core/src/test/resources/notarized_primitives.json @@ -1,73 +1,68 @@ { - "openapi" : "3.0.3", - "info" : { - "title" : "Test API", - "version" : "1.33.7", - "description" : "An amazing, fully-ish 😉 generated API spec", - "termsOfService" : "https://example.com", - "contact" : { - "name" : "Homer Simpson", - "url" : "https://gph.is/1NPUDiM", - "email" : "chunkylover53@aol.com" + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" }, - "license" : { - "name" : "MIT", - "url" : "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" } }, - "servers" : [ { - "url" : "https://myawesomeapi.com", - "description" : "Production instance of my API" - }, { - "url" : "https://staging.myawesomeapi.com", - "description" : "Where the fun stuff happens" - } ], - "paths" : { - "/test" : { - "put" : { - "tags" : [ ], - "summary" : "Test put endpoint", - "description" : "Put your tests here!", - "parameters" : [ ], - "requestBody" : { - "description" : "A Test request", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/Int" + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/test": { + "put": { + "tags": [], + "summary": "Test put endpoint", + "description": "Put your tests here!", + "parameters": [], + "requestBody": { + "description": "A Test request", + "content": { + "application/json": { + "schema": { + "format": "int32", + "type": "integer" } } }, - "required" : false + "required": true }, - "responses" : { - "201" : { - "description" : "A Successful Endeavor", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/Boolean" + "responses": { + "201": { + "description": "A Successful Endeavor", + "content": { + "application/json": { + "schema": { + "type": "boolean" } } } } }, - "deprecated" : false + "deprecated": false } } }, - "components" : { - "schemas" : { - "Int" : { - "type" : "integer", - "format" : "int32" - }, - "Boolean" : { - "type" : "boolean" - } - }, - "securitySchemes" : { } + "components": { + "securitySchemes": {} }, - "security" : [ ], - "tags" : [ ] + "security": [], + "tags": [] } diff --git a/kompendium-core/src/test/resources/notarized_put.json b/kompendium-core/src/test/resources/notarized_put.json index 66abee055..cd7d2f17a 100644 --- a/kompendium-core/src/test/resources/notarized_put.json +++ b/kompendium-core/src/test/resources/notarized_put.json @@ -1,137 +1,129 @@ { - "openapi" : "3.0.3", - "info" : { - "title" : "Test API", - "version" : "1.33.7", - "description" : "An amazing, fully-ish 😉 generated API spec", - "termsOfService" : "https://example.com", - "contact" : { - "name" : "Homer Simpson", - "url" : "https://gph.is/1NPUDiM", - "email" : "chunkylover53@aol.com" + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" }, - "license" : { - "name" : "MIT", - "url" : "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" } }, - "servers" : [ { - "url" : "https://myawesomeapi.com", - "description" : "Production instance of my API" - }, { - "url" : "https://staging.myawesomeapi.com", - "description" : "Where the fun stuff happens" - } ], - "paths" : { - "/test" : { - "put" : { - "tags" : [ ], - "summary" : "Test put endpoint", - "description" : "Put your tests here!", - "parameters" : [ { - "name" : "a", - "in" : "path", - "schema" : { - "type" : "string" + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/test": { + "put": { + "tags": [], + "summary": "Test put endpoint", + "description": "Put your tests here!", + "parameters": [ + { + "name": "a", + "in": "path", + "schema": { + "type": "string" + }, + "required": true, + "deprecated": false }, - "required" : true, - "deprecated" : false - }, { - "name" : "aa", - "in" : "query", - "schema" : { - "type" : "integer", - "format" : "int32" - }, - "required" : true, - "deprecated" : false - } ], - "requestBody" : { - "description" : "A Test request", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/TestRequest" + { + "name": "aa", + "in": "query", + "schema": { + "format": "int32", + "type": "integer" + }, + "required": true, + "deprecated": false + } + ], + "requestBody": { + "description": "A Test request", + "content": { + "application/json": { + "schema": { + "properties": { + "aaa": { + "items": { + "format": "int64", + "type": "integer" + }, + "type": "array" + }, + "b": { + "format": "double", + "type": "number" + }, + "field_name": { + "properties": { + "nesty": { + "type": "string" + } + }, + "required": [ + "nesty" + ], + "type": "object" + } + }, + "required": [ + "fieldName", + "b", + "aaa" + ], + "type": "object" } } }, - "required" : false + "required": true }, - "responses" : { - "201" : { - "description" : "A Successful Endeavor", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/TestCreatedResponse" + "responses": { + "201": { + "description": "A Successful Endeavor", + "content": { + "application/json": { + "schema": { + "properties": { + "c": { + "type": "string" + }, + "id": { + "format": "int32", + "type": "integer" + } + }, + "required": [ + "id", + "c" + ], + "type": "object" } } } } }, - "deprecated" : false + "deprecated": false } } }, - "components" : { - "schemas" : { - "Long" : { - "type" : "integer", - "format" : "int64" - }, - "List-Long" : { - "type" : "array", - "items" : { - "$ref" : "#/components/schemas/Long" - } - }, - "Double" : { - "type" : "number", - "format" : "double" - }, - "String" : { - "type" : "string" - }, - "TestNested" : { - "type" : "object", - "properties" : { - "nesty" : { - "$ref" : "#/components/schemas/String" - } - } - }, - "TestRequest" : { - "type" : "object", - "properties" : { - "aaa" : { - "$ref" : "#/components/schemas/List-Long" - }, - "b" : { - "$ref" : "#/components/schemas/Double" - }, - "fieldName" : { - "$ref" : "#/components/schemas/TestNested" - } - } - }, - "Int" : { - "type" : "integer", - "format" : "int32" - }, - "TestCreatedResponse" : { - "type" : "object", - "properties" : { - "c" : { - "$ref" : "#/components/schemas/String" - }, - "id" : { - "$ref" : "#/components/schemas/Int" - } - } - } - }, - "securitySchemes" : { } + "components": { + "securitySchemes": {} }, - "security" : [ ], - "tags" : [ ] + "security": [], + "tags": [] } diff --git a/kompendium-core/src/test/resources/nullable_field.json b/kompendium-core/src/test/resources/nullable_field.json new file mode 100644 index 000000000..4874dd182 --- /dev/null +++ b/kompendium-core/src/test/resources/nullable_field.json @@ -0,0 +1,84 @@ +{ + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" + }, + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + } + }, + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/test/required_param": { + "post": { + "tags": [], + "summary": "default param", + "description": "Cool stuff", + "parameters": [], + "requestBody": { + "description": "cool", + "content": { + "application/json": { + "schema": { + "properties": { + "a": { + "type": "string", + "nullable": true + } + }, + "required": [ + "a" + ], + "type": "object" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "A successful endeavor", + "content": { + "application/json": { + "schema": { + "properties": { + "c": { + "type": "string" + } + }, + "required": [ + "c" + ], + "type": "object" + } + } + } + } + }, + "deprecated": false + } + } + }, + "components": { + "securitySchemes": {} + }, + "security": [], + "tags": [] +} diff --git a/kompendium-core/src/test/resources/override_parameter_name.json b/kompendium-core/src/test/resources/override_parameter_name.json index 52f272588..ed8fe5413 100644 --- a/kompendium-core/src/test/resources/override_parameter_name.json +++ b/kompendium-core/src/test/resources/override_parameter_name.json @@ -1,74 +1,74 @@ { - "openapi" : "3.0.3", - "info" : { - "title" : "Test API", - "version" : "1.33.7", - "description" : "An amazing, fully-ish 😉 generated API spec", - "termsOfService" : "https://example.com", - "contact" : { - "name" : "Homer Simpson", - "url" : "https://gph.is/1NPUDiM", - "email" : "chunkylover53@aol.com" + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" }, - "license" : { - "name" : "MIT", - "url" : "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" } }, - "servers" : [ { - "url" : "https://myawesomeapi.com", - "description" : "Production instance of my API" - }, { - "url" : "https://staging.myawesomeapi.com", - "description" : "Where the fun stuff happens" - } ], - "paths" : { - "/test/with_header" : { - "get" : { - "tags" : [ ], - "summary" : "testing header stuffs", - "description" : "Good for many things", - "parameters" : [ { - "name" : "X-UserEmail", - "in" : "header", - "schema" : { - "type" : "string" - }, - "required" : true, - "deprecated" : false - } ], - "responses" : { - "200" : { - "description" : "A successful endeavor", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/TestResponse" + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/test/with_header": { + "get": { + "tags": [], + "summary": "testing header stuffs", + "description": "Good for many things", + "parameters": [ + { + "name": "X-UserEmail", + "in": "header", + "schema": { + "type": "string" + }, + "required": true, + "deprecated": false + } + ], + "responses": { + "200": { + "description": "A successful endeavor", + "content": { + "application/json": { + "schema": { + "properties": { + "c": { + "type": "string" + } + }, + "required": [ + "c" + ], + "type": "object" } } } } }, - "deprecated" : false + "deprecated": false } } }, - "components" : { - "schemas" : { - "String" : { - "type" : "string" - }, - "TestResponse" : { - "type" : "object", - "properties" : { - "c" : { - "$ref" : "#/components/schemas/String" - } - } - } - }, - "securitySchemes" : { } + "components": { + "securitySchemes": {} }, - "security" : [ ], - "tags" : [ ] + "security": [], + "tags": [] } diff --git a/kompendium-core/src/test/resources/path_parser.json b/kompendium-core/src/test/resources/path_parser.json index dc10a6dc0..7d1a3fabf 100644 --- a/kompendium-core/src/test/resources/path_parser.json +++ b/kompendium-core/src/test/resources/path_parser.json @@ -1,87 +1,84 @@ { - "openapi" : "3.0.3", - "info" : { - "title" : "Test API", - "version" : "1.33.7", - "description" : "An amazing, fully-ish 😉 generated API spec", - "termsOfService" : "https://example.com", - "contact" : { - "name" : "Homer Simpson", - "url" : "https://gph.is/1NPUDiM", - "email" : "chunkylover53@aol.com" + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" }, - "license" : { - "name" : "MIT", - "url" : "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" } }, - "servers" : [ { - "url" : "https://myawesomeapi.com", - "description" : "Production instance of my API" - }, { - "url" : "https://staging.myawesomeapi.com", - "description" : "Where the fun stuff happens" - } ], - "paths" : { - "/this/is/a/complex/path/with/an/{id}" : { - "get" : { - "tags" : [ ], - "summary" : "Another get test", - "description" : "testing more", - "parameters" : [ { - "name" : "a", - "in" : "path", - "schema" : { - "type" : "string" + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/this/is/a/complex/path/with/an/{id}": { + "get": { + "tags": [], + "summary": "Another get test", + "description": "testing more", + "parameters": [ + { + "name": "a", + "in": "path", + "schema": { + "type": "string" + }, + "required": true, + "deprecated": false }, - "required" : true, - "deprecated" : false - }, { - "name" : "aa", - "in" : "query", - "schema" : { - "type" : "integer", - "format" : "int32" - }, - "required" : true, - "deprecated" : false - } ], - "responses" : { - "200" : { - "description" : "A Successful Endeavor", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/TestResponse" + { + "name": "aa", + "in": "query", + "schema": { + "format": "int32", + "type": "integer" + }, + "required": true, + "deprecated": false + } + ], + "responses": { + "200": { + "description": "A Successful Endeavor", + "content": { + "application/json": { + "schema": { + "properties": { + "c": { + "type": "string" + } + }, + "required": [ + "c" + ], + "type": "object" } } } } }, - "deprecated" : false + "deprecated": false } } }, - "components" : { - "schemas" : { - "String" : { - "type" : "string" - }, - "TestResponse" : { - "type" : "object", - "properties" : { - "c" : { - "$ref" : "#/components/schemas/String" - } - } - }, - "Int" : { - "type" : "integer", - "format" : "int32" - } - }, - "securitySchemes" : { } + "components": { + "securitySchemes": {} }, - "security" : [ ], - "tags" : [ ] + "security": [], + "tags": [] } diff --git a/kompendium-core/src/test/resources/polymorphic_error_status_codes.json b/kompendium-core/src/test/resources/polymorphic_error_status_codes.json new file mode 100644 index 000000000..76f5b0241 --- /dev/null +++ b/kompendium-core/src/test/resources/polymorphic_error_status_codes.json @@ -0,0 +1,122 @@ +{ + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" + }, + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + } + }, + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/test": { + "get": { + "tags": [], + "summary": "Another get test", + "description": "testing more", + "parameters": [ + { + "name": "a", + "in": "path", + "schema": { + "type": "string" + }, + "required": true, + "deprecated": false + }, + { + "name": "aa", + "in": "query", + "schema": { + "format": "int32", + "type": "integer" + }, + "required": true, + "deprecated": false + } + ], + "responses": { + "200": { + "description": "A Successful Endeavor", + "content": { + "application/json": { + "schema": { + "properties": { + "c": { + "type": "string" + } + }, + "required": [ + "c" + ], + "type": "object" + } + } + } + }, + "501": { + "description": "The Gibbits are ANGRY", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "properties": { + "a": { + "type": "string" + } + }, + "required": [ + "a" + ], + "type": "object" + }, + { + "properties": { + "b": { + "type": "string" + }, + "c": { + "format": "int32", + "type": "integer" + } + }, + "required": [ + "b", + "c" + ], + "type": "object" + } + ] + } + } + } + } + }, + "deprecated": false + } + } + }, + "components": { + "securitySchemes": {} + }, + "security": [], + "tags": [] +} diff --git a/kompendium-core/src/test/resources/polymorphic_list_response.json b/kompendium-core/src/test/resources/polymorphic_list_response.json index 62feaafc5..63764f249 100644 --- a/kompendium-core/src/test/resources/polymorphic_list_response.json +++ b/kompendium-core/src/test/resources/polymorphic_list_response.json @@ -1,91 +1,87 @@ { - "openapi" : "3.0.3", - "info" : { - "title" : "Test API", - "version" : "1.33.7", - "description" : "An amazing, fully-ish 😉 generated API spec", - "termsOfService" : "https://example.com", - "contact" : { - "name" : "Homer Simpson", - "url" : "https://gph.is/1NPUDiM", - "email" : "chunkylover53@aol.com" + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" }, - "license" : { - "name" : "MIT", - "url" : "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" } }, - "servers" : [ { - "url" : "https://myawesomeapi.com", - "description" : "Production instance of my API" - }, { - "url" : "https://staging.myawesomeapi.com", - "description" : "Where the fun stuff happens" - } ], - "paths" : { - "/test/polymorphiclist" : { - "get" : { - "tags" : [ ], - "summary" : "Oh so many gibbits", - "description" : "Polymorphic list response", - "parameters" : [ ], - "responses" : { - "200" : { - "description" : "A successful endeavor", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/List-FlibbityGibbit" + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/test/polymorphiclist": { + "get": { + "tags": [], + "summary": "Oh so many gibbits", + "description": "Polymorphic list response", + "parameters": [], + "responses": { + "200": { + "description": "A successful endeavor", + "content": { + "application/json": { + "schema": { + "items": { + "anyOf": [ + { + "properties": { + "a": { + "type": "string" + } + }, + "required": [ + "a" + ], + "type": "object" + }, + { + "properties": { + "b": { + "type": "string" + }, + "c": { + "format": "int32", + "type": "integer" + } + }, + "required": [ + "b", + "c" + ], + "type": "object" + } + ] + }, + "type": "array" } } } } }, - "deprecated" : false + "deprecated": false } } }, - "components" : { - "schemas" : { - "String" : { - "type" : "string" - }, - "SimpleGibbit" : { - "type" : "object", - "properties" : { - "a" : { - "$ref" : "#/components/schemas/String" - } - } - }, - "Int" : { - "type" : "integer", - "format" : "int32" - }, - "ComplexGibbit" : { - "type" : "object", - "properties" : { - "b" : { - "$ref" : "#/components/schemas/String" - }, - "c" : { - "$ref" : "#/components/schemas/Int" - } - } - }, - "List-FlibbityGibbit" : { - "type" : "array", - "items" : { - "anyOf" : [ { - "$ref" : "#/components/schemas/SimpleGibbit" - }, { - "$ref" : "#/components/schemas/ComplexGibbit" - } ] - } - } - }, - "securitySchemes" : { } + "components": { + "securitySchemes": {} }, - "security" : [ ], - "tags" : [ ] + "security": [], + "tags": [] } diff --git a/kompendium-core/src/test/resources/polymorphic_map_response.json b/kompendium-core/src/test/resources/polymorphic_map_response.json index 88c4dfb03..cb0e80c35 100644 --- a/kompendium-core/src/test/resources/polymorphic_map_response.json +++ b/kompendium-core/src/test/resources/polymorphic_map_response.json @@ -1,91 +1,87 @@ { - "openapi" : "3.0.3", - "info" : { - "title" : "Test API", - "version" : "1.33.7", - "description" : "An amazing, fully-ish 😉 generated API spec", - "termsOfService" : "https://example.com", - "contact" : { - "name" : "Homer Simpson", - "url" : "https://gph.is/1NPUDiM", - "email" : "chunkylover53@aol.com" + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" }, - "license" : { - "name" : "MIT", - "url" : "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" } }, - "servers" : [ { - "url" : "https://myawesomeapi.com", - "description" : "Production instance of my API" - }, { - "url" : "https://staging.myawesomeapi.com", - "description" : "Where the fun stuff happens" - } ], - "paths" : { - "/test/polymorphicmap" : { - "get" : { - "tags" : [ ], - "summary" : "By gawd that's a lot of gibbits", - "description" : "Polymorphic list response", - "parameters" : [ ], - "responses" : { - "200" : { - "description" : "A successful endeavor", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/Map-String-FlibbityGibbit" + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/test/polymorphicmap": { + "get": { + "tags": [], + "summary": "By gawd that's a lot of gibbits", + "description": "Polymorphic list response", + "parameters": [], + "responses": { + "200": { + "description": "A successful endeavor", + "content": { + "application/json": { + "schema": { + "additionalProperties": { + "anyOf": [ + { + "properties": { + "a": { + "type": "string" + } + }, + "required": [ + "a" + ], + "type": "object" + }, + { + "properties": { + "b": { + "type": "string" + }, + "c": { + "format": "int32", + "type": "integer" + } + }, + "required": [ + "b", + "c" + ], + "type": "object" + } + ] + }, + "type": "object" } } } } }, - "deprecated" : false + "deprecated": false } } }, - "components" : { - "schemas" : { - "String" : { - "type" : "string" - }, - "SimpleGibbit" : { - "type" : "object", - "properties" : { - "a" : { - "$ref" : "#/components/schemas/String" - } - } - }, - "Int" : { - "type" : "integer", - "format" : "int32" - }, - "ComplexGibbit" : { - "type" : "object", - "properties" : { - "b" : { - "$ref" : "#/components/schemas/String" - }, - "c" : { - "$ref" : "#/components/schemas/Int" - } - } - }, - "Map-String-FlibbityGibbit" : { - "type" : "object", - "additionalProperties" : { - "anyOf" : [ { - "$ref" : "#/components/schemas/SimpleGibbit" - }, { - "$ref" : "#/components/schemas/ComplexGibbit" - } ] - } - } - }, - "securitySchemes" : { } + "components": { + "securitySchemes": {} }, - "security" : [ ], - "tags" : [ ] + "security": [], + "tags": [] } diff --git a/kompendium-core/src/test/resources/polymorphic_response.json b/kompendium-core/src/test/resources/polymorphic_response.json index 3cf471de8..a5c9cb0a6 100644 --- a/kompendium-core/src/test/resources/polymorphic_response.json +++ b/kompendium-core/src/test/resources/polymorphic_response.json @@ -1,85 +1,84 @@ { - "openapi" : "3.0.3", - "info" : { - "title" : "Test API", - "version" : "1.33.7", - "description" : "An amazing, fully-ish 😉 generated API spec", - "termsOfService" : "https://example.com", - "contact" : { - "name" : "Homer Simpson", - "url" : "https://gph.is/1NPUDiM", - "email" : "chunkylover53@aol.com" + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" }, - "license" : { - "name" : "MIT", - "url" : "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" } }, - "servers" : [ { - "url" : "https://myawesomeapi.com", - "description" : "Production instance of my API" - }, { - "url" : "https://staging.myawesomeapi.com", - "description" : "Where the fun stuff happens" - } ], - "paths" : { - "/test/polymorphic" : { - "get" : { - "tags" : [ ], - "summary" : "All the gibbits", - "description" : "Polymorphic response", - "parameters" : [ ], - "responses" : { - "200" : { - "description" : "A successful endeavor", - "content" : { - "application/json" : { - "schema" : { - "anyOf" : [ { - "$ref" : "#/components/schemas/SimpleGibbit" - }, { - "$ref" : "#/components/schemas/ComplexGibbit" - } ] + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/test/polymorphic": { + "get": { + "tags": [], + "summary": "All the gibbits", + "description": "Polymorphic response", + "parameters": [], + "responses": { + "200": { + "description": "A successful endeavor", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "properties": { + "a": { + "type": "string" + } + }, + "required": [ + "a" + ], + "type": "object" + }, + { + "properties": { + "b": { + "type": "string" + }, + "c": { + "format": "int32", + "type": "integer" + } + }, + "required": [ + "b", + "c" + ], + "type": "object" + } + ] } } } } }, - "deprecated" : false + "deprecated": false } } }, - "components" : { - "schemas" : { - "String" : { - "type" : "string" - }, - "SimpleGibbit" : { - "type" : "object", - "properties" : { - "a" : { - "$ref" : "#/components/schemas/String" - } - } - }, - "Int" : { - "type" : "integer", - "format" : "int32" - }, - "ComplexGibbit" : { - "type" : "object", - "properties" : { - "b" : { - "$ref" : "#/components/schemas/String" - }, - "c" : { - "$ref" : "#/components/schemas/Int" - } - } - } - }, - "securitySchemes" : { } + "components": { + "securitySchemes": {} }, - "security" : [ ], - "tags" : [ ] + "security": [], + "tags": [] } diff --git a/kompendium-core/src/test/resources/polymorphic_response_with_generics.json b/kompendium-core/src/test/resources/polymorphic_response_with_generics.json index a0b8e53f5..7b7302e4e 100644 --- a/kompendium-core/src/test/resources/polymorphic_response_with_generics.json +++ b/kompendium-core/src/test/resources/polymorphic_response_with_generics.json @@ -1,89 +1,99 @@ { - "openapi" : "3.0.3", - "info" : { - "title" : "Test API", - "version" : "1.33.7", - "description" : "An amazing, fully-ish 😉 generated API spec", - "termsOfService" : "https://example.com", - "contact" : { - "name" : "Homer Simpson", - "url" : "https://gph.is/1NPUDiM", - "email" : "chunkylover53@aol.com" + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" }, - "license" : { - "name" : "MIT", - "url" : "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" } }, - "servers" : [ { - "url" : "https://myawesomeapi.com", - "description" : "Production instance of my API" - }, { - "url" : "https://staging.myawesomeapi.com", - "description" : "Where the fun stuff happens" - } ], - "paths" : { - "/test/polymorphic" : { - "get" : { - "tags" : [ ], - "summary" : "More flibbity", - "description" : "Polymorphic with generics", - "parameters" : [ ], - "responses" : { - "200" : { - "description" : "A successful endeavor", - "content" : { - "application/json" : { - "schema" : { - "anyOf" : [ { - "$ref" : "#/components/schemas/Gibbity-TestNested" - }, { - "$ref" : "#/components/schemas/Bibbity-TestNested" - } ] + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/test/polymorphic": { + "get": { + "tags": [], + "summary": "More flibbity", + "description": "Polymorphic with generics", + "parameters": [], + "responses": { + "200": { + "description": "A successful endeavor", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "properties": { + "a": { + "properties": { + "nesty": { + "type": "string" + } + }, + "required": [ + "nesty" + ], + "type": "object" + } + }, + "required": [ + "a" + ], + "type": "object" + }, + { + "properties": { + "b": { + "type": "string" + }, + "f": { + "properties": { + "nesty": { + "type": "string" + } + }, + "required": [ + "nesty" + ], + "type": "object" + } + }, + "required": [ + "b", + "f" + ], + "type": "object" + } + ] } } } } }, - "deprecated" : false + "deprecated": false } } }, - "components" : { - "schemas" : { - "String" : { - "type" : "string" - }, - "TestNested" : { - "type" : "object", - "properties" : { - "nesty" : { - "$ref" : "#/components/schemas/String" - } - } - }, - "Gibbity-TestNested" : { - "type" : "object", - "properties" : { - "a" : { - "$ref" : "#/components/schemas/TestNested" - } - } - }, - "Bibbity-TestNested" : { - "type" : "object", - "properties" : { - "b" : { - "$ref" : "#/components/schemas/String" - }, - "f" : { - "$ref" : "#/components/schemas/TestNested" - } - } - } - }, - "securitySchemes" : { } + "components": { + "securitySchemes": {} }, - "security" : [ ], - "tags" : [ ] + "security": [], + "tags": [] } diff --git a/kompendium-core/src/test/resources/query_with_default_parameter.json b/kompendium-core/src/test/resources/query_with_default_parameter.json index 341cddbbf..3e1dc3754 100644 --- a/kompendium-core/src/test/resources/query_with_default_parameter.json +++ b/kompendium-core/src/test/resources/query_with_default_parameter.json @@ -1,87 +1,95 @@ { - "openapi" : "3.0.3", - "info" : { - "title" : "Test API", - "version" : "1.33.7", - "description" : "An amazing, fully-ish 😉 generated API spec", - "termsOfService" : "https://example.com", - "contact" : { - "name" : "Homer Simpson", - "url" : "https://gph.is/1NPUDiM", - "email" : "chunkylover53@aol.com" + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" }, - "license" : { - "name" : "MIT", - "url" : "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" } }, - "servers" : [ { - "url" : "https://myawesomeapi.com", - "description" : "Production instance of my API" - }, { - "url" : "https://staging.myawesomeapi.com", - "description" : "Where the fun stuff happens" - } ], - "paths" : { - "/test" : { - "get" : { - "tags" : [ ], - "summary" : "Testing Default Params", - "description" : "Should have a default parameter value", - "parameters" : [ { - "name" : "a", - "in" : "query", - "schema" : { - "default" : 100, - "type" : "integer", - "format" : "int32" - }, - "required" : true, - "deprecated" : false - }, { - "name" : "b", - "in" : "path", - "schema" : { - "type" : "string" - }, - "required" : false, - "deprecated" : false - }, { - "name" : "c", - "in" : "path", - "schema" : { - "type" : "boolean" - }, - "required" : true, - "deprecated" : false - } ], - "deprecated" : false - } + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" } - }, - "components" : { - "schemas" : { - "String" : { - "type" : "string" - }, - "TestResponse" : { - "type" : "object", - "properties" : { - "c" : { - "$ref" : "#/components/schemas/String" + ], + "paths": { + "/test": { + "get": { + "tags": [], + "summary": "Testing Default Params", + "description": "Should have a default parameter value", + "parameters": [ + { + "name": "a", + "in": "query", + "schema": { + "format": "int32", + "type": "integer", + "default": 100 + }, + "required": false, + "deprecated": false + }, + { + "name": "b", + "in": "path", + "schema": { + "type": "string", + "nullable": true + }, + "required": false, + "deprecated": false + }, + { + "name": "c", + "in": "path", + "schema": { + "type": "boolean" + }, + "required": true, + "deprecated": false } - } - }, - "Int" : { - "type" : "integer", - "format" : "int32" - }, - "Boolean" : { - "type" : "boolean" + ], + "responses": { + "200": { + "description": "A good response", + "content": { + "application/json": { + "schema": { + "properties": { + "c": { + "type": "string" + } + }, + "required": [ + "c" + ], + "type": "object" + } + } + } + } + }, + "deprecated": false } - }, - "securitySchemes" : { } + } }, - "security" : [ ], - "tags" : [ ] + "components": { + "securitySchemes": {} + }, + "security": [], + "tags": [] } diff --git a/kompendium-core/src/test/resources/redoc.html b/kompendium-core/src/test/resources/redoc.html index 21d16e55a..5b377a087 100644 --- a/kompendium-core/src/test/resources/redoc.html +++ b/kompendium-core/src/test/resources/redoc.html @@ -1,7 +1,7 @@ - Test API + Docs diff --git a/kompendium-core/src/test/resources/regex_string.json b/kompendium-core/src/test/resources/regex_string.json new file mode 100644 index 000000000..41bcd3396 --- /dev/null +++ b/kompendium-core/src/test/resources/regex_string.json @@ -0,0 +1,65 @@ +{ + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" + }, + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + } + }, + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/test/required_param": { + "get": { + "tags": [], + "summary": "required param", + "description": "Cool stuff", + "parameters": [], + "responses": { + "200": { + "description": "A successful endeavor", + "content": { + "application/json": { + "schema": { + "properties": { + "a": { + "type": "string", + "pattern": "^\\d{3}-\\d{2}-\\d{4}$" + } + }, + "required": [ + "a" + ], + "type": "object" + } + } + } + } + }, + "deprecated": false + } + } + }, + "components": { + "securitySchemes": {} + }, + "security": [], + "tags": [] +} diff --git a/kompendium-core/src/test/resources/required_param.json b/kompendium-core/src/test/resources/required_param.json new file mode 100644 index 000000000..3ca03d47e --- /dev/null +++ b/kompendium-core/src/test/resources/required_param.json @@ -0,0 +1,74 @@ +{ + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" + }, + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + } + }, + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/test/required_param": { + "get": { + "tags": [], + "summary": "required param", + "description": "Cool stuff", + "parameters": [ + { + "name": "a", + "in": "query", + "schema": { + "type": "string" + }, + "required": true, + "deprecated": false + } + ], + "responses": { + "200": { + "description": "A successful endeavor", + "content": { + "application/json": { + "schema": { + "properties": { + "c": { + "type": "string" + } + }, + "required": [ + "c" + ], + "type": "object" + } + } + } + } + }, + "deprecated": false + } + } + }, + "components": { + "securitySchemes": {} + }, + "security": [], + "tags": [] +} diff --git a/kompendium-core/src/test/resources/response_list.json b/kompendium-core/src/test/resources/response_list.json index f8fdbc7e4..233be4722 100644 --- a/kompendium-core/src/test/resources/response_list.json +++ b/kompendium-core/src/test/resources/response_list.json @@ -1,93 +1,87 @@ { - "openapi" : "3.0.3", - "info" : { - "title" : "Test API", - "version" : "1.33.7", - "description" : "An amazing, fully-ish 😉 generated API spec", - "termsOfService" : "https://example.com", - "contact" : { - "name" : "Homer Simpson", - "url" : "https://gph.is/1NPUDiM", - "email" : "chunkylover53@aol.com" + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" }, - "license" : { - "name" : "MIT", - "url" : "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" } }, - "servers" : [ { - "url" : "https://myawesomeapi.com", - "description" : "Production instance of my API" - }, { - "url" : "https://staging.myawesomeapi.com", - "description" : "Where the fun stuff happens" - } ], - "paths" : { - "/test" : { - "get" : { - "tags" : [ ], - "summary" : "Another get test", - "description" : "testing more", - "parameters" : [ { - "name" : "a", - "in" : "path", - "schema" : { - "type" : "string" + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/test": { + "get": { + "tags": [], + "summary": "Another get test", + "description": "testing more", + "parameters": [ + { + "name": "a", + "in": "path", + "schema": { + "type": "string" + }, + "required": true, + "deprecated": false }, - "required" : true, - "deprecated" : false - }, { - "name" : "aa", - "in" : "query", - "schema" : { - "type" : "integer", - "format" : "int32" - }, - "required" : true, - "deprecated" : false - } ], - "responses" : { - "200" : { - "description" : "A Successful List-y Endeavor", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/List-TestResponse" + { + "name": "aa", + "in": "query", + "schema": { + "format": "int32", + "type": "integer" + }, + "required": true, + "deprecated": false + } + ], + "responses": { + "200": { + "description": "A Successful List-y Endeavor", + "content": { + "application/json": { + "schema": { + "items": { + "properties": { + "c": { + "type": "string" + } + }, + "required": [ + "c" + ], + "type": "object" + }, + "type": "array" } } } } }, - "deprecated" : false + "deprecated": false } } }, - "components" : { - "schemas" : { - "String" : { - "type" : "string" - }, - "TestResponse" : { - "type" : "object", - "properties" : { - "c" : { - "$ref" : "#/components/schemas/String" - } - } - }, - "List-TestResponse" : { - "type" : "array", - "items" : { - "$ref" : "#/components/schemas/TestResponse" - } - }, - "Int" : { - "type" : "integer", - "format" : "int32" - } - }, - "securitySchemes" : { } + "components": { + "securitySchemes": {} }, - "security" : [ ], - "tags" : [ ] + "security": [], + "tags": [] } diff --git a/kompendium-core/src/test/resources/root_route.json b/kompendium-core/src/test/resources/root_route.json index b21bdb142..d3532a565 100644 --- a/kompendium-core/src/test/resources/root_route.json +++ b/kompendium-core/src/test/resources/root_route.json @@ -1,87 +1,84 @@ { - "openapi" : "3.0.3", - "info" : { - "title" : "Test API", - "version" : "1.33.7", - "description" : "An amazing, fully-ish 😉 generated API spec", - "termsOfService" : "https://example.com", - "contact" : { - "name" : "Homer Simpson", - "url" : "https://gph.is/1NPUDiM", - "email" : "chunkylover53@aol.com" + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" }, - "license" : { - "name" : "MIT", - "url" : "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" } }, - "servers" : [ { - "url" : "https://myawesomeapi.com", - "description" : "Production instance of my API" - }, { - "url" : "https://staging.myawesomeapi.com", - "description" : "Where the fun stuff happens" - } ], - "paths" : { - "/" : { - "get" : { - "tags" : [ ], - "summary" : "Another get test", - "description" : "testing more", - "parameters" : [ { - "name" : "a", - "in" : "path", - "schema" : { - "type" : "string" + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/": { + "get": { + "tags": [], + "summary": "Another get test", + "description": "testing more", + "parameters": [ + { + "name": "a", + "in": "path", + "schema": { + "type": "string" + }, + "required": true, + "deprecated": false }, - "required" : true, - "deprecated" : false - }, { - "name" : "aa", - "in" : "query", - "schema" : { - "type" : "integer", - "format" : "int32" - }, - "required" : true, - "deprecated" : false - } ], - "responses" : { - "200" : { - "description" : "A Successful Endeavor", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/TestResponse" + { + "name": "aa", + "in": "query", + "schema": { + "format": "int32", + "type": "integer" + }, + "required": true, + "deprecated": false + } + ], + "responses": { + "200": { + "description": "A Successful Endeavor", + "content": { + "application/json": { + "schema": { + "properties": { + "c": { + "type": "string" + } + }, + "required": [ + "c" + ], + "type": "object" } } } } }, - "deprecated" : false + "deprecated": false } } }, - "components" : { - "schemas" : { - "String" : { - "type" : "string" - }, - "TestResponse" : { - "type" : "object", - "properties" : { - "c" : { - "$ref" : "#/components/schemas/String" - } - } - }, - "Int" : { - "type" : "integer", - "format" : "int32" - } - }, - "securitySchemes" : { } + "components": { + "securitySchemes": {} }, - "security" : [ ], - "tags" : [ ] + "security": [], + "tags": [] } diff --git a/kompendium-core/src/test/resources/sealed_interface_response.json b/kompendium-core/src/test/resources/sealed_interface_response.json index 3a6f375b2..29fd80ed3 100644 --- a/kompendium-core/src/test/resources/sealed_interface_response.json +++ b/kompendium-core/src/test/resources/sealed_interface_response.json @@ -1,83 +1,81 @@ { - "openapi" : "3.0.3", - "info" : { - "title" : "Test API", - "version" : "1.33.7", - "description" : "An amazing, fully-ish 😉 generated API spec", - "termsOfService" : "https://example.com", - "contact" : { - "name" : "Homer Simpson", - "url" : "https://gph.is/1NPUDiM", - "email" : "chunkylover53@aol.com" + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" }, - "license" : { - "name" : "MIT", - "url" : "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" } }, - "servers" : [ { - "url" : "https://myawesomeapi.com", - "description" : "Production instance of my API" - }, { - "url" : "https://staging.myawesomeapi.com", - "description" : "Where the fun stuff happens" - } ], - "paths" : { - "/test/polymorphicmap" : { - "get" : { - "tags" : [ ], - "summary" : "Come on and slam", - "description" : "and welcome to the jam", - "parameters" : [ ], - "responses" : { - "200" : { - "description" : "A successful endeavor", - "content" : { - "application/json" : { - "schema" : { - "anyOf" : [ { - "$ref" : "#/components/schemas/OneJamma" - }, { - "$ref" : "#/components/schemas/AnothaJamma" - } ] + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/test/polymorphicmap": { + "get": { + "tags": [], + "summary": "Come on and slam", + "description": "and welcome to the jam", + "parameters": [], + "responses": { + "200": { + "description": "A successful endeavor", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "properties": { + "a": { + "format": "int32", + "type": "integer" + } + }, + "required": [ + "a" + ], + "type": "object" + }, + { + "properties": { + "b": { + "format": "float", + "type": "number" + } + }, + "required": [ + "b" + ], + "type": "object" + } + ] } } } } }, - "deprecated" : false + "deprecated": false } } }, - "components" : { - "schemas" : { - "Int" : { - "type" : "integer", - "format" : "int32" - }, - "OneJamma" : { - "type" : "object", - "properties" : { - "a" : { - "$ref" : "#/components/schemas/Int" - } - } - }, - "Float" : { - "type" : "number", - "format" : "float" - }, - "AnothaJamma" : { - "type" : "object", - "properties" : { - "b" : { - "$ref" : "#/components/schemas/Float" - } - } - } - }, - "securitySchemes" : { } + "components": { + "securitySchemes": {} }, - "security" : [ ], - "tags" : [ ] + "security": [], + "tags": [] } diff --git a/kompendium-core/src/test/resources/trailing_slash.json b/kompendium-core/src/test/resources/trailing_slash.json index c5395bfd3..b3944e861 100644 --- a/kompendium-core/src/test/resources/trailing_slash.json +++ b/kompendium-core/src/test/resources/trailing_slash.json @@ -1,87 +1,84 @@ { - "openapi" : "3.0.3", - "info" : { - "title" : "Test API", - "version" : "1.33.7", - "description" : "An amazing, fully-ish 😉 generated API spec", - "termsOfService" : "https://example.com", - "contact" : { - "name" : "Homer Simpson", - "url" : "https://gph.is/1NPUDiM", - "email" : "chunkylover53@aol.com" + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" }, - "license" : { - "name" : "MIT", - "url" : "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" } }, - "servers" : [ { - "url" : "https://myawesomeapi.com", - "description" : "Production instance of my API" - }, { - "url" : "https://staging.myawesomeapi.com", - "description" : "Where the fun stuff happens" - } ], - "paths" : { - "/test/" : { - "get" : { - "tags" : [ ], - "summary" : "Another get test", - "description" : "testing more", - "parameters" : [ { - "name" : "a", - "in" : "path", - "schema" : { - "type" : "string" + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/test/": { + "get": { + "tags": [], + "summary": "Another get test", + "description": "testing more", + "parameters": [ + { + "name": "a", + "in": "path", + "schema": { + "type": "string" + }, + "required": true, + "deprecated": false }, - "required" : true, - "deprecated" : false - }, { - "name" : "aa", - "in" : "query", - "schema" : { - "type" : "integer", - "format" : "int32" - }, - "required" : true, - "deprecated" : false - } ], - "responses" : { - "200" : { - "description" : "A Successful Endeavor", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/TestResponse" + { + "name": "aa", + "in": "query", + "schema": { + "format": "int32", + "type": "integer" + }, + "required": true, + "deprecated": false + } + ], + "responses": { + "200": { + "description": "A Successful Endeavor", + "content": { + "application/json": { + "schema": { + "properties": { + "c": { + "type": "string" + } + }, + "required": [ + "c" + ], + "type": "object" } } } } }, - "deprecated" : false + "deprecated": false } } }, - "components" : { - "schemas" : { - "String" : { - "type" : "string" - }, - "TestResponse" : { - "type" : "object", - "properties" : { - "c" : { - "$ref" : "#/components/schemas/String" - } - } - }, - "Int" : { - "type" : "integer", - "format" : "int32" - } - }, - "securitySchemes" : { } + "components": { + "securitySchemes": {} }, - "security" : [ ], - "tags" : [ ] + "security": [], + "tags": [] } diff --git a/kompendium-core/src/test/resources/undeclared_field.json b/kompendium-core/src/test/resources/undeclared_field.json index 65c24e1bf..7c5ca3538 100644 --- a/kompendium-core/src/test/resources/undeclared_field.json +++ b/kompendium-core/src/test/resources/undeclared_field.json @@ -1,73 +1,71 @@ { - "openapi" : "3.0.3", - "info" : { - "title" : "Test API", - "version" : "1.33.7", - "description" : "An amazing, fully-ish 😉 generated API spec", - "termsOfService" : "https://example.com", - "contact" : { - "name" : "Homer Simpson", - "url" : "https://gph.is/1NPUDiM", - "email" : "chunkylover53@aol.com" + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" }, - "license" : { - "name" : "MIT", - "url" : "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" } }, - "servers" : [ { - "url" : "https://myawesomeapi.com", - "description" : "Production instance of my API" - }, { - "url" : "https://staging.myawesomeapi.com", - "description" : "Where the fun stuff happens" - } ], - "paths" : { - "/test/polymorphic" : { - "get" : { - "tags" : [ ], - "summary" : "spooky class", - "description" : "break this glass in scenario of emergency", - "parameters" : [ ], - "responses" : { - "200" : { - "description" : "A successful endeavor", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/Mysterious" + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/test/polymorphic": { + "get": { + "tags": [], + "summary": "spooky class", + "description": "break this glass in scenario of emergency", + "parameters": [], + "responses": { + "200": { + "description": "A successful endeavor", + "content": { + "application/json": { + "schema": { + "properties": { + "nowYouSeeMe": { + "type": "string" + }, + "nowYouDont": { + "enum": [ + "HAHA", + "HOHO" + ], + "type": "string" + } + }, + "required": [ + "nowYouSeeMe" + ], + "type": "object" } } } } }, - "deprecated" : false + "deprecated": false } } }, - "components" : { - "schemas" : { - "String" : { - "type" : "string" - }, - "Hehe" : { - "type" : "string", - "enum" : [ "HAHA", "HOHO" ] - }, - "Mysterious" : { - "type" : "object", - "properties" : { - "nowYouSeeMe" : { - "$ref" : "#/components/schemas/String" - }, - "nowYouDont" : { - "$ref" : "#/components/schemas/Hehe" - } - } - } - }, - "securitySchemes" : { } + "components": { + "securitySchemes": {} }, - "security" : [ ], - "tags" : [ ] + "security": [], + "tags": [] } diff --git a/kompendium-core/src/test/resources/unique_array.json b/kompendium-core/src/test/resources/unique_array.json new file mode 100644 index 000000000..64c7aaacd --- /dev/null +++ b/kompendium-core/src/test/resources/unique_array.json @@ -0,0 +1,69 @@ +{ + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" + }, + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + } + }, + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/test/required_param": { + "get": { + "tags": [], + "summary": "required param", + "description": "Cool stuff", + "parameters": [], + "responses": { + "200": { + "description": "A successful endeavor", + "content": { + "application/json": { + "schema": { + "properties": { + "a": { + "items": { + "format": "int32", + "type": "integer" + }, + "uniqueItems": true, + "type": "array" + } + }, + "required": [ + "a" + ], + "type": "object" + } + } + } + } + }, + "deprecated": false + } + } + }, + "components": { + "securitySchemes": {} + }, + "security": [], + "tags": [] +} diff --git a/kompendium-core/src/testFixtures/kotlin/io/bkbn/kompendium/core/fixtures/TestHelpers.kt b/kompendium-core/src/testFixtures/kotlin/io/bkbn/kompendium/core/fixtures/TestHelpers.kt new file mode 100644 index 000000000..ba4b9425d --- /dev/null +++ b/kompendium-core/src/testFixtures/kotlin/io/bkbn/kompendium/core/fixtures/TestHelpers.kt @@ -0,0 +1,112 @@ +package io.bkbn.kompendium.core.fixtures + +import io.kotest.assertions.json.shouldEqualJson +import io.kotest.assertions.ktor.shouldHaveStatus +import io.kotest.matchers.shouldBe +import io.kotest.matchers.shouldNotBe +import io.ktor.application.Application +import io.ktor.http.HttpMethod +import io.ktor.http.HttpStatusCode +import io.ktor.server.testing.TestApplicationEngine +import io.ktor.server.testing.createTestEnvironment +import io.ktor.server.testing.handleRequest +import io.ktor.server.testing.withApplication +import java.io.File + +object TestHelpers { + + private const val OPEN_API_ENDPOINT = "/openapi.json" + const val DEFAULT_TEST_ENDPOINT = "/test" + + fun getFileSnapshot(fileName: String): String { + val snapshotPath = "src/test/resources" + val file = File("$snapshotPath/$fileName") + return file.readText() + } + + /** + * Performs the baseline expected tests on an OpenAPI result. Confirms that the endpoint + * exists as expected, and that the content matches the expected blob found in the specified file + * @param snapshotName The snapshot file to retrieve from the resources folder + */ + private fun TestApplicationEngine.compareOpenAPISpec(snapshotName: String) { + // act + handleRequest(HttpMethod.Get, OPEN_API_ENDPOINT).apply { + // assert + response shouldHaveStatus HttpStatusCode.OK + response.content shouldNotBe null + response.content!! shouldEqualJson getFileSnapshot(snapshotName) + } + } + + /** + * This will take a provided JSON snapshot file, retrieve it from the resource folder, + * and build a test ktor server to compare the expected output with the output found in the default + * OpenAPI json endpoint + * @param snapshotName The snapshot file to retrieve from the resources folder + * @param moduleFunction Initializer for the application to allow tests to pass the required Ktor modules + */ + fun openApiTest(snapshotName: String, moduleFunction: Application.() -> Unit) { + withApplication(createTestEnvironment()) { + moduleFunction(application.apply { + kompendium() + docs() + jacksonConfigModule() + }) + compareOpenAPISpec(snapshotName) + } + } + + /** + * This allows us to easily confirm that an API endpoints functionality is not impacted by notarization. + * @param httpMethod The HTTP operation that we wish to perform + * @param endpoint The relative endpoint we wish to hit + * @param expectedResponse The expected response content of the operation + * @param expectedStatusCode The expected status code of the operation + */ + fun apiFunctionalityTest( + expectedResponse: String?, + endpoint: String = DEFAULT_TEST_ENDPOINT, + httpMethod: HttpMethod = HttpMethod.Get, + expectedStatusCode: HttpStatusCode = HttpStatusCode.OK, + moduleFunction: Application.() -> Unit + ) { + withApplication(createTestEnvironment()) { + moduleFunction(application.apply { + kompendium() + docs() + jacksonConfigModule() + }) + when (expectedResponse) { + null -> testWithNoResponse(httpMethod, endpoint, expectedStatusCode) + else -> testWithResponse(httpMethod, expectedResponse, endpoint, expectedStatusCode) + } + } + } + + private fun TestApplicationEngine.testWithResponse( + httpMethod: HttpMethod, + expectedResponse: String, + endpoint: String, + expectedStatusCode: HttpStatusCode, + ) { + handleRequest(httpMethod, endpoint).apply { + // assert + response shouldHaveStatus expectedStatusCode + response.content shouldNotBe null + response.content shouldBe expectedResponse + } + } + + private fun TestApplicationEngine.testWithNoResponse( + httpMethod: HttpMethod, + endpoint: String, + expectedStatusCode: HttpStatusCode, + ) { + handleRequest(httpMethod, endpoint).apply { + // assert + response shouldHaveStatus expectedStatusCode + response.content shouldBe null + } + } +} diff --git a/kompendium-core/src/testFixtures/kotlin/io/bkbn/kompendium/core/fixtures/TestModels.kt b/kompendium-core/src/testFixtures/kotlin/io/bkbn/kompendium/core/fixtures/TestModels.kt new file mode 100644 index 000000000..5f1017b4a --- /dev/null +++ b/kompendium-core/src/testFixtures/kotlin/io/bkbn/kompendium/core/fixtures/TestModels.kt @@ -0,0 +1,218 @@ +package io.bkbn.kompendium.core.fixtures + +import io.bkbn.kompendium.annotations.Field +import io.bkbn.kompendium.annotations.FreeFormObject +import io.bkbn.kompendium.annotations.Param +import io.bkbn.kompendium.annotations.ParamType +import io.bkbn.kompendium.annotations.UndeclaredField +import io.bkbn.kompendium.annotations.constraint.Format +import io.bkbn.kompendium.annotations.constraint.MaxItems +import io.bkbn.kompendium.annotations.constraint.MaxLength +import io.bkbn.kompendium.annotations.constraint.MaxProperties +import io.bkbn.kompendium.annotations.constraint.Maximum +import io.bkbn.kompendium.annotations.constraint.MinItems +import io.bkbn.kompendium.annotations.constraint.MinLength +import io.bkbn.kompendium.annotations.constraint.MinProperties +import io.bkbn.kompendium.annotations.constraint.Minimum +import io.bkbn.kompendium.annotations.constraint.MultipleOf +import io.bkbn.kompendium.annotations.constraint.Pattern +import io.bkbn.kompendium.annotations.constraint.UniqueItems +import kotlinx.serialization.json.JsonElement +import java.math.BigDecimal +import java.math.BigInteger +import java.util.UUID + +data class TestSimpleModel(val a: String, val b: Int) + +data class TestBigNumberModel(val a: BigDecimal, val b: BigInteger) + +data class TestByteArrayModel(val a: ByteArray) + +data class TestNestedModel(val inner: TestSimpleModel) + +data class TestSimpleWithEnums(val a: String, val b: SimpleEnum) + +data class TestSimpleWithMap(val a: String, val b: Map) + +data class TestSimpleWithList(val a: Boolean, val b: List) + +data class TestSimpleWithEnumList(val a: Double, val b: List) + +data class TestInvalidMap(val a: Map) + +data class TestParams( + @Param(ParamType.PATH) val a: String, + @Param(ParamType.QUERY) val aa: Int +) + +data class TestNested(val nesty: String) + +data class TestWithUUID(val id: UUID) + +data class TestRequest( + @Field(name = "field_name") + val fieldName: TestNested, + val b: Double, + val aaa: List +) + +data class TestResponse(val c: String) + +data class TestGeneric(val messy: String, val potato: T) + +data class TestCreatedResponse(val id: Int, val c: String) + +data class TestFieldOverride( + @Field(name = "real_name", description = "A Field that is super important!") + val b: Boolean +) + +data class MinMaxInt( + @Minimum("5") + @Maximum("100") + val a: Int +) + +data class MinMaxDouble( + @Minimum("5.5") + @Maximum("13.37") + val a: Double +) + +data class ExclusiveMinMax( + @Minimum("5", true) + @Maximum("100", true) + val a: Int +) + +data class FormattedString( + @Format("password") + @Param(ParamType.QUERY) + val a: String +) + +data class MinMaxString( + @MinLength(42) + @MaxLength(1337) + val a: String +) + +data class RegexString( + @Pattern("^\\d{3}-\\d{2}-\\d{4}\$") + val a: String +) + +data class MinMaxArray( + @MinItems(1) + @MaxItems(10) + val a: List +) + +data class UniqueArray( + @UniqueItems + val a: List +) + +data class MultipleOfInt( + @MultipleOf("5") + val a: Int +) + +data class MultipleOfDouble( + @MultipleOf("2.5") + val a: Double +) + +data class FreeFormData( + @FreeFormObject + val data: JsonElement +) + +data class MinMaxFreeForm( + @FreeFormObject + @MinProperties(5) + @MaxProperties(10) + val data: JsonElement +) + + +data class RequiredParam( + @Param(ParamType.QUERY) + val a: String +) + +data class DefaultParam( + @Param(ParamType.QUERY) + val b: String = "heyo" +) + +data class DefaultField( + val a: String = "hi", + val b: Int +) + +data class NullableField( + val a: String? +) + +data class ComplexRequest( + val org: String, + @Field("amazing_field") + val amazingField: String, + val tables: List +) + +data class NestedComplexItem( + val name: String, + val alias: CustomAlias +) + +typealias CustomAlias = Map + +data class CrazyItem(val enumeration: SimpleEnum) + +enum class SimpleEnum { + ONE, + TWO +} + +data class DefaultParameter( + @Param(ParamType.QUERY) val a: Int = 100, + @Param(ParamType.PATH) val b: String?, + @Param(ParamType.PATH) val c: Boolean +) + +data class ExceptionResponse(val message: String) + +data class OptionalParams( + @Param(ParamType.QUERY) val required: String, + @Param(ParamType.QUERY) val notRequired: String? +) + +sealed class FlibbityGibbit + +data class SimpleGibbit(val a: String) : FlibbityGibbit() +data class ComplexGibbit(val b: String, val c: Int) : FlibbityGibbit() + +sealed interface SlammaJamma + +data class OneJamma(val a: Int) : SlammaJamma +data class AnothaJamma(val b: Float) : SlammaJamma +//data class InsaneJamma(val c: SlammaJamma) : SlammaJamma // 👀 + +sealed interface Flibbity + +data class Gibbity(val a: T) : Flibbity +data class Bibbity(val b: String, val f: T) : Flibbity + +enum class Hehe { + HAHA, + HOHO +} + +@UndeclaredField("nowYouDont", Hehe::class) +data class Mysterious(val nowYouSeeMe: String) + +data class HeaderNameTest( + @Param(type = ParamType.HEADER) val `X-UserEmail`: String +) diff --git a/kompendium-core/src/testFixtures/kotlin/io/bkbn/kompendium/core/fixtures/TestModules.kt b/kompendium-core/src/testFixtures/kotlin/io/bkbn/kompendium/core/fixtures/TestModules.kt new file mode 100644 index 000000000..191820b36 --- /dev/null +++ b/kompendium-core/src/testFixtures/kotlin/io/bkbn/kompendium/core/fixtures/TestModules.kt @@ -0,0 +1,65 @@ +package io.bkbn.kompendium.core.fixtures + +import com.fasterxml.jackson.annotation.JsonInclude +import com.fasterxml.jackson.databind.SerializationFeature +import io.bkbn.kompendium.core.Kompendium +import io.bkbn.kompendium.core.routes.redoc +import io.bkbn.kompendium.oas.OpenApiSpec +import io.bkbn.kompendium.oas.info.Contact +import io.bkbn.kompendium.oas.info.Info +import io.bkbn.kompendium.oas.info.License +import io.bkbn.kompendium.oas.server.Server +import io.ktor.application.Application +import io.ktor.application.install +import io.ktor.features.ContentNegotiation +import io.ktor.http.ContentType +import io.ktor.jackson.jackson +import io.ktor.routing.routing +import java.net.URI + +fun Application.docs() { + routing { + redoc() + } +} + +fun Application.jacksonConfigModule() { + install(ContentNegotiation) { + jackson(ContentType.Application.Json) { + enable(SerializationFeature.INDENT_OUTPUT) + setSerializationInclusion(JsonInclude.Include.NON_NULL) + } + } +} + +fun Application.kompendium() { + install(Kompendium) { + spec = OpenApiSpec( + info = Info( + title = "Test API", + version = "1.33.7", + description = "An amazing, fully-ish 😉 generated API spec", + termsOfService = URI("https://example.com"), + contact = Contact( + name = "Homer Simpson", + email = "chunkylover53@aol.com", + url = URI("https://gph.is/1NPUDiM") + ), + license = License( + name = "MIT", + url = URI("https://github.com/bkbnio/kompendium/blob/main/LICENSE") + ) + ), + servers = mutableListOf( + Server( + url = URI("https://myawesomeapi.com"), + description = "Production instance of my API" + ), + Server( + url = URI("https://staging.myawesomeapi.com"), + description = "Where the fun stuff happens" + ) + ) + ) + } +} diff --git a/kompendium-core/src/testFixtures/kotlin/io/bkbn/kompendium/core/fixtures/TestResponseInfo.kt b/kompendium-core/src/testFixtures/kotlin/io/bkbn/kompendium/core/fixtures/TestResponseInfo.kt new file mode 100644 index 000000000..44df6edc9 --- /dev/null +++ b/kompendium-core/src/testFixtures/kotlin/io/bkbn/kompendium/core/fixtures/TestResponseInfo.kt @@ -0,0 +1,250 @@ +package io.bkbn.kompendium.core.fixtures + +import io.bkbn.kompendium.core.metadata.ExceptionInfo +import io.bkbn.kompendium.core.metadata.method.PostInfo +import io.bkbn.kompendium.core.metadata.method.PutInfo +import io.bkbn.kompendium.core.metadata.RequestInfo +import io.bkbn.kompendium.core.metadata.ResponseInfo +import io.bkbn.kompendium.core.metadata.method.DeleteInfo +import io.bkbn.kompendium.core.metadata.method.GetInfo +import io.ktor.http.HttpStatusCode +import kotlin.reflect.typeOf + +object TestResponseInfo { + val testGetResponse = ResponseInfo(HttpStatusCode.OK, "A Successful Endeavor") + private val testGetListResponse = + ResponseInfo>(HttpStatusCode.OK, "A Successful List-y Endeavor") + private val testPostResponse = ResponseInfo(HttpStatusCode.Created, "A Successful Endeavor") + private val testPostResponseAgain = ResponseInfo(HttpStatusCode.Created, "A Successful Endeavor") + private val testDeleteResponse = + ResponseInfo(HttpStatusCode.NoContent, "A Successful Endeavor", mediaTypes = emptyList()) + private val testRequest = RequestInfo("A Test request") + private val testRequestAgain = RequestInfo("A Test request") + private val complexRequest = RequestInfo("A Complex request") + val testGetInfo = GetInfo( + summary = "Another get test", + description = "testing more", + responseInfo = testGetResponse + ) + val testGetInfoAgain = GetInfo>( + summary = "Another get test", + description = "testing more", + responseInfo = testGetListResponse + ) + private val accessDeniedResponse = ExceptionInfo( + responseType = typeOf(), + description = "Access Denied", + status = HttpStatusCode.Forbidden + ) + private val polymorphicException = ExceptionInfo( + responseType = typeOf(), + description = "The Gibbits are ANGRY", + status = HttpStatusCode.NotImplemented + ) + private val genericException = ExceptionInfo>( + responseType = typeOf>(), + description = "Wow serious things went wrong", + status = HttpStatusCode.BadRequest + ) + private val exceptionResponseInfo = ExceptionInfo( + responseType = typeOf(), + description = "Bad Things Happened", + status = HttpStatusCode.BadRequest + ) + val testGetWithException = testGetInfo.copy( + canThrow = setOf(exceptionResponseInfo) + ) + val testGetWithMultipleExceptions = testGetInfo.copy( + canThrow = setOf(accessDeniedResponse, exceptionResponseInfo) + ) + val testGetWithPolymorphicException = testGetInfo.copy( + canThrow = setOf(polymorphicException) + ) + val testGetWithGenericException = testGetInfo.copy( + canThrow = setOf(genericException) + ) + val testPostInfo = PostInfo( + summary = "Test post endpoint", + description = "Post your tests here!", + responseInfo = testPostResponse, + requestInfo = testRequest + ) + val testPutInfo = PutInfo( + summary = "Test put endpoint", + description = "Put your tests here!", + responseInfo = testPostResponse, + requestInfo = complexRequest + ) + val testPutInfoAlso = PutInfo( + summary = "Test put endpoint", + description = "Put your tests here!", + responseInfo = testPostResponse, + requestInfo = testRequest + ) + val testPutInfoAgain = PutInfo( + summary = "Test put endpoint", + description = "Put your tests here!", + responseInfo = testPostResponseAgain, + requestInfo = testRequestAgain + ) + val testDeleteInfo = DeleteInfo( + summary = "Test delete endpoint", + description = "testing my deletes", + responseInfo = testDeleteResponse + ) + val testOptionalParams = GetInfo( + summary = "No request params and response body", + description = "testing more", + responseInfo = ResponseInfo(HttpStatusCode.NoContent, "Empty") + ) + val polymorphicResponse = GetInfo( + summary = "All the gibbits", + description = "Polymorphic response", + responseInfo = simpleOkResponse() + ) + val polymorphicListResponse = GetInfo>( + summary = "Oh so many gibbits", + description = "Polymorphic list response", + responseInfo = simpleOkResponse() + ) + val polymorphicMapResponse = GetInfo>( + summary = "By gawd that's a lot of gibbits", + description = "Polymorphic list response", + responseInfo = simpleOkResponse() + ) + val polymorphicInterfaceResponse = GetInfo( + summary = "Come on and slam", + description = "and welcome to the jam", + responseInfo = simpleOkResponse() + ) + val genericPolymorphicResponse = GetInfo>( + summary = "More flibbity", + description = "Polymorphic with generics", + responseInfo = simpleOkResponse() + ) + val anotherGenericPolymorphicResponse = GetInfo>( + summary = "The Most Flibbity", + description = "Polymorphic with generics but like... crazier", + responseInfo = simpleOkResponse() + ) + val undeclaredResponseType = GetInfo( + summary = "spooky class", + description = "break this glass in scenario of emergency", + responseInfo = simpleOkResponse() + ) + val headerParam = GetInfo( + summary = "testing header stuffs", + description = "Good for many things", + responseInfo = simpleOkResponse() + ) + val genericResponse = GetInfo>( + summary = "Single Generic", + description = "Simple generic data class", + responseInfo = simpleOkResponse() + ) + val fieldOverride = GetInfo( + summary = "A Response with a spicy field", + description = "Important info within!", + responseInfo = simpleOkResponse() + ) + + val minMaxInt = GetInfo( + summary = "Constrained int field", + description = "Cool stuff", + responseInfo = simpleOkResponse() + ) + + val minMaxDouble = GetInfo( + summary = "Constrained int field", + description = "Cool stuff", + responseInfo = simpleOkResponse() + ) + + val exclusiveMinMax = GetInfo( + summary = "Constrained int field", + description = "Cool stuff", + responseInfo = simpleOkResponse() + ) + + val requiredParam = GetInfo( + summary = "required param", + description = "Cool stuff", + responseInfo = simpleOkResponse() + ) + + val formattedParam = GetInfo( + summary = "required param", + description = "Cool stuff", + responseInfo = simpleOkResponse() + ) + + val minMaxString = GetInfo( + summary = "required param", + description = "Cool stuff", + responseInfo = simpleOkResponse() + ) + + val regexString = GetInfo( + summary = "required param", + description = "Cool stuff", + responseInfo = simpleOkResponse() + ) + + val minMaxArray = GetInfo( + summary = "required param", + description = "Cool stuff", + responseInfo = simpleOkResponse() + ) + + val uniqueArray = GetInfo( + summary = "required param", + description = "Cool stuff", + responseInfo = simpleOkResponse() + ) + + val multipleOfInt = GetInfo( + summary = "required param", + description = "Cool stuff", + responseInfo = simpleOkResponse() + ) + + val multipleOfDouble = GetInfo( + summary = "required param", + description = "Cool stuff", + responseInfo = simpleOkResponse() + ) + + val freeFormObject = GetInfo( + summary = "required param", + description = "Cool stuff", + responseInfo = simpleOkResponse() + ) + + val minMaxFreeForm = GetInfo( + summary = "required param", + description = "Cool stuff", + responseInfo = simpleOkResponse() + ) + + val defaultParam = GetInfo( + summary = "default param", + description = "Cool stuff", + responseInfo = simpleOkResponse() + ) + + val defaultField = PostInfo( + summary = "default param", + description = "Cool stuff", + responseInfo = simpleOkResponse(), + requestInfo = RequestInfo("cool") + ) + + val nullableField = PostInfo( + summary = "default param", + description = "Cool stuff", + responseInfo = simpleOkResponse(), + requestInfo = RequestInfo("cool") + ) + + private fun simpleOkResponse() = ResponseInfo(HttpStatusCode.OK, "A successful endeavor") +} diff --git a/kompendium-locations/Module.md b/kompendium-locations/Module.md new file mode 100644 index 000000000..3718d3ffa --- /dev/null +++ b/kompendium-locations/Module.md @@ -0,0 +1 @@ +# Module kompendium-locations diff --git a/kompendium-locations/build.gradle.kts b/kompendium-locations/build.gradle.kts index 68f608208..e70daf0e7 100644 --- a/kompendium-locations/build.gradle.kts +++ b/kompendium-locations/build.gradle.kts @@ -1,78 +1,16 @@ plugins { - `java-library` - `maven-publish` - signing + id("io.bkbn.sourdough.library") } dependencies { - implementation(platform("org.jetbrains.kotlin:kotlin-bom")) - implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8") - implementation(libs.bundles.ktor) - implementation(libs.ktor.locations) + // IMPLEMENTATION + + val ktorVersion: String by project implementation(projects.kompendiumCore) + implementation(group = "io.ktor", name = "ktor-server-core", version = ktorVersion) + implementation(group = "io.ktor", name = "ktor-locations", version = ktorVersion) - testImplementation(libs.ktor.jackson) - testImplementation("org.jetbrains.kotlin:kotlin-test") - testImplementation("org.jetbrains.kotlin:kotlin-test-junit") - testImplementation(libs.jackson.module.kotlin) - testImplementation(libs.ktor.server.test.host) -} - -java { - withSourcesJar() - withJavadocJar() -} - -publishing { - repositories { - maven { - name = "GithubPackages" - url = uri("https://maven.pkg.github.com/bkbnio/kompendium") - credentials { - username = System.getenv("GITHUB_ACTOR") - password = System.getenv("GITHUB_TOKEN") - } - } - } - publications { - create("kompendium") { - from(components["kotlin"]) - artifact(tasks.sourcesJar) - artifact(tasks.javadocJar) - groupId = project.group.toString() - artifactId = project.name.toLowerCase() - version = project.version.toString() - - pom { - name.set("Kompendium") - description.set("A minimally invasive OpenAPI spec generator for Ktor") - url.set("https://github.com/bkbnio/Kompendium") - licenses { - license { - name.set("MIT License") - url.set("https://mit-license.org/") - } - } - developers { - developer { - id.set("bkbnio") - name.set("Ryan Brink") - email.set("admin@bkbn.io") - } - } - scm { - connection.set("scm:git:git://github.com/bkbnio/Kompendium.git") - developerConnection.set("scm:git:ssh://github.com/bkbnio/Kompendium.git") - url.set("https://github.com/bkbnio/Kompendium.git") - } - } - } - } -} - -signing { - val signingKey: String? by project - val signingPassword: String? by project - useInMemoryPgpKeys(signingKey, signingPassword) - sign(publishing.publications) + // TESTING + + testImplementation(testFixtures(projects.kompendiumCore)) } diff --git a/kompendium-locations/src/main/kotlin/io/bkbn/kompendium/locations/NotarizedLocation.kt b/kompendium-locations/src/main/kotlin/io/bkbn/kompendium/locations/NotarizedLocation.kt index 52fe92a75..e2f119074 100644 --- a/kompendium-locations/src/main/kotlin/io/bkbn/kompendium/locations/NotarizedLocation.kt +++ b/kompendium-locations/src/main/kotlin/io/bkbn/kompendium/locations/NotarizedLocation.kt @@ -1,20 +1,24 @@ package io.bkbn.kompendium.locations -import io.bkbn.kompendium.Kompendium -import io.bkbn.kompendium.KompendiumPreFlight -import io.bkbn.kompendium.MethodParser.parseMethodInfo -import io.bkbn.kompendium.models.meta.MethodInfo.DeleteInfo -import io.bkbn.kompendium.models.meta.MethodInfo.GetInfo -import io.bkbn.kompendium.models.meta.MethodInfo.PostInfo -import io.bkbn.kompendium.models.meta.MethodInfo.PutInfo -import io.bkbn.kompendium.models.oas.OpenApiSpecPathItem +import io.bkbn.kompendium.core.Kompendium +import io.bkbn.kompendium.core.KompendiumPreFlight.methodNotarizationPreFlight +import io.bkbn.kompendium.core.MethodParser.parseMethodInfo +import io.bkbn.kompendium.core.Notarized.calculateRoutePath +import io.bkbn.kompendium.core.metadata.method.DeleteInfo +import io.bkbn.kompendium.core.metadata.method.GetInfo +import io.bkbn.kompendium.core.metadata.method.PostInfo +import io.bkbn.kompendium.core.metadata.method.PutInfo +import io.bkbn.kompendium.oas.path.Path +import io.bkbn.kompendium.oas.path.PathOperation import io.ktor.application.ApplicationCall +import io.ktor.application.feature import io.ktor.http.HttpMethod import io.ktor.locations.KtorExperimentalLocationsAPI import io.ktor.locations.Location import io.ktor.locations.handle import io.ktor.locations.location import io.ktor.routing.Route +import io.ktor.routing.application import io.ktor.routing.method import io.ktor.util.pipeline.PipelineContext import kotlin.reflect.KClass @@ -30,115 +34,125 @@ object NotarizedLocation { /** * Notarization for an HTTP GET request leveraging the Ktor [io.ktor.locations.Locations] plugin * @param TParam The class containing all parameter fields. - * Each field must be annotated with @[io.bkbn.kompendium.annotations.KompendiumField]. + * Each field must be annotated with @[io.bkbn.kompendium.annotations.Param]. * Additionally, the class must be annotated with @[io.ktor.locations.Location]. * @param TResp Class detailing the expected API response * @param info Route metadata + * @param postProcess Adds an optional callback hook to perform manual overrides on the generated [PathOperation] */ inline fun Route.notarizedGet( info: GetInfo, + postProcess: (PathOperation) -> PathOperation = { p -> p }, noinline body: suspend PipelineContext.(TParam) -> Unit - ): Route = - KompendiumPreFlight.methodNotarizationPreFlight() { paramType, requestType, responseType -> - val locationAnnotation = TParam::class.findAnnotation() - require(locationAnnotation != null) { "Location annotation must be present to leverage notarized location api" } - val path = Kompendium.calculatePath(this) - val locationPath = TParam::class.calculatePath() - val pathWithLocation = path.plus(locationPath) - Kompendium.openApiSpec.paths.getOrPut(pathWithLocation) { OpenApiSpecPathItem() } - Kompendium.openApiSpec.paths[pathWithLocation]?.get = parseMethodInfo(info, paramType, requestType, responseType) - return location(TParam::class) { - method(HttpMethod.Get) { handle(body) } - } + ): Route = methodNotarizationPreFlight() { paramType, requestType, responseType -> + val locationAnnotation = TParam::class.findAnnotation() + require(locationAnnotation != null) { "Location annotation must be present to leverage notarized location api" } + val feature = application.feature(Kompendium) + val path = calculateRoutePath() + val locationPath = TParam::class.calculateLocationPath() + val pathWithLocation = path.plus(locationPath) + feature.config.spec.paths.getOrPut(pathWithLocation) { Path() } + val baseInfo = parseMethodInfo(info, paramType, requestType, responseType, feature) + feature.config.spec.paths[pathWithLocation]?.get = postProcess(baseInfo) + return location(TParam::class) { + method(HttpMethod.Get) { handle(body) } } + } /** * Notarization for an HTTP POST request leveraging the Ktor [io.ktor.locations.Locations] plugin * @param TParam The class containing all parameter fields. - * Each field must be annotated with @[io.bkbn.kompendium.annotations.KompendiumField] + * Each field must be annotated with @[io.bkbn.kompendium.annotations.Param] * Additionally, the class must be annotated with @[io.ktor.locations.Location]. * @param TReq Class detailing the expected API request body * @param TResp Class detailing the expected API response * @param info Route metadata + * @param postProcess Adds an optional callback hook to perform manual overrides on the generated [PathOperation] */ inline fun Route.notarizedPost( info: PostInfo, + postProcess: (PathOperation) -> PathOperation = { p -> p }, noinline body: suspend PipelineContext.(TParam) -> Unit - ): Route = - KompendiumPreFlight.methodNotarizationPreFlight() { paramType, requestType, responseType -> - val locationAnnotation = TParam::class.findAnnotation() - require(locationAnnotation != null) { "Location annotation must be present to leverage notarized location api" } - val path = Kompendium.calculatePath(this) - val locationPath = TParam::class.calculatePath() - val pathWithLocation = path.plus(locationPath) - Kompendium.openApiSpec.paths.getOrPut(pathWithLocation) { OpenApiSpecPathItem() } - Kompendium.openApiSpec.paths[pathWithLocation]?.post = parseMethodInfo(info, paramType, requestType, responseType) - return location(TParam::class) { - method(HttpMethod.Post) { handle(body) } - } + ): Route = methodNotarizationPreFlight() { paramType, requestType, responseType -> + val locationAnnotation = TParam::class.findAnnotation() + require(locationAnnotation != null) { "Location annotation must be present to leverage notarized location api" } + val feature = application.feature(Kompendium) + val path = calculateRoutePath() + val locationPath = TParam::class.calculateLocationPath() + val pathWithLocation = path.plus(locationPath) + feature.config.spec.paths.getOrPut(pathWithLocation) { Path() } + val baseInfo = parseMethodInfo(info, paramType, requestType, responseType, feature) + feature.config.spec.paths[pathWithLocation]?.post = postProcess(baseInfo) + return location(TParam::class) { + method(HttpMethod.Post) { handle(body) } } + } /** * Notarization for an HTTP Delete request leveraging the Ktor [io.ktor.locations.Locations] plugin * @param TParam The class containing all parameter fields. - * Each field must be annotated with @[io.bkbn.kompendium.annotations.KompendiumField] + * Each field must be annotated with @[io.bkbn.kompendium.annotations.Param] * Additionally, the class must be annotated with @[io.ktor.locations.Location]. * @param TReq Class detailing the expected API request body * @param TResp Class detailing the expected API response * @param info Route metadata + * @param postProcess Adds an optional callback hook to perform manual overrides on the generated [PathOperation] */ inline fun Route.notarizedPut( info: PutInfo, + postProcess: (PathOperation) -> PathOperation = { p -> p }, noinline body: suspend PipelineContext.(TParam) -> Unit - ): Route = - KompendiumPreFlight.methodNotarizationPreFlight() { paramType, requestType, responseType -> - val locationAnnotation = TParam::class.findAnnotation() - require(locationAnnotation != null) { "Location annotation must be present to leverage notarized location api" } - val path = Kompendium.calculatePath(this) - val locationPath = TParam::class.calculatePath() - val pathWithLocation = path.plus(locationPath) - Kompendium.openApiSpec.paths.getOrPut(pathWithLocation) { OpenApiSpecPathItem() } - Kompendium.openApiSpec.paths[pathWithLocation]?.put = - parseMethodInfo(info, paramType, requestType, responseType) - return location(TParam::class) { - method(HttpMethod.Put) { handle(body) } - } + ): Route = methodNotarizationPreFlight() { paramType, requestType, responseType -> + val locationAnnotation = TParam::class.findAnnotation() + require(locationAnnotation != null) { "Location annotation must be present to leverage notarized location api" } + val feature = application.feature(Kompendium) + val path = calculateRoutePath() + val locationPath = TParam::class.calculateLocationPath() + val pathWithLocation = path.plus(locationPath) + feature.config.spec.paths.getOrPut(pathWithLocation) { Path() } + val baseInfo = parseMethodInfo(info, paramType, requestType, responseType, feature) + feature.config.spec.paths[pathWithLocation]?.put = postProcess(baseInfo) + return location(TParam::class) { + method(HttpMethod.Put) { handle(body) } } + } /** * Notarization for an HTTP POST request leveraging the Ktor [io.ktor.locations.Locations] plugin * @param TParam The class containing all parameter fields. - * Each field must be annotated with @[io.bkbn.kompendium.annotations.KompendiumField] + * Each field must be annotated with @[io.bkbn.kompendium.annotations.Param] * Additionally, the class must be annotated with @[io.ktor.locations.Location]. * @param TResp Class detailing the expected API response * @param info Route metadata + * @param postProcess Adds an optional callback hook to perform manual overrides on the generated [PathOperation] */ inline fun Route.notarizedDelete( info: DeleteInfo, + postProcess: (PathOperation) -> PathOperation = { p -> p }, noinline body: suspend PipelineContext.(TParam) -> Unit - ): Route = - KompendiumPreFlight.methodNotarizationPreFlight { paramType, requestType, responseType -> - val locationAnnotation = TParam::class.findAnnotation() - require(locationAnnotation != null) { "Location annotation must be present to leverage notarized location api" } - val path = Kompendium.calculatePath(this) - val locationPath = TParam::class.calculatePath() - val pathWithLocation = path.plus(locationPath) - Kompendium.openApiSpec.paths.getOrPut(pathWithLocation) { OpenApiSpecPathItem() } - Kompendium.openApiSpec.paths[pathWithLocation]?.delete = - parseMethodInfo(info, paramType, requestType, responseType) - return location(TParam::class) { - method(HttpMethod.Delete) { handle(body) } - } + ): Route = methodNotarizationPreFlight { paramType, requestType, responseType -> + val locationAnnotation = TParam::class.findAnnotation() + require(locationAnnotation != null) { "Location annotation must be present to leverage notarized location api" } + val feature = application.feature(Kompendium) + val path = calculateRoutePath() + val locationPath = TParam::class.calculateLocationPath() + val pathWithLocation = path.plus(locationPath) + feature.config.spec.paths.getOrPut(pathWithLocation) { Path() } + val baseInfo = parseMethodInfo(info, paramType, requestType, responseType, feature) + feature.config.spec.paths[pathWithLocation]?.delete = postProcess(baseInfo) + return location(TParam::class) { + method(HttpMethod.Delete) { handle(body) } } + } - fun KClass<*>.calculatePath(suffix: String = ""): String { + fun KClass<*>.calculateLocationPath(suffix: String = ""): String { val locationAnnotation = this.findAnnotation() require(locationAnnotation != null) { "Location annotation must be present to leverage notarized location api" } val parent = this.java.declaringClass?.kotlin val newSuffix = locationAnnotation.path.plus(suffix) return when (parent) { null -> newSuffix - else -> parent.calculatePath(newSuffix) + else -> parent.calculateLocationPath(newSuffix) } } } diff --git a/kompendium-locations/src/test/kotlin/io/bkbn/kompendium/locations/KompendiumLocationsTest.kt b/kompendium-locations/src/test/kotlin/io/bkbn/kompendium/locations/KompendiumLocationsTest.kt index 40f1250e4..2b9214d1e 100644 --- a/kompendium-locations/src/test/kotlin/io/bkbn/kompendium/locations/KompendiumLocationsTest.kt +++ b/kompendium-locations/src/test/kotlin/io/bkbn/kompendium/locations/KompendiumLocationsTest.kt @@ -1,358 +1,74 @@ package io.bkbn.kompendium.locations -import com.fasterxml.jackson.annotation.JsonInclude -import com.fasterxml.jackson.databind.SerializationFeature -import io.bkbn.kompendium.Kompendium -import io.bkbn.kompendium.annotations.KompendiumParam -import io.bkbn.kompendium.annotations.ParamType -import io.bkbn.kompendium.locations.NotarizedLocation.notarizedDelete -import io.bkbn.kompendium.locations.NotarizedLocation.notarizedGet -import io.bkbn.kompendium.locations.NotarizedLocation.notarizedPost -import io.bkbn.kompendium.locations.NotarizedLocation.notarizedPut -import io.bkbn.kompendium.locations.util.TestData -import io.bkbn.kompendium.models.meta.MethodInfo -import io.bkbn.kompendium.models.meta.RequestInfo -import io.bkbn.kompendium.models.meta.ResponseInfo -import io.bkbn.kompendium.routes.openApi -import io.bkbn.kompendium.routes.redoc -import io.ktor.application.Application -import io.ktor.application.call -import io.ktor.application.install -import io.ktor.features.ContentNegotiation -import io.ktor.http.ContentType -import io.ktor.http.HttpMethod -import io.ktor.http.HttpStatusCode -import io.ktor.jackson.jackson -import io.ktor.locations.Location -import io.ktor.locations.Locations -import io.ktor.response.respondText -import io.ktor.routing.route -import io.ktor.routing.routing -import io.ktor.server.testing.handleRequest -import io.ktor.server.testing.withTestApplication -import org.junit.Test -import kotlin.test.AfterTest -import kotlin.test.assertEquals +import io.bkbn.kompendium.core.fixtures.TestHelpers.openApiTest +import io.bkbn.kompendium.locations.util.locationsConfig +import io.bkbn.kompendium.locations.util.notarizedDeleteNestedLocation +import io.bkbn.kompendium.locations.util.notarizedDeleteSimpleLocation +import io.bkbn.kompendium.locations.util.notarizedGetNestedLocation +import io.bkbn.kompendium.locations.util.notarizedGetSimpleLocation +import io.bkbn.kompendium.locations.util.notarizedPostNestedLocation +import io.bkbn.kompendium.locations.util.notarizedPostSimpleLocation +import io.bkbn.kompendium.locations.util.notarizedPutNestedLocation +import io.bkbn.kompendium.locations.util.notarizedPutSimpleLocation +import io.kotest.core.spec.style.DescribeSpec -class KompendiumLocationsTest { - - @AfterTest - fun `reset Kompendium`() { - Kompendium.resetSchema() - } - - @Test - fun `Notarized Get with simple location`() { - withTestApplication({ - configModule() - docs() - notarizedGetSimpleLocation() - }) { - // do - val json = handleRequest(HttpMethod.Get, "/openapi.json").response.content - - // expect - val expected = TestData.getFileSnapshot("notarized_get_simple_location.json").trim() - assertEquals(expected, json, "The received json spec should match the expected content") - } - } - - @Test - fun `Notarized Get with nested location`() { - withTestApplication({ - configModule() - docs() - notarizedGetNestedLocation() - }) { - // do - val json = handleRequest(HttpMethod.Get, "/openapi.json").response.content - - // expect - val expected = TestData.getFileSnapshot("notarized_get_nested_location.json").trim() - assertEquals(expected, json, "The received json spec should match the expected content") - } - } - - @Test - fun `Notarized Post with simple location`() { - withTestApplication({ - configModule() - docs() - notarizedPostSimpleLocation() - }) { - // do - val json = handleRequest(HttpMethod.Get, "/openapi.json").response.content - - // expect - val expected = TestData.getFileSnapshot("notarized_post_simple_location.json").trim() - assertEquals(expected, json, "The received json spec should match the expected content") - } - } - - @Test - fun `Notarized Post with nested location`() { - withTestApplication({ - configModule() - docs() - notarizedPostNestedLocation() - }) { - // do - val json = handleRequest(HttpMethod.Get, "/openapi.json").response.content - - // expect - val expected = TestData.getFileSnapshot("notarized_post_nested_location.json").trim() - assertEquals(expected, json, "The received json spec should match the expected content") - } - } - - @Test - fun `Notarized Put with simple location`() { - withTestApplication({ - configModule() - docs() - notarizedPutSimpleLocation() - }) { - // do - val json = handleRequest(HttpMethod.Get, "/openapi.json").response.content - - // expect - val expected = TestData.getFileSnapshot("notarized_put_simple_location.json").trim() - assertEquals(expected, json, "The received json spec should match the expected content") - } - } - - @Test - fun `Notarized Put with nested location`() { - withTestApplication({ - configModule() - docs() - notarizedPutNestedLocation() - }) { - // do - val json = handleRequest(HttpMethod.Get, "/openapi.json").response.content - - // expect - val expected = TestData.getFileSnapshot("notarized_put_nested_location.json").trim() - assertEquals(expected, json, "The received json spec should match the expected content") - } - } - - @Test - fun `Notarized Delete with simple location`() { - withTestApplication({ - configModule() - docs() - notarizedDeleteSimpleLocation() - }) { - // do - val json = handleRequest(HttpMethod.Get, "/openapi.json").response.content - - // expect - val expected = TestData.getFileSnapshot("notarized_delete_simple_location.json").trim() - assertEquals(expected, json, "The received json spec should match the expected content") - } - } - - @Test - fun `Notarized Delete with nested location`() { - withTestApplication({ - configModule() - docs() - notarizedDeleteNestedLocation() - }) { - // do - val json = handleRequest(HttpMethod.Get, "/openapi.json").response.content - - // expect - val expected = TestData.getFileSnapshot("notarized_delete_nested_location.json").trim() - assertEquals(expected, json, "The received json spec should match the expected content") - } - } - - private fun Application.configModule() { - install(ContentNegotiation) { - jackson(ContentType.Application.Json) { - enable(SerializationFeature.INDENT_OUTPUT) - setSerializationInclusion(JsonInclude.Include.NON_NULL) +class KompendiumLocationsTest : DescribeSpec({ + describe("Locations") { + it("Can notarize a get request with a simple location") { + // act + openApiTest("notarized_get_simple_location.json") { + locationsConfig() + notarizedGetSimpleLocation() } } - install(Locations) - } - - private val oas = Kompendium.openApiSpec.copy() - - private fun Application.docs() { - routing { - openApi(oas) - redoc(oas) + it("Can notarize a get request with a nested location") { + // act + openApiTest("notarized_get_nested_location.json") { + locationsConfig() + notarizedGetNestedLocation() + } } - } - - private fun Application.notarizedGetSimpleLocation() { - routing { - route("/test") { - notarizedGet(TestResponseInfo.testGetSimpleLocation) { - call.respondText { "hey dude ‼️ congratz on the get request" } - } + it("Can notarize a post with a simple location") { + // act + openApiTest("notarized_post_simple_location.json") { + locationsConfig() + notarizedPostSimpleLocation() + } + } + it("Can notarize a post with a nested location") { + // act + openApiTest("notarized_post_nested_location.json") { + locationsConfig() + notarizedPostNestedLocation() + } + } + it("Can notarize a put with a simple location") { + // act + openApiTest("notarized_put_simple_location.json") { + locationsConfig() + notarizedPutSimpleLocation() + } + } + it("Can notarize a put with a nested location") { + // act + openApiTest("notarized_put_nested_location.json") { + locationsConfig() + notarizedPutNestedLocation() + } + } + it("Can notarize a delete with a simple location") { + // act + openApiTest("notarized_delete_simple_location.json") { + locationsConfig() + notarizedDeleteSimpleLocation() + } + } + it("Can notarize a delete with a nested location") { + // act + openApiTest("notarized_delete_nested_location.json") { + locationsConfig() + notarizedDeleteNestedLocation() } } } - - private fun Application.notarizedGetNestedLocation() { - routing { - route("/test") { - notarizedGet(TestResponseInfo.testGetNestedLocation) { - call.respondText { "hey dude ‼️ congratz on the get request" } - } - } - } - } - - private fun Application.notarizedPostSimpleLocation() { - routing { - route("/test") { - notarizedPost(TestResponseInfo.testPostSimpleLocation) { - call.respondText { "hey dude ‼️ congratz on the get request" } - } - } - } - } - - private fun Application.notarizedPostNestedLocation() { - routing { - route("/test") { - notarizedPost(TestResponseInfo.testPostNestedLocation) { - call.respondText { "hey dude ‼️ congratz on the get request" } - } - } - } - } - - private fun Application.notarizedPutSimpleLocation() { - routing { - route("/test") { - notarizedPut(TestResponseInfo.testPutSimpleLocation) { - call.respondText { "hey dude ‼️ congratz on the get request" } - } - } - } - } - - private fun Application.notarizedPutNestedLocation() { - routing { - route("/test") { - notarizedPut(TestResponseInfo.testPutNestedLocation) { - call.respondText { "hey dude ‼️ congratz on the get request" } - } - } - } - } - - private fun Application.notarizedDeleteSimpleLocation() { - routing { - route("/test") { - notarizedDelete(TestResponseInfo.testDeleteSimpleLocation) { - call.respondText { "hey dude ‼️ congratz on the get request" } - } - } - } - } - - private fun Application.notarizedDeleteNestedLocation() { - routing { - route("/test") { - notarizedDelete(TestResponseInfo.testDeleteNestedLocation) { - call.respondText { "hey dude ‼️ congratz on the get request" } - } - } - } - } - - object TestResponseInfo { - val testGetSimpleLocation = MethodInfo.GetInfo( - summary = "Location Test", - description = "A cool test", - responseInfo = ResponseInfo( - status = HttpStatusCode.OK, - description = "A successful endeavor" - ) - ) - val testPostSimpleLocation = MethodInfo.PostInfo( - summary = "Location Test", - description = "A cool test", - requestInfo = RequestInfo( - description = "Cool stuff" - ), - responseInfo = ResponseInfo( - status = HttpStatusCode.OK, - description = "A successful endeavor" - ) - ) - val testPutSimpleLocation = MethodInfo.PutInfo( - summary = "Location Test", - description = "A cool test", - requestInfo = RequestInfo( - description = "Cool stuff" - ), - responseInfo = ResponseInfo( - status = HttpStatusCode.OK, - description = "A successful endeavor" - ) - ) - val testDeleteSimpleLocation = MethodInfo.DeleteInfo( - summary = "Location Test", - description = "A cool test", - responseInfo = ResponseInfo( - status = HttpStatusCode.OK, - description = "A successful endeavor" - ) - ) - val testGetNestedLocation = MethodInfo.GetInfo( - summary = "Location Test", - description = "A cool test", - responseInfo = ResponseInfo( - status = HttpStatusCode.OK, - description = "A successful endeavor" - ) - ) - val testPostNestedLocation = MethodInfo.PostInfo( - summary = "Location Test", - description = "A cool test", - requestInfo = RequestInfo( - description = "Cool stuff" - ), - responseInfo = ResponseInfo( - status = HttpStatusCode.OK, - description = "A successful endeavor" - ) - ) - val testPutNestedLocation = MethodInfo.PutInfo( - summary = "Location Test", - description = "A cool test", - requestInfo = RequestInfo( - description = "Cool stuff" - ), - responseInfo = ResponseInfo( - status = HttpStatusCode.OK, - description = "A successful endeavor" - ) - ) - val testDeleteNestedLocation = MethodInfo.DeleteInfo( - summary = "Location Test", - description = "A cool test", - responseInfo = ResponseInfo( - status = HttpStatusCode.OK, - description = "A successful endeavor" - ) - ) - } -} - -@Location("/test/{name}") -data class SimpleLoc(@KompendiumParam(ParamType.PATH) val name: String) { - @Location("/nesty") - data class NestedLoc(@KompendiumParam(ParamType.QUERY) val isCool: Boolean, val parent: SimpleLoc) -} - -data class SimpleResponse(val result: Boolean) -data class SimpleRequest(val input: String) +}) diff --git a/kompendium-locations/src/test/kotlin/io/bkbn/kompendium/locations/util/TestData.kt b/kompendium-locations/src/test/kotlin/io/bkbn/kompendium/locations/util/TestData.kt deleted file mode 100644 index a94fe22db..000000000 --- a/kompendium-locations/src/test/kotlin/io/bkbn/kompendium/locations/util/TestData.kt +++ /dev/null @@ -1,11 +0,0 @@ -package io.bkbn.kompendium.locations.util - -import java.io.File - -object TestData { - fun getFileSnapshot(fileName: String): String { - val snapshotPath = "src/test/resources" - val file = File("$snapshotPath/$fileName") - return file.readText() - } -} diff --git a/kompendium-locations/src/test/kotlin/io/bkbn/kompendium/locations/util/TestModels.kt b/kompendium-locations/src/test/kotlin/io/bkbn/kompendium/locations/util/TestModels.kt index 7fe8085db..e07412131 100644 --- a/kompendium-locations/src/test/kotlin/io/bkbn/kompendium/locations/util/TestModels.kt +++ b/kompendium-locations/src/test/kotlin/io/bkbn/kompendium/locations/util/TestModels.kt @@ -1,2 +1,14 @@ package io.bkbn.kompendium.locations.util +import io.bkbn.kompendium.annotations.Param +import io.bkbn.kompendium.annotations.ParamType +import io.ktor.locations.Location + +@Location("/test/{name}") +data class SimpleLoc(@Param(ParamType.PATH) val name: String) { + @Location("/nesty") + data class NestedLoc(@Param(ParamType.QUERY) val isCool: Boolean, val parent: SimpleLoc) +} + +data class SimpleResponse(val result: Boolean) +data class SimpleRequest(val input: String) diff --git a/kompendium-locations/src/test/kotlin/io/bkbn/kompendium/locations/util/TestModules.kt b/kompendium-locations/src/test/kotlin/io/bkbn/kompendium/locations/util/TestModules.kt new file mode 100644 index 000000000..b7382f3b7 --- /dev/null +++ b/kompendium-locations/src/test/kotlin/io/bkbn/kompendium/locations/util/TestModules.kt @@ -0,0 +1,97 @@ +package io.bkbn.kompendium.locations.util + +import io.bkbn.kompendium.locations.NotarizedLocation.notarizedDelete +import io.bkbn.kompendium.locations.NotarizedLocation.notarizedGet +import io.bkbn.kompendium.locations.NotarizedLocation.notarizedPost +import io.bkbn.kompendium.locations.NotarizedLocation.notarizedPut +import io.ktor.application.Application +import io.ktor.application.call +import io.ktor.application.install +import io.ktor.locations.Locations +import io.ktor.response.respondText +import io.ktor.routing.route +import io.ktor.routing.routing + +fun Application.locationsConfig() { + install(Locations) +} + +fun Application.notarizedGetSimpleLocation() { + routing { + route("/test") { + notarizedGet(TestResponseInfo.testGetSimpleLocation) { + call.respondText { "hey dude ‼️ congratz on the get request" } + } + } + } +} + +fun Application.notarizedGetNestedLocation() { + routing { + route("/test") { + notarizedGet(TestResponseInfo.testGetNestedLocation) { + call.respondText { "hey dude ‼️ congratz on the get request" } + } + } + } +} + +fun Application.notarizedPostSimpleLocation() { + routing { + route("/test") { + notarizedPost(TestResponseInfo.testPostSimpleLocation) { + call.respondText { "hey dude ‼️ congratz on the get request" } + } + } + } +} + +fun Application.notarizedPostNestedLocation() { + routing { + route("/test") { + notarizedPost(TestResponseInfo.testPostNestedLocation) { + call.respondText { "hey dude ‼️ congratz on the get request" } + } + } + } +} + +fun Application.notarizedPutSimpleLocation() { + routing { + route("/test") { + notarizedPut(TestResponseInfo.testPutSimpleLocation) { + call.respondText { "hey dude ‼️ congratz on the get request" } + } + } + } +} + +fun Application.notarizedPutNestedLocation() { + routing { + route("/test") { + notarizedPut(TestResponseInfo.testPutNestedLocation) { + call.respondText { "hey dude ‼️ congratz on the get request" } + } + } + } +} + +fun Application.notarizedDeleteSimpleLocation() { + routing { + route("/test") { + notarizedDelete(TestResponseInfo.testDeleteSimpleLocation) { + call.respondText { "hey dude ‼️ congratz on the get request" } + } + } + } +} + +fun Application.notarizedDeleteNestedLocation() { + routing { + route("/test") { + notarizedDelete(TestResponseInfo.testDeleteNestedLocation) { + call.respondText { "hey dude ‼️ congratz on the get request" } + } + } + } +} diff --git a/kompendium-locations/src/test/kotlin/io/bkbn/kompendium/locations/util/TestResponseInfo.kt b/kompendium-locations/src/test/kotlin/io/bkbn/kompendium/locations/util/TestResponseInfo.kt new file mode 100644 index 000000000..a01513fed --- /dev/null +++ b/kompendium-locations/src/test/kotlin/io/bkbn/kompendium/locations/util/TestResponseInfo.kt @@ -0,0 +1,89 @@ +package io.bkbn.kompendium.locations.util + +import io.bkbn.kompendium.core.metadata.method.MethodInfo +import io.bkbn.kompendium.core.metadata.RequestInfo +import io.bkbn.kompendium.core.metadata.ResponseInfo +import io.bkbn.kompendium.core.metadata.method.DeleteInfo +import io.bkbn.kompendium.core.metadata.method.GetInfo +import io.bkbn.kompendium.core.metadata.method.PostInfo +import io.bkbn.kompendium.core.metadata.method.PutInfo +import io.ktor.http.HttpStatusCode + +object TestResponseInfo { + val testGetSimpleLocation = GetInfo( + summary = "Location Test", + description = "A cool test", + responseInfo = ResponseInfo( + status = HttpStatusCode.OK, + description = "A successful endeavor" + ) + ) + val testPostSimpleLocation = PostInfo( + summary = "Location Test", + description = "A cool test", + requestInfo = RequestInfo( + description = "Cool stuff" + ), + responseInfo = ResponseInfo( + status = HttpStatusCode.OK, + description = "A successful endeavor" + ) + ) + val testPutSimpleLocation = PutInfo( + summary = "Location Test", + description = "A cool test", + requestInfo = RequestInfo( + description = "Cool stuff" + ), + responseInfo = ResponseInfo( + status = HttpStatusCode.OK, + description = "A successful endeavor" + ) + ) + val testDeleteSimpleLocation = DeleteInfo( + summary = "Location Test", + description = "A cool test", + responseInfo = ResponseInfo( + status = HttpStatusCode.OK, + description = "A successful endeavor" + ) + ) + val testGetNestedLocation = GetInfo( + summary = "Location Test", + description = "A cool test", + responseInfo = ResponseInfo( + status = HttpStatusCode.OK, + description = "A successful endeavor" + ) + ) + val testPostNestedLocation = PostInfo( + summary = "Location Test", + description = "A cool test", + requestInfo = RequestInfo( + description = "Cool stuff" + ), + responseInfo = ResponseInfo( + status = HttpStatusCode.OK, + description = "A successful endeavor" + ) + ) + val testPutNestedLocation = PutInfo( + summary = "Location Test", + description = "A cool test", + requestInfo = RequestInfo( + description = "Cool stuff" + ), + responseInfo = ResponseInfo( + status = HttpStatusCode.OK, + description = "A successful endeavor" + ) + ) + val testDeleteNestedLocation = DeleteInfo( + summary = "Location Test", + description = "A cool test", + responseInfo = ResponseInfo( + status = HttpStatusCode.OK, + description = "A successful endeavor" + ) + ) +} diff --git a/kompendium-locations/src/test/resources/notarized_delete_nested_location.json b/kompendium-locations/src/test/resources/notarized_delete_nested_location.json index 3108d4167..65dead71f 100644 --- a/kompendium-locations/src/test/resources/notarized_delete_nested_location.json +++ b/kompendium-locations/src/test/resources/notarized_delete_nested_location.json @@ -1,65 +1,74 @@ { - "openapi" : "3.0.3", - "info" : { }, - "servers" : [ ], - "paths" : { - "/test/test/{name}/nesty" : { - "delete" : { - "tags" : [ ], - "summary" : "Location Test", - "description" : "A cool test", - "parameters" : [ { - "name" : "isCool", - "in" : "query", - "schema" : { - "type" : "boolean" - }, - "required" : true, - "deprecated" : false - } ], - "responses" : { - "200" : { - "description" : "A successful endeavor", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/SimpleResponse" + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" + }, + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + } + }, + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/test/test/{name}/nesty": { + "delete": { + "tags": [], + "summary": "Location Test", + "description": "A cool test", + "parameters": [ + { + "name": "isCool", + "in": "query", + "schema": { + "type": "boolean" + }, + "required": true, + "deprecated": false + } + ], + "responses": { + "200": { + "description": "A successful endeavor", + "content": { + "application/json": { + "schema": { + "properties": { + "result": { + "type": "boolean" + } + }, + "required": [ + "result" + ], + "type": "object" } } } } }, - "deprecated" : false + "deprecated": false } } }, - "components" : { - "schemas" : { - "Boolean" : { - "type" : "boolean" - }, - "SimpleResponse" : { - "type" : "object", - "properties" : { - "result" : { - "$ref" : "#/components/schemas/Boolean" - } - } - }, - "String" : { - "type" : "string" - }, - "SimpleLoc" : { - "type" : "object", - "properties" : { - "name" : { - "$ref" : "#/components/schemas/String" - } - } - } - }, - "securitySchemes" : { } + "components": { + "securitySchemes": {} }, - "security" : [ ], - "tags" : [ ] + "security": [], + "tags": [] } diff --git a/kompendium-locations/src/test/resources/notarized_delete_simple_location.json b/kompendium-locations/src/test/resources/notarized_delete_simple_location.json index 6fc4f75de..85cc87104 100644 --- a/kompendium-locations/src/test/resources/notarized_delete_simple_location.json +++ b/kompendium-locations/src/test/resources/notarized_delete_simple_location.json @@ -1,57 +1,74 @@ { - "openapi" : "3.0.3", - "info" : { }, - "servers" : [ ], - "paths" : { - "/test/test/{name}" : { - "delete" : { - "tags" : [ ], - "summary" : "Location Test", - "description" : "A cool test", - "parameters" : [ { - "name" : "name", - "in" : "path", - "schema" : { - "type" : "string" - }, - "required" : true, - "deprecated" : false - } ], - "responses" : { - "200" : { - "description" : "A successful endeavor", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/SimpleResponse" + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" + }, + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + } + }, + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/test/test/{name}": { + "delete": { + "tags": [], + "summary": "Location Test", + "description": "A cool test", + "parameters": [ + { + "name": "name", + "in": "path", + "schema": { + "type": "string" + }, + "required": true, + "deprecated": false + } + ], + "responses": { + "200": { + "description": "A successful endeavor", + "content": { + "application/json": { + "schema": { + "properties": { + "result": { + "type": "boolean" + } + }, + "required": [ + "result" + ], + "type": "object" } } } } }, - "deprecated" : false + "deprecated": false } } }, - "components" : { - "schemas" : { - "Boolean" : { - "type" : "boolean" - }, - "SimpleResponse" : { - "type" : "object", - "properties" : { - "result" : { - "$ref" : "#/components/schemas/Boolean" - } - } - }, - "String" : { - "type" : "string" - } - }, - "securitySchemes" : { } + "components": { + "securitySchemes": {} }, - "security" : [ ], - "tags" : [ ] + "security": [], + "tags": [] } diff --git a/kompendium-locations/src/test/resources/notarized_get_nested_location.json b/kompendium-locations/src/test/resources/notarized_get_nested_location.json index c927f42d5..3e864c610 100644 --- a/kompendium-locations/src/test/resources/notarized_get_nested_location.json +++ b/kompendium-locations/src/test/resources/notarized_get_nested_location.json @@ -1,65 +1,74 @@ { - "openapi" : "3.0.3", - "info" : { }, - "servers" : [ ], - "paths" : { - "/test/test/{name}/nesty" : { - "get" : { - "tags" : [ ], - "summary" : "Location Test", - "description" : "A cool test", - "parameters" : [ { - "name" : "isCool", - "in" : "query", - "schema" : { - "type" : "boolean" - }, - "required" : true, - "deprecated" : false - } ], - "responses" : { - "200" : { - "description" : "A successful endeavor", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/SimpleResponse" + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" + }, + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + } + }, + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/test/test/{name}/nesty": { + "get": { + "tags": [], + "summary": "Location Test", + "description": "A cool test", + "parameters": [ + { + "name": "isCool", + "in": "query", + "schema": { + "type": "boolean" + }, + "required": true, + "deprecated": false + } + ], + "responses": { + "200": { + "description": "A successful endeavor", + "content": { + "application/json": { + "schema": { + "properties": { + "result": { + "type": "boolean" + } + }, + "required": [ + "result" + ], + "type": "object" } } } } }, - "deprecated" : false + "deprecated": false } } }, - "components" : { - "schemas" : { - "Boolean" : { - "type" : "boolean" - }, - "SimpleResponse" : { - "type" : "object", - "properties" : { - "result" : { - "$ref" : "#/components/schemas/Boolean" - } - } - }, - "String" : { - "type" : "string" - }, - "SimpleLoc" : { - "type" : "object", - "properties" : { - "name" : { - "$ref" : "#/components/schemas/String" - } - } - } - }, - "securitySchemes" : { } + "components": { + "securitySchemes": {} }, - "security" : [ ], - "tags" : [ ] + "security": [], + "tags": [] } diff --git a/kompendium-locations/src/test/resources/notarized_get_simple_location.json b/kompendium-locations/src/test/resources/notarized_get_simple_location.json index 2a2fba318..5ae6eb0df 100644 --- a/kompendium-locations/src/test/resources/notarized_get_simple_location.json +++ b/kompendium-locations/src/test/resources/notarized_get_simple_location.json @@ -1,57 +1,74 @@ { - "openapi" : "3.0.3", - "info" : { }, - "servers" : [ ], - "paths" : { - "/test/test/{name}" : { - "get" : { - "tags" : [ ], - "summary" : "Location Test", - "description" : "A cool test", - "parameters" : [ { - "name" : "name", - "in" : "path", - "schema" : { - "type" : "string" - }, - "required" : true, - "deprecated" : false - } ], - "responses" : { - "200" : { - "description" : "A successful endeavor", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/SimpleResponse" + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" + }, + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + } + }, + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/test/test/{name}": { + "get": { + "tags": [], + "summary": "Location Test", + "description": "A cool test", + "parameters": [ + { + "name": "name", + "in": "path", + "schema": { + "type": "string" + }, + "required": true, + "deprecated": false + } + ], + "responses": { + "200": { + "description": "A successful endeavor", + "content": { + "application/json": { + "schema": { + "properties": { + "result": { + "type": "boolean" + } + }, + "required": [ + "result" + ], + "type": "object" } } } } }, - "deprecated" : false + "deprecated": false } } }, - "components" : { - "schemas" : { - "Boolean" : { - "type" : "boolean" - }, - "SimpleResponse" : { - "type" : "object", - "properties" : { - "result" : { - "$ref" : "#/components/schemas/Boolean" - } - } - }, - "String" : { - "type" : "string" - } - }, - "securitySchemes" : { } + "components": { + "securitySchemes": {} }, - "security" : [ ], - "tags" : [ ] + "security": [], + "tags": [] } diff --git a/kompendium-locations/src/test/resources/notarized_post_nested_location.json b/kompendium-locations/src/test/resources/notarized_post_nested_location.json index da1a204e2..a01bdb8ea 100644 --- a/kompendium-locations/src/test/resources/notarized_post_nested_location.json +++ b/kompendium-locations/src/test/resources/notarized_post_nested_location.json @@ -1,84 +1,93 @@ { - "openapi" : "3.0.3", - "info" : { }, - "servers" : [ ], - "paths" : { - "/test/test/{name}/nesty" : { - "post" : { - "tags" : [ ], - "summary" : "Location Test", - "description" : "A cool test", - "parameters" : [ { - "name" : "isCool", - "in" : "query", - "schema" : { - "type" : "boolean" - }, - "required" : true, - "deprecated" : false - } ], - "requestBody" : { - "description" : "Cool stuff", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/SimpleRequest" + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" + }, + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + } + }, + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/test/test/{name}/nesty": { + "post": { + "tags": [], + "summary": "Location Test", + "description": "A cool test", + "parameters": [ + { + "name": "isCool", + "in": "query", + "schema": { + "type": "boolean" + }, + "required": true, + "deprecated": false + } + ], + "requestBody": { + "description": "Cool stuff", + "content": { + "application/json": { + "schema": { + "properties": { + "input": { + "type": "string" + } + }, + "required": [ + "input" + ], + "type": "object" } } }, - "required" : false + "required": true }, - "responses" : { - "200" : { - "description" : "A successful endeavor", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/SimpleResponse" + "responses": { + "200": { + "description": "A successful endeavor", + "content": { + "application/json": { + "schema": { + "properties": { + "result": { + "type": "boolean" + } + }, + "required": [ + "result" + ], + "type": "object" } } } } }, - "deprecated" : false + "deprecated": false } } }, - "components" : { - "schemas" : { - "String" : { - "type" : "string" - }, - "SimpleRequest" : { - "type" : "object", - "properties" : { - "input" : { - "$ref" : "#/components/schemas/String" - } - } - }, - "Boolean" : { - "type" : "boolean" - }, - "SimpleResponse" : { - "type" : "object", - "properties" : { - "result" : { - "$ref" : "#/components/schemas/Boolean" - } - } - }, - "SimpleLoc" : { - "type" : "object", - "properties" : { - "name" : { - "$ref" : "#/components/schemas/String" - } - } - } - }, - "securitySchemes" : { } + "components": { + "securitySchemes": {} }, - "security" : [ ], - "tags" : [ ] + "security": [], + "tags": [] } diff --git a/kompendium-locations/src/test/resources/notarized_post_simple_location.json b/kompendium-locations/src/test/resources/notarized_post_simple_location.json index d1852c1c0..d8dab1467 100644 --- a/kompendium-locations/src/test/resources/notarized_post_simple_location.json +++ b/kompendium-locations/src/test/resources/notarized_post_simple_location.json @@ -1,76 +1,93 @@ { - "openapi" : "3.0.3", - "info" : { }, - "servers" : [ ], - "paths" : { - "/test/test/{name}" : { - "post" : { - "tags" : [ ], - "summary" : "Location Test", - "description" : "A cool test", - "parameters" : [ { - "name" : "name", - "in" : "path", - "schema" : { - "type" : "string" - }, - "required" : true, - "deprecated" : false - } ], - "requestBody" : { - "description" : "Cool stuff", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/SimpleRequest" + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" + }, + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + } + }, + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/test/test/{name}": { + "post": { + "tags": [], + "summary": "Location Test", + "description": "A cool test", + "parameters": [ + { + "name": "name", + "in": "path", + "schema": { + "type": "string" + }, + "required": true, + "deprecated": false + } + ], + "requestBody": { + "description": "Cool stuff", + "content": { + "application/json": { + "schema": { + "properties": { + "input": { + "type": "string" + } + }, + "required": [ + "input" + ], + "type": "object" } } }, - "required" : false + "required": true }, - "responses" : { - "200" : { - "description" : "A successful endeavor", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/SimpleResponse" + "responses": { + "200": { + "description": "A successful endeavor", + "content": { + "application/json": { + "schema": { + "properties": { + "result": { + "type": "boolean" + } + }, + "required": [ + "result" + ], + "type": "object" } } } } }, - "deprecated" : false + "deprecated": false } } }, - "components" : { - "schemas" : { - "String" : { - "type" : "string" - }, - "SimpleRequest" : { - "type" : "object", - "properties" : { - "input" : { - "$ref" : "#/components/schemas/String" - } - } - }, - "Boolean" : { - "type" : "boolean" - }, - "SimpleResponse" : { - "type" : "object", - "properties" : { - "result" : { - "$ref" : "#/components/schemas/Boolean" - } - } - } - }, - "securitySchemes" : { } + "components": { + "securitySchemes": {} }, - "security" : [ ], - "tags" : [ ] + "security": [], + "tags": [] } diff --git a/kompendium-locations/src/test/resources/notarized_put_nested_location.json b/kompendium-locations/src/test/resources/notarized_put_nested_location.json index 583158369..d9c989bb2 100644 --- a/kompendium-locations/src/test/resources/notarized_put_nested_location.json +++ b/kompendium-locations/src/test/resources/notarized_put_nested_location.json @@ -1,84 +1,93 @@ { - "openapi" : "3.0.3", - "info" : { }, - "servers" : [ ], - "paths" : { - "/test/test/{name}/nesty" : { - "put" : { - "tags" : [ ], - "summary" : "Location Test", - "description" : "A cool test", - "parameters" : [ { - "name" : "isCool", - "in" : "query", - "schema" : { - "type" : "boolean" - }, - "required" : true, - "deprecated" : false - } ], - "requestBody" : { - "description" : "Cool stuff", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/SimpleRequest" + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" + }, + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + } + }, + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/test/test/{name}/nesty": { + "put": { + "tags": [], + "summary": "Location Test", + "description": "A cool test", + "parameters": [ + { + "name": "isCool", + "in": "query", + "schema": { + "type": "boolean" + }, + "required": true, + "deprecated": false + } + ], + "requestBody": { + "description": "Cool stuff", + "content": { + "application/json": { + "schema": { + "properties": { + "input": { + "type": "string" + } + }, + "required": [ + "input" + ], + "type": "object" } } }, - "required" : false + "required": true }, - "responses" : { - "200" : { - "description" : "A successful endeavor", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/SimpleResponse" + "responses": { + "200": { + "description": "A successful endeavor", + "content": { + "application/json": { + "schema": { + "properties": { + "result": { + "type": "boolean" + } + }, + "required": [ + "result" + ], + "type": "object" } } } } }, - "deprecated" : false + "deprecated": false } } }, - "components" : { - "schemas" : { - "String" : { - "type" : "string" - }, - "SimpleRequest" : { - "type" : "object", - "properties" : { - "input" : { - "$ref" : "#/components/schemas/String" - } - } - }, - "Boolean" : { - "type" : "boolean" - }, - "SimpleResponse" : { - "type" : "object", - "properties" : { - "result" : { - "$ref" : "#/components/schemas/Boolean" - } - } - }, - "SimpleLoc" : { - "type" : "object", - "properties" : { - "name" : { - "$ref" : "#/components/schemas/String" - } - } - } - }, - "securitySchemes" : { } + "components": { + "securitySchemes": {} }, - "security" : [ ], - "tags" : [ ] + "security": [], + "tags": [] } diff --git a/kompendium-locations/src/test/resources/notarized_put_simple_location.json b/kompendium-locations/src/test/resources/notarized_put_simple_location.json index 42e7ab42e..f2e141fc8 100644 --- a/kompendium-locations/src/test/resources/notarized_put_simple_location.json +++ b/kompendium-locations/src/test/resources/notarized_put_simple_location.json @@ -1,76 +1,93 @@ { - "openapi" : "3.0.3", - "info" : { }, - "servers" : [ ], - "paths" : { - "/test/test/{name}" : { - "put" : { - "tags" : [ ], - "summary" : "Location Test", - "description" : "A cool test", - "parameters" : [ { - "name" : "name", - "in" : "path", - "schema" : { - "type" : "string" - }, - "required" : true, - "deprecated" : false - } ], - "requestBody" : { - "description" : "Cool stuff", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/SimpleRequest" + "openapi": "3.0.3", + "info": { + "title": "Test API", + "version": "1.33.7", + "description": "An amazing, fully-ish 😉 generated API spec", + "termsOfService": "https://example.com", + "contact": { + "name": "Homer Simpson", + "url": "https://gph.is/1NPUDiM", + "email": "chunkylover53@aol.com" + }, + "license": { + "name": "MIT", + "url": "https://github.com/bkbnio/kompendium/blob/main/LICENSE" + } + }, + "servers": [ + { + "url": "https://myawesomeapi.com", + "description": "Production instance of my API" + }, + { + "url": "https://staging.myawesomeapi.com", + "description": "Where the fun stuff happens" + } + ], + "paths": { + "/test/test/{name}": { + "put": { + "tags": [], + "summary": "Location Test", + "description": "A cool test", + "parameters": [ + { + "name": "name", + "in": "path", + "schema": { + "type": "string" + }, + "required": true, + "deprecated": false + } + ], + "requestBody": { + "description": "Cool stuff", + "content": { + "application/json": { + "schema": { + "properties": { + "input": { + "type": "string" + } + }, + "required": [ + "input" + ], + "type": "object" } } }, - "required" : false + "required": true }, - "responses" : { - "200" : { - "description" : "A successful endeavor", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/SimpleResponse" + "responses": { + "200": { + "description": "A successful endeavor", + "content": { + "application/json": { + "schema": { + "properties": { + "result": { + "type": "boolean" + } + }, + "required": [ + "result" + ], + "type": "object" } } } } }, - "deprecated" : false + "deprecated": false } } }, - "components" : { - "schemas" : { - "String" : { - "type" : "string" - }, - "SimpleRequest" : { - "type" : "object", - "properties" : { - "input" : { - "$ref" : "#/components/schemas/String" - } - } - }, - "Boolean" : { - "type" : "boolean" - }, - "SimpleResponse" : { - "type" : "object", - "properties" : { - "result" : { - "$ref" : "#/components/schemas/Boolean" - } - } - } - }, - "securitySchemes" : { } + "components": { + "securitySchemes": {} }, - "security" : [ ], - "tags" : [ ] + "security": [], + "tags": [] } diff --git a/kompendium-oas/Module.md b/kompendium-oas/Module.md new file mode 100644 index 000000000..ad51e7480 --- /dev/null +++ b/kompendium-oas/Module.md @@ -0,0 +1,55 @@ +# Module kompendium-oas + +## Open Api Specification + +This module contains the models that represent the Open Api Specification 3.0 (OAS). + +It is a purely domain-based module, with no logic whatsoever. + +The specification can be found [here](https://swagger.io/specification). + +# Package io.bkbn.kompendium.oas + +This is the root package that contains the top level spec that is ultimately serialized into the specification JSON +payload. + +# Package io.bkbn.kompendium.oas.common + +Here we house data models that will be used across the module. + +# Package io.bkbn.kompendium.oas.component + +This package correlates to the OAS Component layer, which at the moment is relatively bare bones. It will just contain a +reference to any security schemas, as adding objects here as components severely limits future ability to add cool +features such as route level object validations. Got issues with that, bring it up with the Open API Team :) + +# Package io.bkbn.kompendium.oas.info + +This package houses the data models for information metadata such as contact and licensing info + +# Package io.bkbn.kompendium.oas.path + +Now we're getting to the good stuff. This is where the details on each path level operation will live. Your `gets`, +your `puts`, so on and so forth. + +# Package io.bkbn.kompendium.oas.payload + +This is another good one, this is where the actual payload types live. Request and response body specifications, +parameter details, collection support. That all lives here. + +# Package io.bkbn.kompendium.oas.schema + +A bit confusingly, in the OAS, there is a distinction between a payload and a schema. You can think of payloads as +containing schemas. So here we dive into the true object level definitions that we want to map out. Models for +supporting collections, dictionaries, polymorphic classes, enums, along with your standard library classes all live +here. + +# Package io.bkbn.kompendium.oas.security + +Separated from the core schema models are the models that represent security schemas. Despite being referred to as +schemas, and despite living as part of the component data structure, these models are drastically different from your +core data model schemas, and thus earn their own package + +# Package io.bkbn.kompendium.oas.server + +Here we detail any server information that you wish to attach to your specification diff --git a/kompendium-oas/build.gradle.kts b/kompendium-oas/build.gradle.kts new file mode 100644 index 000000000..57decae86 --- /dev/null +++ b/kompendium-oas/build.gradle.kts @@ -0,0 +1,3 @@ +plugins { + id("io.bkbn.sourdough.library") +} diff --git a/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/OpenApiSpec.kt b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/OpenApiSpec.kt new file mode 100644 index 000000000..c2169c508 --- /dev/null +++ b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/OpenApiSpec.kt @@ -0,0 +1,19 @@ +package io.bkbn.kompendium.oas + +import io.bkbn.kompendium.oas.common.ExternalDocumentation +import io.bkbn.kompendium.oas.common.Tag +import io.bkbn.kompendium.oas.component.Components +import io.bkbn.kompendium.oas.info.Info +import io.bkbn.kompendium.oas.path.Path +import io.bkbn.kompendium.oas.server.Server + +data class OpenApiSpec( + val openapi: String = "3.0.3", + val info: Info, + val servers: MutableList = mutableListOf(), + val paths: MutableMap = mutableMapOf(), + val components: Components = Components(), + val security: MutableList>> = mutableListOf(), + val tags: MutableList = mutableListOf(), + val externalDocs: ExternalDocumentation? = null +) diff --git a/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/common/ExternalDocumentation.kt b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/common/ExternalDocumentation.kt new file mode 100644 index 000000000..755a3e5ba --- /dev/null +++ b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/common/ExternalDocumentation.kt @@ -0,0 +1,8 @@ +package io.bkbn.kompendium.oas.common + +import java.net.URI + +data class ExternalDocumentation( + val url: URI, + val description: String? +) diff --git a/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/common/Tag.kt b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/common/Tag.kt new file mode 100644 index 000000000..5cc24c5f4 --- /dev/null +++ b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/common/Tag.kt @@ -0,0 +1,7 @@ +package io.bkbn.kompendium.oas.common + +data class Tag( + val name: String, + val description: String? = null, + val externalDocs: ExternalDocumentation? = null +) diff --git a/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/component/Components.kt b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/component/Components.kt new file mode 100644 index 000000000..9df9d7cab --- /dev/null +++ b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/component/Components.kt @@ -0,0 +1,7 @@ +package io.bkbn.kompendium.oas.component + +import io.bkbn.kompendium.oas.security.SecuritySchema + +data class Components( + val securitySchemes: MutableMap = mutableMapOf() +) diff --git a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpecInfoContact.kt b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/info/Contact.kt similarity index 61% rename from kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpecInfoContact.kt rename to kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/info/Contact.kt index 1938b0a5d..3d84d3db8 100644 --- a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpecInfoContact.kt +++ b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/info/Contact.kt @@ -1,8 +1,8 @@ -package io.bkbn.kompendium.models.oas +package io.bkbn.kompendium.oas.info import java.net.URI -data class OpenApiSpecInfoContact( +data class Contact( var name: String, var url: URI? = null, var email: String? = null // TODO Enforce email? diff --git a/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/info/Info.kt b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/info/Info.kt new file mode 100644 index 000000000..32b8c9307 --- /dev/null +++ b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/info/Info.kt @@ -0,0 +1,12 @@ +package io.bkbn.kompendium.oas.info + +import java.net.URI + +data class Info( + var title: String? = null, + var version: String? = null, + var description: String? = null, + var termsOfService: URI? = null, + var contact: Contact? = null, + var license: License? = null +) diff --git a/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/info/License.kt b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/info/License.kt new file mode 100644 index 000000000..37e030d7a --- /dev/null +++ b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/info/License.kt @@ -0,0 +1,8 @@ +package io.bkbn.kompendium.oas.info + +import java.net.URI + +data class License( + var name: String, + var url: URI? = null +) diff --git a/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/path/Path.kt b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/path/Path.kt new file mode 100644 index 000000000..a8b0a617c --- /dev/null +++ b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/path/Path.kt @@ -0,0 +1,17 @@ +package io.bkbn.kompendium.oas.path + +import io.bkbn.kompendium.oas.payload.Parameter +import io.bkbn.kompendium.oas.server.Server + +data class Path( + var get: PathOperation? = null, + var put: PathOperation? = null, + var post: PathOperation? = null, + var delete: PathOperation? = null, + var options: PathOperation? = null, + var head: PathOperation? = null, + var patch: PathOperation? = null, + var trace: PathOperation? = null, + var servers: List? = null, + var parameters: List? = null +) diff --git a/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/path/PathOperation.kt b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/path/PathOperation.kt new file mode 100644 index 000000000..5bb7473bb --- /dev/null +++ b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/path/PathOperation.kt @@ -0,0 +1,25 @@ +package io.bkbn.kompendium.oas.path + +import io.bkbn.kompendium.oas.common.ExternalDocumentation +import io.bkbn.kompendium.oas.payload.Parameter +import io.bkbn.kompendium.oas.payload.Payload +import io.bkbn.kompendium.oas.payload.Request +import io.bkbn.kompendium.oas.payload.Response +import io.bkbn.kompendium.oas.server.Server + +data class PathOperation( + var tags: Set = emptySet(), + var summary: String? = null, + var description: String? = null, + var externalDocs: ExternalDocumentation? = null, + var operationId: String? = null, + var parameters: List? = null, + var requestBody: Request<*>? = null, + // TODO How to enforce `default` requirement 🧐 + var responses: Map>? = null, + var callbacks: Map? = null, // todo what is this? + var deprecated: Boolean = false, + var security: List>>? = null, + var servers: List? = null, + var `x-codegen-request-body-name`: String? = null +) diff --git a/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/payload/AnyOfPayload.kt b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/payload/AnyOfPayload.kt new file mode 100644 index 000000000..8a061a6b9 --- /dev/null +++ b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/payload/AnyOfPayload.kt @@ -0,0 +1,5 @@ +package io.bkbn.kompendium.oas.payload + +import io.bkbn.kompendium.oas.schema.ComponentSchema + +data class AnyOfPayload(val anyOf: List) : Payload diff --git a/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/payload/MediaType.kt b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/payload/MediaType.kt new file mode 100644 index 000000000..a4404b37f --- /dev/null +++ b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/payload/MediaType.kt @@ -0,0 +1,10 @@ +package io.bkbn.kompendium.oas.payload + +import io.bkbn.kompendium.oas.schema.ComponentSchema + +data class MediaType( + val schema: ComponentSchema, + val examples: Map>? = null +) { + data class Example(val value: T) +} diff --git a/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/payload/Parameter.kt b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/payload/Parameter.kt new file mode 100644 index 000000000..5fe191bb3 --- /dev/null +++ b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/payload/Parameter.kt @@ -0,0 +1,15 @@ +package io.bkbn.kompendium.oas.payload + +import io.bkbn.kompendium.oas.schema.ComponentSchema + +data class Parameter( + val name: String, + val `in`: String, // TODO Enum? "query", "header", "path" or "cookie" + val schema: ComponentSchema, + val description: String? = null, + val required: Boolean = true, + val deprecated: Boolean = false, + val allowEmptyValue: Boolean? = null, + val style: String? = null, + val explode: Boolean? = null +) diff --git a/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/payload/Payload.kt b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/payload/Payload.kt new file mode 100644 index 000000000..8e76771fb --- /dev/null +++ b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/payload/Payload.kt @@ -0,0 +1,3 @@ +package io.bkbn.kompendium.oas.payload + +sealed interface Payload diff --git a/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/payload/Request.kt b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/payload/Request.kt new file mode 100644 index 000000000..60aae099c --- /dev/null +++ b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/payload/Request.kt @@ -0,0 +1,7 @@ +package io.bkbn.kompendium.oas.payload + +data class Request( + val description: String?, + val content: Map>, + val required: Boolean = false +) : Payload diff --git a/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/payload/Response.kt b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/payload/Response.kt new file mode 100644 index 000000000..b6fde9b57 --- /dev/null +++ b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/payload/Response.kt @@ -0,0 +1,8 @@ +package io.bkbn.kompendium.oas.payload + +data class Response( + val description: String? = null, + val headers: Map? = null, + val content: Map>? = null, + val links: Map? = null +) : Payload diff --git a/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/schema/AnyOfSchema.kt b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/schema/AnyOfSchema.kt new file mode 100644 index 000000000..acf6b319f --- /dev/null +++ b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/schema/AnyOfSchema.kt @@ -0,0 +1,3 @@ +package io.bkbn.kompendium.oas.schema + +data class AnyOfSchema(val anyOf: List, override val description: String? = null) : ComponentSchema diff --git a/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/schema/ArraySchema.kt b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/schema/ArraySchema.kt new file mode 100644 index 000000000..2aec11761 --- /dev/null +++ b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/schema/ArraySchema.kt @@ -0,0 +1,14 @@ +package io.bkbn.kompendium.oas.schema + +data class ArraySchema( + val items: ComponentSchema, + override val default: Any? = null, + override val description: String? = null, + override val nullable: Boolean? = null, + // constraints + val minItems: Int? = null, + val maxItems: Int? = null, + val uniqueItems: Boolean? = null +) : TypedSchema { + override val type: String = "array" +} diff --git a/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/schema/ComponentSchema.kt b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/schema/ComponentSchema.kt new file mode 100644 index 000000000..ea88a3041 --- /dev/null +++ b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/schema/ComponentSchema.kt @@ -0,0 +1,31 @@ +package io.bkbn.kompendium.oas.schema + +sealed interface ComponentSchema { + val description: String? + get() = null + + val default: Any? + get() = null + + fun addDefault(default: Any?): ComponentSchema = when (this) { + is AnyOfSchema -> error("Cannot add default to anyOf reference") // todo is this true though? + is ArraySchema -> this.copy(default = default) + is DictionarySchema -> this.copy(default = default) + is EnumSchema -> this.copy(default = default) + is FormattedSchema -> this.copy(default = default) + is ObjectSchema -> this.copy(default = default) + is SimpleSchema -> this.copy(default = default) + else -> error("Compiler bug??") + } + + fun setDescription(description: String): ComponentSchema = when (this) { + is AnyOfSchema -> this.copy(description = description) + is ArraySchema -> this.copy(description = description) + is DictionarySchema -> this.copy(description = description) + is EnumSchema -> this.copy(description = description) + is FormattedSchema -> this.copy(description = description) + is ObjectSchema -> this.copy(description = description) + is SimpleSchema -> this.copy(description = description) + else -> error("Compiler bug??") + } +} diff --git a/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/schema/DictionarySchema.kt b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/schema/DictionarySchema.kt new file mode 100644 index 000000000..f0868ce3d --- /dev/null +++ b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/schema/DictionarySchema.kt @@ -0,0 +1,10 @@ +package io.bkbn.kompendium.oas.schema + +data class DictionarySchema( + val additionalProperties: ComponentSchema, + override val default: Any? = null, + override val description: String? = null, + override val nullable: Boolean? = null +) : TypedSchema { + override val type: String = "object" +} diff --git a/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/schema/EnumSchema.kt b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/schema/EnumSchema.kt new file mode 100644 index 000000000..2852a8c00 --- /dev/null +++ b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/schema/EnumSchema.kt @@ -0,0 +1,10 @@ +package io.bkbn.kompendium.oas.schema + +data class EnumSchema( + val `enum`: Set, + override val default: Any? = null, + override val description: String? = null, + override val nullable: Boolean? = null +) : TypedSchema { + override val type: String = "string" +} diff --git a/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/schema/FormattedSchema.kt b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/schema/FormattedSchema.kt new file mode 100644 index 000000000..3aecbba53 --- /dev/null +++ b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/schema/FormattedSchema.kt @@ -0,0 +1,15 @@ +package io.bkbn.kompendium.oas.schema + +data class FormattedSchema( + val format: String, + override val type: String, + override val default: Any? = null, + override val description: String? = null, + override val nullable: Boolean? = null, + // Constraints + val minimum: Number? = null, + val maximum: Number? = null, + val exclusiveMinimum: Boolean? = null, + val exclusiveMaximum: Boolean? = null, + val multipleOf: Number? = null, +) : TypedSchema diff --git a/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/schema/FreeFormSchema.kt b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/schema/FreeFormSchema.kt new file mode 100644 index 000000000..c5e17d55f --- /dev/null +++ b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/schema/FreeFormSchema.kt @@ -0,0 +1,12 @@ +package io.bkbn.kompendium.oas.schema + +data class FreeFormSchema( + override val nullable: Boolean? = null, + // constraints + val minProperties: Int? = null, + val maxProperties: Int? = null +) : TypedSchema { + val additionalProperties: Boolean = true + override val type: String = "object" + override val default: Any? = null +} diff --git a/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/schema/ObjectSchema.kt b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/schema/ObjectSchema.kt new file mode 100644 index 000000000..17c02363d --- /dev/null +++ b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/schema/ObjectSchema.kt @@ -0,0 +1,12 @@ +package io.bkbn.kompendium.oas.schema + +data class ObjectSchema( + val properties: Map, + override val default: Any? = null, + override val description: String? = null, + override val nullable: Boolean? = null, + // constraints + val required: List? = null +) : TypedSchema { + override val type = "object" +} diff --git a/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/schema/SimpleSchema.kt b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/schema/SimpleSchema.kt new file mode 100644 index 000000000..13533c744 --- /dev/null +++ b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/schema/SimpleSchema.kt @@ -0,0 +1,13 @@ +package io.bkbn.kompendium.oas.schema + +data class SimpleSchema( + override val type: String, + override val default: Any? = null, + override val description: String? = null, + override val nullable: Boolean? = null, + // Constraints + val minLength: Int? = null, + val maxLength: Int? = null, + val pattern: String? = null, + val format: String? = null +) : TypedSchema diff --git a/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/schema/TypedSchema.kt b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/schema/TypedSchema.kt new file mode 100644 index 000000000..6a3adf5ce --- /dev/null +++ b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/schema/TypedSchema.kt @@ -0,0 +1,7 @@ +package io.bkbn.kompendium.oas.schema + +sealed interface TypedSchema : ComponentSchema { + val type: String + val nullable: Boolean? + override val default: Any? +} diff --git a/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/security/ApiKeyAuth.kt b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/security/ApiKeyAuth.kt new file mode 100644 index 000000000..64960ebd8 --- /dev/null +++ b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/security/ApiKeyAuth.kt @@ -0,0 +1,18 @@ +package io.bkbn.kompendium.oas.security + +import java.util.Locale + +// TODO... is there even an official ktor api auth mechanism?? + +@Suppress("UnusedPrivateMember") +class ApiKeyAuth(val `in`: ApiKeyLocation, name: String) : SecuritySchema { + val type: String = "apiKey" + + enum class ApiKeyLocation { + HEADER, + QUERY, + COOKIE; + + override fun toString(): String = name.lowercase(Locale.getDefault()) + } +} diff --git a/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/security/BasicAuth.kt b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/security/BasicAuth.kt new file mode 100644 index 000000000..7d1649b75 --- /dev/null +++ b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/security/BasicAuth.kt @@ -0,0 +1,6 @@ +package io.bkbn.kompendium.oas.security + +class BasicAuth : SecuritySchema { + val type: String = "http" + val scheme: String = "basic" +} diff --git a/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/security/BearerAuth.kt b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/security/BearerAuth.kt new file mode 100644 index 000000000..07427ac29 --- /dev/null +++ b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/security/BearerAuth.kt @@ -0,0 +1,6 @@ +package io.bkbn.kompendium.oas.security + +data class BearerAuth(val bearerFormat: String? = null): SecuritySchema { + val type: String = "http" + val scheme: String = "bearer" +} diff --git a/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/security/OAuth.kt b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/security/OAuth.kt new file mode 100644 index 000000000..3a90fbb08 --- /dev/null +++ b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/security/OAuth.kt @@ -0,0 +1,49 @@ +package io.bkbn.kompendium.oas.security + +data class OAuth(val description: String? = null, val flows: Flows) : SecuritySchema { + val type: String = "oauth2" + + data class Flows( + val implicit: Implicit? = null, + val authorizationCode: AuthorizationCode? = null, + val password: Password? = null, + val clientCredentials: ClientCredential? = null, + ) { + + sealed interface Flow { + val authorizationUrl: String? + get() = null + val tokenUrl: String? + get() = null + val refreshUrl: String? + get() = null + val scopes: Map + get() = emptyMap() + } + + data class Implicit( + override val authorizationUrl: String, + override val refreshUrl: String? = null, + override val scopes: Map = emptyMap() + ) : Flow + + data class AuthorizationCode( + override val authorizationUrl: String, + override val tokenUrl: String? = null, + override val refreshUrl: String? = null, + override val scopes: Map = emptyMap() + ) : Flow + + data class Password( + override val tokenUrl: String? = null, + override val refreshUrl: String? = null, + override val scopes: Map = emptyMap() + ) : Flow + + data class ClientCredential( + override val tokenUrl: String? = null, + override val refreshUrl: String? = null, + override val scopes: Map = emptyMap() + ) : Flow + } +} diff --git a/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/security/SecuritySchema.kt b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/security/SecuritySchema.kt new file mode 100644 index 000000000..6f1d7ddf1 --- /dev/null +++ b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/security/SecuritySchema.kt @@ -0,0 +1,3 @@ +package io.bkbn.kompendium.oas.security + +sealed interface SecuritySchema diff --git a/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/server/Server.kt b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/server/Server.kt new file mode 100644 index 000000000..423b72a88 --- /dev/null +++ b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/server/Server.kt @@ -0,0 +1,9 @@ +package io.bkbn.kompendium.oas.server + +import java.net.URI + +data class Server( + val url: URI, + val description: String? = null, + var variables: Map? = null +) diff --git a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpecServerVariable.kt b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/server/ServerVariable.kt similarity index 58% rename from kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpecServerVariable.kt rename to kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/server/ServerVariable.kt index 1855a4fe9..ae1d076a0 100644 --- a/kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpecServerVariable.kt +++ b/kompendium-oas/src/main/kotlin/io/bkbn/kompendium/oas/server/ServerVariable.kt @@ -1,6 +1,6 @@ -package io.bkbn.kompendium.models.oas +package io.bkbn.kompendium.oas.server -data class OpenApiSpecServerVariable( +data class ServerVariable( val `enum`: Set, // todo enforce not empty val default: String, val description: String? diff --git a/kompendium-playground/Module.md b/kompendium-playground/Module.md new file mode 100644 index 000000000..00d0bd3f5 --- /dev/null +++ b/kompendium-playground/Module.md @@ -0,0 +1,3 @@ +# Module kompendium-playground + +This module contains a number of examples showcasing the capabilities of Kompendium diff --git a/kompendium-playground/build.gradle.kts b/kompendium-playground/build.gradle.kts index dd66268dc..ffaed5f46 100644 --- a/kompendium-playground/build.gradle.kts +++ b/kompendium-playground/build.gradle.kts @@ -1,33 +1,27 @@ plugins { - kotlin("plugin.serialization") version "1.5.0" + kotlin("plugin.serialization") version "1.6.0" application } dependencies { - implementation(platform("org.jetbrains.kotlin:kotlin-bom")) - implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8") - + // IMPLEMENTATION implementation(projects.kompendiumCore) implementation(projects.kompendiumAuth) implementation(projects.kompendiumLocations) implementation(projects.kompendiumSwaggerUi) - implementation(libs.bundles.ktor) - implementation(libs.ktor.jackson) - implementation(libs.kotlinx.serialization.json) - implementation(libs.ktor.serialization) - implementation(libs.bundles.ktorAuth) - implementation(libs.ktor.locations) - implementation(libs.bundles.logging) + // Ktor + val ktorVersion: String by project - implementation("joda-time:joda-time:2.10.13") + implementation(group = "io.ktor", name = "ktor-server-core", version = ktorVersion) + implementation(group = "io.ktor", name = "ktor-server-netty", version = ktorVersion) + implementation(group = "io.ktor", name = "ktor-auth", version = ktorVersion) + implementation(group = "io.ktor", name = "ktor-auth-jwt", version = ktorVersion) + implementation(group = "io.ktor", name = "ktor-serialization", version = ktorVersion) + implementation(group = "io.ktor", name = "ktor-locations", version = ktorVersion) + implementation(group = "io.ktor", name = "ktor-webjars", version = ktorVersion) - testImplementation("org.jetbrains.kotlin:kotlin-test") - testImplementation("org.jetbrains.kotlin:kotlin-test-junit") -} - -application { - @Suppress("DEPRECATION") - mainClassName = "io.bkbn.kompendium.playground.MainKt" - applicationDefaultJvmArgs = listOf("-Dio.ktor.development=true") // TODO I don't think this is working 😢 + implementation(group = "org.jetbrains.kotlinx", "kotlinx-serialization-json", version = "1.3.1") + + implementation(group = "joda-time", name = "joda-time", version = "2.10.13") } diff --git a/kompendium-playground/src/main/kotlin/io/bkbn/kompendium/playground/AuthPlayground.kt b/kompendium-playground/src/main/kotlin/io/bkbn/kompendium/playground/AuthPlayground.kt new file mode 100644 index 000000000..702ca4381 --- /dev/null +++ b/kompendium-playground/src/main/kotlin/io/bkbn/kompendium/playground/AuthPlayground.kt @@ -0,0 +1,130 @@ +package io.bkbn.kompendium.playground + +import io.bkbn.kompendium.auth.Notarized.notarizedAuthenticate +import io.bkbn.kompendium.auth.configuration.BasicAuthConfiguration +import io.bkbn.kompendium.core.Kompendium +import io.bkbn.kompendium.core.Notarized.notarizedGet +import io.bkbn.kompendium.core.metadata.ResponseInfo +import io.bkbn.kompendium.core.metadata.method.GetInfo +import io.bkbn.kompendium.core.routes.redoc +import io.bkbn.kompendium.oas.OpenApiSpec +import io.bkbn.kompendium.oas.info.Contact +import io.bkbn.kompendium.oas.info.Info +import io.bkbn.kompendium.oas.info.License +import io.bkbn.kompendium.oas.server.Server +import io.bkbn.kompendium.playground.AuthPlaygroundToC.simpleAuthenticatedGet +import io.ktor.application.Application +import io.ktor.application.call +import io.ktor.application.install +import io.ktor.auth.Authentication +import io.ktor.auth.UserIdPrincipal +import io.ktor.auth.basic +import io.ktor.features.ContentNegotiation +import io.ktor.http.HttpStatusCode +import io.ktor.response.respond +import io.ktor.routing.routing +import io.ktor.serialization.json +import io.ktor.server.engine.embeddedServer +import io.ktor.server.netty.Netty +import kotlinx.serialization.Serializable +import java.net.URI + +/** + * Application entrypoint. Run this and head on over to `localhost:8081/docs` + * to see some documented, authenticated routes. + */ +fun main() { + embeddedServer( + Netty, + port = 8081, + module = Application::mainModule + ).start(wait = true) +} + +// Application Module +private fun Application.mainModule() { + install(ContentNegotiation) { + json() + } + install(Kompendium) { + spec = AuthMetadata.spec + } + install(Authentication) { + // We can leverage the security config name to prevent typos + basic(SecurityConfigurations.basic.name) { + realm = "Access to the '/' path" + validate { credentials -> + if (credentials.name == "admin" && credentials.password == "foobar") { + UserIdPrincipal(credentials.name) + } else { + null + } + } + + } + } + routing { + redoc(pageTitle = "Authenticated API") + notarizedAuthenticate(SecurityConfigurations.basic) { + notarizedGet(simpleAuthenticatedGet) { + call.respond(HttpStatusCode.OK, AuthModels.SimpleAuthResponse(true)) + } + } + } +} + +object AuthMetadata { + val spec = OpenApiSpec( + info = Info( + title = "Simple API with documented Authentication", + version = "1.33.7", + description = "Wow isn't this cool?", + termsOfService = URI("https://example.com"), + contact = Contact( + name = "Homer Simpson", + email = "chunkylover53@aol.com", + url = URI("https://gph.is/1NPUDiM") + ), + license = License( + name = "MIT", + url = URI("https://github.com/bkbnio/kompendium/blob/main/LICENSE") + ) + ), + servers = mutableListOf( + Server( + url = URI("https://myawesomeapi.com"), + description = "Production instance of my API" + ), + Server( + url = URI("https://staging.myawesomeapi.com"), + description = "Where the fun stuff happens" + ) + ) + ) +} + +// This is where we define the available security configurations for our app +object SecurityConfigurations { + val basic = object : BasicAuthConfiguration { + override val name: String = "basic" + } +} + +// This is a table of contents to hold all the metadata for our various API endpoints +object AuthPlaygroundToC { + val simpleAuthenticatedGet = GetInfo( + summary = "Simple GET Request behind authentication", + description = "Can only make this request if you are a true OG", + responseInfo = ResponseInfo( + status = HttpStatusCode.OK, + description = "Proves that you are in fact an OG" + ), + tags = setOf("Authenticated"), + securitySchemes = setOf(SecurityConfigurations.basic.name) + ) +} + +object AuthModels { + @Serializable + data class SimpleAuthResponse(val isOG: Boolean) +} diff --git a/kompendium-playground/src/main/kotlin/io/bkbn/kompendium/playground/BasicPlayground.kt b/kompendium-playground/src/main/kotlin/io/bkbn/kompendium/playground/BasicPlayground.kt new file mode 100644 index 000000000..fb0449485 --- /dev/null +++ b/kompendium-playground/src/main/kotlin/io/bkbn/kompendium/playground/BasicPlayground.kt @@ -0,0 +1,213 @@ +package io.bkbn.kompendium.playground + +import io.bkbn.kompendium.annotations.Field +import io.bkbn.kompendium.annotations.Param +import io.bkbn.kompendium.annotations.ParamType +import io.bkbn.kompendium.core.Kompendium +import io.bkbn.kompendium.core.Notarized.notarizedDelete +import io.bkbn.kompendium.core.Notarized.notarizedGet +import io.bkbn.kompendium.core.Notarized.notarizedPost +import io.bkbn.kompendium.core.metadata.RequestInfo +import io.bkbn.kompendium.core.metadata.ResponseInfo +import io.bkbn.kompendium.core.metadata.method.DeleteInfo +import io.bkbn.kompendium.core.metadata.method.GetInfo +import io.bkbn.kompendium.core.metadata.method.PostInfo +import io.bkbn.kompendium.core.routes.redoc +import io.bkbn.kompendium.oas.OpenApiSpec +import io.bkbn.kompendium.oas.info.Contact +import io.bkbn.kompendium.oas.info.Info +import io.bkbn.kompendium.oas.info.License +import io.bkbn.kompendium.oas.server.Server +import io.bkbn.kompendium.playground.BasicModels.BasicParameters +import io.bkbn.kompendium.playground.BasicModels.BasicResponse +import io.bkbn.kompendium.playground.BasicModels.BasicRequest +import io.bkbn.kompendium.playground.BasicPlaygroundToC.simpleDeleteRequest +import io.bkbn.kompendium.playground.BasicPlaygroundToC.simpleGetExample +import io.bkbn.kompendium.playground.BasicPlaygroundToC.simpleGetExampleWithParameters +import io.bkbn.kompendium.playground.BasicPlaygroundToC.simplePostRequest +import io.ktor.application.Application +import io.ktor.application.call +import io.ktor.application.install +import io.ktor.features.ContentNegotiation +import io.ktor.http.HttpStatusCode +import io.ktor.request.receive +import io.ktor.response.respond +import io.ktor.routing.route +import io.ktor.routing.routing +import io.ktor.serialization.json +import io.ktor.server.engine.embeddedServer +import io.ktor.server.netty.Netty +import kotlinx.serialization.Serializable +import java.net.URI +import java.util.UUID + +/** + * Application entrypoint. Run this and head on over to `localhost:8081/docs` + * to see a very simple yet beautifully documented API + */ +fun main() { + embeddedServer( + Netty, + port = 8081, + module = Application::mainModule + ).start(wait = true) +} + +// Application Module +private fun Application.mainModule() { + // Installs Simple JSON Content Negotiation + install(ContentNegotiation) { + json() + } + // Installs the Kompendium Plugin and sets up baseline server metadata + install(Kompendium) { + spec = BasicMetadata.spec + } + // Configures the routes for our API + routing { + // This adds ReDoc support at the `/docs` endpoint. + // By default, it will point at the `/openapi.json` created by Kompendium + redoc(pageTitle = "Simple API Docs") + // Kompendium infers the route path from the Ktor Route. This will show up as the root path `/` + notarizedGet(simpleGetExample) { + call.respond(HttpStatusCode.OK, BasicResponse(c = UUID.randomUUID().toString())) + } + notarizedDelete(simpleDeleteRequest) { + call.respond(HttpStatusCode.NoContent) + } + // It can also infer path parameters + route("/{a}") { + notarizedGet(simpleGetExampleWithParameters) { + val a = call.parameters["a"] ?: error("Unable to read expected path parameter") + val b = call.request.queryParameters["b"]?.toInt() ?: error("Unable to read expected query parameter") + call.respond(HttpStatusCode.OK, BasicResponse(c = "$a: $b")) + } + } + route("/create") { + notarizedPost(simplePostRequest) { + val request = call.receive() + when (request.d) { + true -> call.respond(HttpStatusCode.OK, BasicResponse(c = "So it is true!")) + false -> call.respond(HttpStatusCode.OK, BasicResponse(c = "Oh, I knew it!")) + } + } + } + } +} + +// This is a table of contents to hold all the metadata for our various API endpoints +object BasicPlaygroundToC { + /** + * This is the information required to document a simple request. Here we declare that our endpoint + * takes no parameters, and will return an object of type [BasicResponse] + * with status code [HttpStatusCode.OK] + */ + val simpleGetExample = GetInfo( + summary = "Simple, Documented GET Request", + description = "This is to showcase just how easy it is to document your Ktor API!", + responseInfo = ResponseInfo( + status = HttpStatusCode.OK, + description = "This means everything went as expected!", + examples = mapOf("demo" to BasicResponse(c = "52c099d7-8642-46cc-b34e-22f39b923cf4")) + ), + tags = setOf("Simple") + ) + + /** + * This showcases a GET request with parameters. Here we declare that our endpoint takes a path and a query + * parameter. This is inferred by the annotations on [BasicParameters.a] and [BasicParameters.b] + * respectively. + */ + val simpleGetExampleWithParameters = GetInfo( + summary = "Simple, Documented GET Request with Parameters", + description = "This showcases how easy it is to document your input parameters!", + responseInfo = ResponseInfo( + status = HttpStatusCode.OK, + description = "This means everything went as expected!", + examples = mapOf("demo" to BasicResponse(c = "52c099d7-8642-46cc-b34e-22f39b923cf4")) + ), + tags = setOf("Parameters") + ) + + /** + * This showcases a POST request with a request body of type [BasicRequest] + */ + val simplePostRequest = PostInfo( + summary = "Simple, Documented POST Request", + description = "Showcases how easy it is to document a post request!", + requestInfo = RequestInfo( + description = "This is the required info for this request!", + examples = mapOf("demo" to BasicRequest(true)) + ), + responseInfo = ResponseInfo( + status = HttpStatusCode.OK, + description = "This means everything went as expected!", + examples = mapOf("demo" to BasicResponse(c = "So it is true!")) + ), + tags = setOf("Simple") + ) + + /** + * This showcases a DELETE request + */ + val simpleDeleteRequest = DeleteInfo( + summary = "Simple, documented DELETE Request", + description = "Cleanin' house", + responseInfo = ResponseInfo( + status = HttpStatusCode.NoContent, + description = "We wiped the files boss" + ), + tags = setOf("Simple") + ) +} + +// Contains the root metadata for our server. This is all the stuff that is defined once +// and cannot be inferred from the Ktor application +object BasicMetadata { + val spec = OpenApiSpec( + info = Info( + title = "Simple Demo API", + version = "1.33.7", + description = "Wow isn't this cool?", + termsOfService = URI("https://example.com"), + contact = Contact( + name = "Homer Simpson", + email = "chunkylover53@aol.com", + url = URI("https://gph.is/1NPUDiM") + ), + license = License( + name = "MIT", + url = URI("https://github.com/bkbnio/kompendium/blob/main/LICENSE") + ) + ), + servers = mutableListOf( + Server( + url = URI("https://myawesomeapi.com"), + description = "Production instance of my API" + ), + Server( + url = URI("https://staging.myawesomeapi.com"), + description = "Where the fun stuff happens" + ) + ) + ) +} + +object BasicModels { + @Serializable + data class BasicResponse(val c: String) + + @Serializable + data class BasicParameters( + @Param(type = ParamType.PATH) + val a: String, + @Param(type = ParamType.QUERY) + val b: Int + ) + + @Serializable + data class BasicRequest( + @Field(description = "This is a super important field!!", name = "best_field") + val d: Boolean + ) +} diff --git a/kompendium-playground/src/main/kotlin/io/bkbn/kompendium/playground/ConstraintPlayground.kt b/kompendium-playground/src/main/kotlin/io/bkbn/kompendium/playground/ConstraintPlayground.kt new file mode 100644 index 000000000..9aa0fb016 --- /dev/null +++ b/kompendium-playground/src/main/kotlin/io/bkbn/kompendium/playground/ConstraintPlayground.kt @@ -0,0 +1,174 @@ +package io.bkbn.kompendium.playground + +import io.bkbn.kompendium.annotations.Field +import io.bkbn.kompendium.annotations.FreeFormObject +import io.bkbn.kompendium.annotations.Param +import io.bkbn.kompendium.annotations.ParamType +import io.bkbn.kompendium.annotations.constraint.Format +import io.bkbn.kompendium.annotations.constraint.MaxItems +import io.bkbn.kompendium.annotations.constraint.MaxLength +import io.bkbn.kompendium.annotations.constraint.Maximum +import io.bkbn.kompendium.annotations.constraint.MinItems +import io.bkbn.kompendium.annotations.constraint.MinLength +import io.bkbn.kompendium.annotations.constraint.MinProperties +import io.bkbn.kompendium.annotations.constraint.Minimum +import io.bkbn.kompendium.annotations.constraint.MultipleOf +import io.bkbn.kompendium.annotations.constraint.Pattern +import io.bkbn.kompendium.annotations.constraint.UniqueItems +import io.bkbn.kompendium.core.Kompendium +import io.bkbn.kompendium.core.Notarized.notarizedGet +import io.bkbn.kompendium.core.Notarized.notarizedPost +import io.bkbn.kompendium.core.metadata.RequestInfo +import io.bkbn.kompendium.core.metadata.ResponseInfo +import io.bkbn.kompendium.core.metadata.method.GetInfo +import io.bkbn.kompendium.core.metadata.method.PostInfo +import io.bkbn.kompendium.core.routes.redoc +import io.bkbn.kompendium.oas.OpenApiSpec +import io.bkbn.kompendium.oas.info.Contact +import io.bkbn.kompendium.oas.info.Info +import io.bkbn.kompendium.oas.info.License +import io.bkbn.kompendium.oas.server.Server +import io.bkbn.kompendium.playground.ConstrainedModels.ConstrainedParams +import io.bkbn.kompendium.playground.ConstrainedModels.ConstrainedRequest +import io.bkbn.kompendium.playground.ConstrainedModels.ConstrainedResponse +import io.bkbn.kompendium.playground.ConstrainedPlaygroundToC.simpleConstrainedGet +import io.bkbn.kompendium.playground.ConstrainedPlaygroundToC.simpleConstrainedPost +import io.ktor.application.Application +import io.ktor.application.call +import io.ktor.application.install +import io.ktor.features.ContentNegotiation +import io.ktor.http.HttpStatusCode +import io.ktor.response.respond +import io.ktor.routing.routing +import io.ktor.serialization.json +import io.ktor.server.engine.embeddedServer +import io.ktor.server.netty.Netty +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.JsonElement +import java.net.URI + +fun main() { + embeddedServer( + Netty, + port = 8081, + module = Application::mainModule + ).start(wait = true) +} + +// Application Module +private fun Application.mainModule() { + // Installs Simple JSON Content Negotiation + install(ContentNegotiation) { + json() + } + // Installs the Kompendium Plugin and sets up baseline server metadata + install(Kompendium) { + spec = ConstrainedMetadata.spec + } + // Configures the routes for our API + routing { + // This adds ReDoc support at the `/docs` endpoint. + // By default, it will point at the `/openapi.json` created by Kompendium + redoc(pageTitle = "Constrained API Docs") + notarizedGet(simpleConstrainedGet) { + call.respond(HttpStatusCode.OK, ConstrainedResponse(100)) + } + notarizedPost(simpleConstrainedPost) { + call.respond(HttpStatusCode.OK, ConstrainedResponse(100)) + } + } +} + +object ConstrainedPlaygroundToC { + val simpleConstrainedGet = GetInfo( + summary = "Simple, Constrained get", + description = "Shows that you can set constraints on given fields", + responseInfo = ResponseInfo( + status = HttpStatusCode.OK, + description = "Cool stuff", + examples = mapOf("demo" to ConstrainedResponse()) + ) + ) + val simpleConstrainedPost = + PostInfo( + summary = "Simple, Constrained post", + description = "Shows that you can set constraints on given fields", + requestInfo = RequestInfo( + description = "Cool stuff" + ), + responseInfo = ResponseInfo( + status = HttpStatusCode.OK, + description = "Cool stuff", + examples = mapOf("demo" to ConstrainedResponse()) + ) + ) +} + +object ConstrainedMetadata { + val spec = OpenApiSpec( + info = Info( + title = "Simple Demo API", + version = "1.33.7", + description = "Wow isn't this cool?", + termsOfService = URI("https://example.com"), + contact = Contact( + name = "Homer Simpson", + email = "chunkylover53@aol.com", + url = URI("https://gph.is/1NPUDiM") + ), + license = License( + name = "MIT", + url = URI("https://github.com/bkbnio/kompendium/blob/main/LICENSE") + ) + ), + servers = mutableListOf( + Server( + url = URI("https://myawesomeapi.com"), + description = "Production instance of my API" + ), + Server( + url = URI("https://staging.myawesomeapi.com"), + description = "Where the fun stuff happens" + ) + ) + ) +} + +object ConstrainedModels { + @Serializable + data class ConstrainedResponse( + @Minimum("5") + @Maximum("101") + @MultipleOf("5") + val a: Int = 10, + @MinItems(100) + @MaxItems(1000) + @UniqueItems + val b: List = (0..500).map { it.toString() } + ) + + @Serializable + data class ConstrainedParams( + @Field(description = "This is a really important field!") + @Param(ParamType.QUERY) + @MinLength(11) + @MaxLength(11) + @Pattern("^\\d{3}-\\d{2}-\\d{4}\$") + @Format("password") + val ssn: String = "111-11-1111" + ) + + @Serializable + data class ConstrainedRequest( + val fieldy: Field, + @MinProperties(1) + @FreeFormObject + val data: JsonElement? = null + ) { + @Serializable + data class Field(val nesty: Nested?) { + @Serializable + data class Nested(val a: Int = 100, val b: Boolean) + } + } +} diff --git a/kompendium-playground/src/main/kotlin/io/bkbn/kompendium/playground/ExceptionPlayground.kt b/kompendium-playground/src/main/kotlin/io/bkbn/kompendium/playground/ExceptionPlayground.kt new file mode 100644 index 000000000..3b05f5a28 --- /dev/null +++ b/kompendium-playground/src/main/kotlin/io/bkbn/kompendium/playground/ExceptionPlayground.kt @@ -0,0 +1,138 @@ +package io.bkbn.kompendium.playground + +import io.bkbn.kompendium.core.Kompendium +import io.bkbn.kompendium.core.Notarized.notarizedGet +import io.bkbn.kompendium.core.metadata.ExceptionInfo +import io.bkbn.kompendium.core.metadata.ResponseInfo +import io.bkbn.kompendium.core.metadata.method.GetInfo +import io.bkbn.kompendium.core.routes.redoc +import io.bkbn.kompendium.oas.OpenApiSpec +import io.bkbn.kompendium.oas.info.Contact +import io.bkbn.kompendium.oas.info.Info +import io.bkbn.kompendium.oas.info.License +import io.bkbn.kompendium.oas.server.Server +import io.bkbn.kompendium.playground.ExceptionPlaygroundToC.simpleGetExample +import io.ktor.application.Application +import io.ktor.application.call +import io.ktor.application.install +import io.ktor.features.ContentNegotiation +import io.ktor.features.StatusPages +import io.ktor.http.HttpStatusCode +import io.ktor.response.respond +import io.ktor.routing.routing +import io.ktor.serialization.json +import io.ktor.server.engine.embeddedServer +import io.ktor.server.netty.Netty +import kotlin.reflect.typeOf +import kotlinx.serialization.Serializable +import java.net.URI +import java.time.LocalDateTime + +// Application Entrypoint +fun main() { + embeddedServer( + Netty, + port = 8081, + module = Application::mainModule + ).start(wait = true) +} + +// Application Module +private fun Application.mainModule() { + // Installs Simple JSON Content Negotiation + install(ContentNegotiation) { + json() + } + // Installs the Kompendium Plugin and sets up baseline server metadata + install(Kompendium) { + spec = ExceptionMetadata.spec + } + install(StatusPages) { + exception { + call.respond(HttpStatusCode.BadRequest, ExceptionModels.ExceptionResponse("Bad user thing happened")) + } + exception { + call.respond(HttpStatusCode.BadRequest, ExceptionModels.ExceptionResponse("Bad coder thing happened")) + } + } + // Configures the routes for our API + routing { + // This adds ReDoc support at the `/docs` endpoint. + // By default, it will point at the `/openapi.json` created by Kompendium + redoc(pageTitle = "Simple Exception Examples") + notarizedGet(simpleGetExample) { + if (LocalDateTime.now().second % 2 == 0) { + throw ExceptionModels.BadCoderException() + } else { + throw ExceptionModels.BadUserException() + } + } + } +} + +object ExceptionMetadata { + val spec = OpenApiSpec( + info = Info( + title = "Simple Demo API with notarized exceptions", + version = "1.33.7", + description = "Wow isn't this cool?", + termsOfService = URI("https://example.com"), + contact = Contact( + name = "Homer Simpson", + email = "chunkylover53@aol.com", + url = URI("https://gph.is/1NPUDiM") + ), + license = License( + name = "MIT", + url = URI("https://github.com/bkbnio/kompendium/blob/main/LICENSE") + ) + ), + servers = mutableListOf( + Server( + url = URI("https://myawesomeapi.com"), + description = "Production instance of my API" + ), + Server( + url = URI("https://staging.myawesomeapi.com"), + description = "Where the fun stuff happens" + ) + ) + ) +} + +// This is a table of contents to hold all the metadata for our various API endpoints +object ExceptionPlaygroundToC { + private val simpleException = ExceptionInfo( + responseType = typeOf(), + status = HttpStatusCode.BadRequest, + description = "Indicates that the user is a TOTAL LOSER hehehe" + ) + + private val badCoderSignal = ExceptionInfo( + responseType = typeOf(), + status = HttpStatusCode.InternalServerError, + description = "Indicates that the engineer is a TOTAL NOOB mwahahaha" + ) + + val simpleGetExample = GetInfo( + summary = "A route that throws an exception", + description = "You will never see the real response MWAHAHAHA", + responseInfo = ResponseInfo( + HttpStatusCode.OK, + description = "Not gonna happen pal" + ), + canThrow = setOf(simpleException, badCoderSignal) + ) +} + +object ExceptionModels { + @Serializable + data class WontGetHere(val result: Int) + + @Serializable + data class ExceptionResponse(val message: String) + + class BadUserException : Exception() + + class BadCoderException : Exception() +} diff --git a/kompendium-playground/src/main/kotlin/io/bkbn/kompendium/playground/GenericPlayground.kt b/kompendium-playground/src/main/kotlin/io/bkbn/kompendium/playground/GenericPlayground.kt new file mode 100644 index 000000000..9ddbd0944 --- /dev/null +++ b/kompendium-playground/src/main/kotlin/io/bkbn/kompendium/playground/GenericPlayground.kt @@ -0,0 +1,114 @@ +package io.bkbn.kompendium.playground + +import io.bkbn.kompendium.core.Kompendium +import io.bkbn.kompendium.core.Notarized.notarizedGet +import io.bkbn.kompendium.core.metadata.ResponseInfo +import io.bkbn.kompendium.core.metadata.method.GetInfo +import io.bkbn.kompendium.core.routes.redoc +import io.bkbn.kompendium.oas.OpenApiSpec +import io.bkbn.kompendium.oas.info.Contact +import io.bkbn.kompendium.oas.info.Info +import io.bkbn.kompendium.oas.info.License +import io.bkbn.kompendium.oas.server.Server +import io.bkbn.kompendium.playground.GenericPlaygroundToC.simpleGenericGet +import io.ktor.application.Application +import io.ktor.application.call +import io.ktor.application.install +import io.ktor.features.ContentNegotiation +import io.ktor.http.HttpStatusCode +import io.ktor.response.respond +import io.ktor.routing.routing +import io.ktor.serialization.json +import io.ktor.server.engine.embeddedServer +import io.ktor.server.netty.Netty +import kotlinx.serialization.Serializable +import java.net.URI + +/** + * Application entrypoint. Run this and head on over to `localhost:8081/docs` + * to see a very simple yet beautifully documented API + */ +fun main() { + embeddedServer( + Netty, + port = 8081, + module = Application::mainModule + ).start(wait = true) +} + +// Application Module +private fun Application.mainModule() { + // Installs Simple JSON Content Negotiation + install(ContentNegotiation) { + json() + } + // Installs the Kompendium Plugin and sets up baseline server metadata + install(Kompendium) { + spec = GenericMetadata.spec + } + routing { + redoc(pageTitle = "Simple API Docs") + notarizedGet(simpleGenericGet) { + call.respond( + HttpStatusCode.OK, + GenericModels.Foosy(GenericModels.Barzo(5), listOf("hey", "now", "you're", "an", "all-start")) + ) + } + } +} + + +// This is a table of contents to hold all the metadata for our various API endpoints +object GenericPlaygroundToC { + val simpleGenericGet = GetInfo>( + summary = "Lots 'o Generics", + description = "Pretty funky huh", + responseInfo = ResponseInfo( + status = HttpStatusCode.OK, + description = "Enjoy all this data, pal" + ) + ) +} + +// Contains the root metadata for our server. This is all the stuff that is defined once +// and cannot be inferred from the Ktor application +object GenericMetadata { + val spec = OpenApiSpec( + info = Info( + title = "Simple Demo API with Generic Data", + version = "1.33.7", + description = "Wow isn't this cool?", + termsOfService = URI("https://example.com"), + contact = Contact( + name = "Homer Simpson", + email = "chunkylover53@aol.com", + url = URI("https://gph.is/1NPUDiM") + ), + license = License( + name = "MIT", + url = URI("https://github.com/bkbnio/kompendium/blob/main/LICENSE") + ) + ), + servers = mutableListOf( + Server( + url = URI("https://myawesomeapi.com"), + description = "Production instance of my API" + ), + Server( + url = URI("https://staging.myawesomeapi.com"), + description = "Where the fun stuff happens" + ) + ) + ) +} + +object GenericModels { + @Serializable + data class Foosy(val test: T, val otherThing: List) + + @Serializable + data class Barzo(val result: G) + + @Serializable + data class SimpleG(val result: G) +} diff --git a/kompendium-playground/src/main/kotlin/io/bkbn/kompendium/playground/LocationPlayground.kt b/kompendium-playground/src/main/kotlin/io/bkbn/kompendium/playground/LocationPlayground.kt new file mode 100644 index 000000000..440ecd3b3 --- /dev/null +++ b/kompendium-playground/src/main/kotlin/io/bkbn/kompendium/playground/LocationPlayground.kt @@ -0,0 +1,156 @@ +package io.bkbn.kompendium.playground + +import io.bkbn.kompendium.annotations.Param +import io.bkbn.kompendium.annotations.ParamType +import io.bkbn.kompendium.core.Kompendium +import io.bkbn.kompendium.core.metadata.ResponseInfo +import io.bkbn.kompendium.core.metadata.method.GetInfo +import io.bkbn.kompendium.core.routes.redoc +import io.bkbn.kompendium.locations.NotarizedLocation.notarizedGet +import io.bkbn.kompendium.oas.OpenApiSpec +import io.bkbn.kompendium.oas.info.Contact +import io.bkbn.kompendium.oas.info.Info +import io.bkbn.kompendium.oas.info.License +import io.bkbn.kompendium.oas.server.Server +import io.bkbn.kompendium.playground.LocationsToC.ohBoiUCrazy +import io.bkbn.kompendium.playground.LocationsToC.testLocation +import io.bkbn.kompendium.playground.LocationsToC.testNestLocation +import io.ktor.application.Application +import io.ktor.application.call +import io.ktor.application.install +import io.ktor.features.ContentNegotiation +import io.ktor.http.HttpStatusCode +import io.ktor.locations.Location +import io.ktor.locations.Locations +import io.ktor.response.respondText +import io.ktor.routing.routing +import io.ktor.serialization.json +import io.ktor.server.engine.embeddedServer +import io.ktor.server.netty.Netty +import kotlinx.serialization.Serializable +import java.net.URI + +/** + * Application entrypoint. Run this and head on over to `localhost:8081/docs` + * to see a very simple yet beautifully documented API + */ +fun main() { + embeddedServer( + Netty, + port = 8081, + module = Application::mainModule + ).start(wait = true) +} + +private fun Application.mainModule() { + install(ContentNegotiation) { + json() + } + install(Kompendium) { + spec = LocationMetadata.spec + } + install(Locations) + routing { + redoc() + /** + * Notice the difference here between this and the standard notarizedGet! tl contains your input parameters + */ + notarizedGet(testLocation) { tl -> + call.respondText { tl.name } + } + notarizedGet(testNestLocation) { tnl -> + call.respondText { tnl.idk.toString() } + } + notarizedGet(ohBoiUCrazy) { obuc -> + call.respondText { obuc.parent.parent.name } + } + } +} + +private object LocationsToC { + val testLocation = GetInfo( + summary = "Shallow", + description = "Ez Pz Lemon Squeezy", + responseInfo = ResponseInfo( + status = HttpStatusCode.OK, + description = "Great!" + ) + ) + val testNestLocation = GetInfo( + summary = "Nested", + description = "Gettin' scary", + responseInfo = ResponseInfo( + status = HttpStatusCode.Continue, + description = "Hmmm" + ) + ) + val ohBoiUCrazy = GetInfo( + summary = "Example Deeply Nested", + description = "We deep now", + responseInfo = ResponseInfo( + status = HttpStatusCode.OK, + description = "nice", + examples = mapOf("test" to LocationModels.ExampleResponse(c = "spud")) + ), + ) +} + +// For more info make sure to read through the Ktor location docs +// Additionally, make sure to note that even though we define the locations here, we still must annotate fields +// with KompendiumParam!!! +@Location("test/{name}") +data class TestLocations( + @Param(ParamType.PATH) + val name: String, +) { + @Location("/spaghetti") + data class NestedTestLocations( + @Param(ParamType.QUERY) + val idk: Int, + val parent: TestLocations + ) { + @Location("/hehe/{madness}") + data class OhBoiUCrazy( + @Param(ParamType.PATH) + val madness: Boolean, + val parent: NestedTestLocations + ) + } +} + +// Contains the root metadata for our server. This is all the stuff that is defined once +// and cannot be inferred from the Ktor application +object LocationMetadata { + val spec = OpenApiSpec( + info = Info( + title = "Simple Demo Leveraging Ktor Locations", + version = "1.33.7", + description = "Wow isn't this cool?", + termsOfService = URI("https://example.com"), + contact = Contact( + name = "Homer Simpson", + email = "chunkylover53@aol.com", + url = URI("https://gph.is/1NPUDiM") + ), + license = License( + name = "MIT", + url = URI("https://github.com/bkbnio/kompendium/blob/main/LICENSE") + ) + ), + servers = mutableListOf( + Server( + url = URI("https://myawesomeapi.com"), + description = "Production instance of my API" + ), + Server( + url = URI("https://staging.myawesomeapi.com"), + description = "Where the fun stuff happens" + ) + ) + ) +} + +object LocationModels { + @Serializable + data class ExampleResponse(val c: String) +} diff --git a/kompendium-playground/src/main/kotlin/io/bkbn/kompendium/playground/LocationsSpike.kt b/kompendium-playground/src/main/kotlin/io/bkbn/kompendium/playground/LocationsSpike.kt deleted file mode 100644 index 2c93b67d4..000000000 --- a/kompendium-playground/src/main/kotlin/io/bkbn/kompendium/playground/LocationsSpike.kt +++ /dev/null @@ -1,91 +0,0 @@ -package io.bkbn.kompendium.playground - -import io.bkbn.kompendium.Kompendium -import io.bkbn.kompendium.annotations.KompendiumParam -import io.bkbn.kompendium.annotations.ParamType -import io.bkbn.kompendium.locations.NotarizedLocation.notarizedGet -import io.bkbn.kompendium.models.meta.MethodInfo -import io.bkbn.kompendium.models.meta.ResponseInfo -import io.bkbn.kompendium.models.oas.FormatSchema -import io.bkbn.kompendium.playground.LocationsToC.testLocation -import io.bkbn.kompendium.routes.openApi -import io.bkbn.kompendium.routes.redoc -import io.ktor.application.Application -import io.ktor.application.call -import io.ktor.application.install -import io.ktor.features.ContentNegotiation -import io.ktor.http.HttpStatusCode -import io.ktor.locations.Location -import io.ktor.locations.Locations -import io.ktor.response.respondText -import io.ktor.routing.routing -import io.ktor.serialization.json -import io.ktor.server.engine.embeddedServer -import io.ktor.server.netty.Netty -import org.joda.time.DateTime - -fun main() { - Kompendium.addCustomTypeSchema(DateTime::class, FormatSchema("date-time", "string")) - - embeddedServer( - Netty, - port = 8081, - module = Application::mainModule - ).start(wait = true) -} - -private var featuresInstalled = false - -private fun Application.configModule() { - if (!featuresInstalled) { - install(ContentNegotiation) { - json() - } - install(Locations) - featuresInstalled = true - } -} - -private fun Application.mainModule() { - configModule() - routing { - openApi(oas) - redoc(oas) - notarizedGet(testLocation) { tl -> - call.respondText { tl.parent.parent.name } - } - } -} - -private object LocationsToC { - val testLocation = MethodInfo.GetInfo( - summary = "Example Parameters", - description = "A test for setting parameter examples", - responseInfo = ResponseInfo( - status = HttpStatusCode.OK, - description = "nice", - examples = mapOf("test" to ExampleResponse(c = "spud")) - ), - canThrow = setOf(Exception::class) - ) -} - -@Location("/test/{name}") -data class TestLocations( - @KompendiumParam(ParamType.PATH) - val name: String, -) { - @Location("/spaghetti") - data class NestedTestLocations( - @KompendiumParam(ParamType.QUERY) - val idk: Int, - val parent: TestLocations - ) { - @Location("/hehe/{madness}") - data class OhBoiUCrazy( - @KompendiumParam(ParamType.PATH) - val madness: Boolean, - val parent: NestedTestLocations - ) - } -} diff --git a/kompendium-playground/src/main/kotlin/io/bkbn/kompendium/playground/Main.kt b/kompendium-playground/src/main/kotlin/io/bkbn/kompendium/playground/Main.kt deleted file mode 100644 index 01f31593d..000000000 --- a/kompendium-playground/src/main/kotlin/io/bkbn/kompendium/playground/Main.kt +++ /dev/null @@ -1,148 +0,0 @@ -package io.bkbn.kompendium.playground - -import io.bkbn.kompendium.Kompendium -import io.bkbn.kompendium.Notarized.notarizedDelete -import io.bkbn.kompendium.Notarized.notarizedException -import io.bkbn.kompendium.Notarized.notarizedGet -import io.bkbn.kompendium.Notarized.notarizedPost -import io.bkbn.kompendium.Notarized.notarizedPut -import io.bkbn.kompendium.auth.KompendiumAuth.notarizedBasic -import io.bkbn.kompendium.models.meta.ResponseInfo -import io.bkbn.kompendium.models.oas.FormatSchema -import io.bkbn.kompendium.playground.PlaygroundToC.testAuthenticatedSingleGetInfo -import io.bkbn.kompendium.playground.PlaygroundToC.testCustomOverride -import io.bkbn.kompendium.playground.PlaygroundToC.testGetWithExamples -import io.bkbn.kompendium.playground.PlaygroundToC.testIdGetInfo -import io.bkbn.kompendium.playground.PlaygroundToC.testPostWithExamples -import io.bkbn.kompendium.playground.PlaygroundToC.testSingleDeleteInfo -import io.bkbn.kompendium.playground.PlaygroundToC.testSingleGetInfo -import io.bkbn.kompendium.playground.PlaygroundToC.testSingleGetInfoWithThrowable -import io.bkbn.kompendium.playground.PlaygroundToC.testSinglePostInfo -import io.bkbn.kompendium.playground.PlaygroundToC.testSinglePutInfo -import io.bkbn.kompendium.playground.PlaygroundToC.testUndeclaredFields -import io.bkbn.kompendium.routes.openApi -import io.bkbn.kompendium.routes.redoc -import io.bkbn.kompendium.swagger.swaggerUI -import io.ktor.application.Application -import io.ktor.application.call -import io.ktor.application.install -import io.ktor.auth.Authentication -import io.ktor.auth.UserIdPrincipal -import io.ktor.auth.authenticate -import io.ktor.features.ContentNegotiation -import io.ktor.features.StatusPages -import io.ktor.http.HttpStatusCode -import io.ktor.response.respond -import io.ktor.response.respondText -import io.ktor.routing.route -import io.ktor.routing.routing -import io.ktor.serialization.json -import io.ktor.server.engine.embeddedServer -import io.ktor.server.netty.Netty -import io.ktor.webjars.Webjars -import org.joda.time.DateTime - -fun main() { - Kompendium.addCustomTypeSchema(DateTime::class, FormatSchema("date-time", "string")) - - embeddedServer( - Netty, - port = 8081, - module = Application::mainModule - ).start(wait = true) -} - -private var featuresInstalled = false - -private fun Application.configModule() { - if (!featuresInstalled) { - install(ContentNegotiation) { - json() - } - install(Authentication) { - notarizedBasic("basic") { - realm = "Ktor Server" - validate { credentials -> - if (credentials.name == credentials.password) { - UserIdPrincipal(credentials.name) - } else { - null - } - } - } - } - install(Webjars) - install(StatusPages) { - notarizedException( - info = ResponseInfo( - HttpStatusCode.BadRequest, - "Bad Things Happened", - examples = mapOf("example" to ExceptionResponse("hey bad things happened sorry")) - ) - ) { - call.respond(HttpStatusCode.BadRequest, ExceptionResponse("Why you do dis?")) - } - } - featuresInstalled = true - } -} - -private fun Application.mainModule() { - configModule() - routing { - openApi(oas) - redoc(oas) - swaggerUI() - route("/potato/spud") { - notarizedGet(testGetWithExamples) { - call.respond(HttpStatusCode.OK) - } - notarizedPost(testPostWithExamples) { - call.respond(HttpStatusCode.Created, ExampleResponse("hey")) - } - } - route("/test") { - route("/{id}") { - notarizedGet(testIdGetInfo) { - call.respondText("get by id") - } - } - route("/single") { - notarizedGet(testSingleGetInfo) { - call.respondText("get single") - } - notarizedPost(testSinglePostInfo) { - call.respondText("test post") - } - notarizedPut(testSinglePutInfo) { - call.respondText { "hey" } - } - notarizedDelete(testSingleDeleteInfo) { - call.respondText { "heya" } - } - } - route("custom_override") { - notarizedGet(testCustomOverride) { - call.respondText { DateTime.now().toString() } - } - } - authenticate("basic") { - route("/authenticated/single") { - notarizedGet(testAuthenticatedSingleGetInfo) { - call.respond(HttpStatusCode.OK) - } - } - } - } - route("/error") { - notarizedGet(testSingleGetInfoWithThrowable) { - error("bad things just happened") - } - } - route("/undeclared") { - notarizedGet(testUndeclaredFields) { - call.respondText { "hi" } - } - } - } -} diff --git a/kompendium-playground/src/main/kotlin/io/bkbn/kompendium/playground/Models.kt b/kompendium-playground/src/main/kotlin/io/bkbn/kompendium/playground/Models.kt deleted file mode 100644 index 83fdf60dd..000000000 --- a/kompendium-playground/src/main/kotlin/io/bkbn/kompendium/playground/Models.kt +++ /dev/null @@ -1,46 +0,0 @@ -package io.bkbn.kompendium.playground - -import io.bkbn.kompendium.annotations.KompendiumField -import io.bkbn.kompendium.annotations.KompendiumParam -import io.bkbn.kompendium.annotations.ParamType -import io.bkbn.kompendium.annotations.UndeclaredField -import kotlinx.serialization.Serializable -import org.joda.time.DateTime - -data class ExampleParams( - @KompendiumParam(ParamType.PATH) val id: Int, - @KompendiumParam(ParamType.QUERY) val name: String -) - -data class JustQuery( - @KompendiumParam(ParamType.QUERY) val potato: Boolean, - @KompendiumParam(ParamType.QUERY) val tomato: String -) - -data class ExampleNested(val nesty: String) - -data class ExampleGeneric(val potato: T) - -data class ExampleRequest( - @KompendiumField(name = "field_name") - val fieldName: ExampleNested, - val b: Double, - val aaa: List -) - -@Serializable -data class ExampleResponse(val c: String) - -data class ExceptionResponse(val message: String) - -data class ExampleCreatedResponse(val id: Int, val c: String) - -data class DateTimeWrapper(val dt: DateTime) - -enum class Testerino { - First, - Second -} - -@UndeclaredField("type", Testerino::class) -data class SimpleYetMysterious(val exists: Boolean) diff --git a/kompendium-playground/src/main/kotlin/io/bkbn/kompendium/playground/PlaygroundToC.kt b/kompendium-playground/src/main/kotlin/io/bkbn/kompendium/playground/PlaygroundToC.kt deleted file mode 100644 index 50bcb51af..000000000 --- a/kompendium-playground/src/main/kotlin/io/bkbn/kompendium/playground/PlaygroundToC.kt +++ /dev/null @@ -1,121 +0,0 @@ -package io.bkbn.kompendium.playground - -import io.ktor.http.HttpStatusCode -import io.bkbn.kompendium.models.meta.MethodInfo -import io.bkbn.kompendium.models.meta.RequestInfo -import io.bkbn.kompendium.models.meta.ResponseInfo - -object PlaygroundToC { - val testGetWithExamples = MethodInfo.GetInfo( - summary = "Example Parameters", - description = "A test for setting parameter examples", - responseInfo = ResponseInfo( - status = HttpStatusCode.OK, - description = "nice", - examples = mapOf("test" to ExampleResponse(c = "spud")) - ), - canThrow = setOf(Exception::class) - ) - @Suppress("MagicNumber") - val testPostWithExamples = MethodInfo.PostInfo( - summary = "Full Example", - description = "Throws just about all Kompendium has to offer into one endpoint", - requestInfo = RequestInfo( - description = "Necessary deetz", - examples = mapOf( - "Send This" to ExampleRequest(ExampleNested("potato"), 13.37, listOf(12341)) - ) - ), - responseInfo = ResponseInfo( - status = HttpStatusCode.Created, - description = "Congratz you hit da endpoint", - examples = mapOf( - "Expect This" to ExampleResponse(c = "Hi"), - "Or This" to ExampleResponse(c = "Hey") - ) - ), - canThrow = setOf(Exception::class) - ) - - val testIdGetInfo = MethodInfo.GetInfo>( - summary = "Get Test", - description = "Test for the getting", - tags = setOf("test", "sample", "get"), - responseInfo = ResponseInfo( - status = HttpStatusCode.OK, - description = "Returns sample info" - ) - ) - val testSingleGetInfo = MethodInfo.GetInfo( - summary = "Another get test", - description = "testing more", - tags = setOf("anotherTest", "sample"), - responseInfo = ResponseInfo( - status = HttpStatusCode.OK, - description = "Returns a different sample" - ) - ) - val testCustomOverride = MethodInfo.GetInfo( - summary = "custom schema test", - description = "testing", - tags = setOf("custom"), - responseInfo = ResponseInfo( - status = HttpStatusCode.OK, - description = "good tings" - ) - ) - val testSingleGetInfoWithThrowable = testSingleGetInfo.copy( - summary = "Show me the error baby 🙏", - canThrow = setOf(Exception::class) - ) - val testSinglePostInfo = MethodInfo.PostInfo( - summary = "Test post endpoint", - description = "Post your tests here!", - requestInfo = RequestInfo( - description = "Simple request body" - ), - responseInfo = ResponseInfo( - status = HttpStatusCode.Created, - description = "Worlds most complex response" - ) - ) - val testSinglePutInfo = MethodInfo.PutInfo( - summary = "Test put endpoint", - description = "Put your tests here!", - requestInfo = RequestInfo( - description = "Info needed to perform this put request" - ), - responseInfo = ResponseInfo( - status = HttpStatusCode.Created, - description = "What we give you when u do the puts" - ) - ) - val testSingleDeleteInfo = MethodInfo.DeleteInfo( - summary = "Test delete endpoint", - description = "testing my deletes", - responseInfo = ResponseInfo( - status = HttpStatusCode.NoContent, - description = "Signifies that your item was deleted successfully", - mediaTypes = emptyList() - ) - ) - val testAuthenticatedSingleGetInfo = MethodInfo.GetInfo( - summary = "Another get test", - description = "testing more", - tags = setOf("anotherTest", "sample"), - responseInfo = ResponseInfo( - status = HttpStatusCode.OK, - description = "Returns a different sample" - ), - securitySchemes = setOf("basic") - ) - val testUndeclaredFields = MethodInfo.GetInfo( - summary = "Tests adding undeclared fields", - description = "vvv mysterious", - tags = setOf("mysterious"), - responseInfo = ResponseInfo( - status = HttpStatusCode.OK, - description = "good tings" - ) - ) -} diff --git a/kompendium-playground/src/main/kotlin/io/bkbn/kompendium/playground/PolymorphicPlayground.kt b/kompendium-playground/src/main/kotlin/io/bkbn/kompendium/playground/PolymorphicPlayground.kt new file mode 100644 index 000000000..0bfdd5126 --- /dev/null +++ b/kompendium-playground/src/main/kotlin/io/bkbn/kompendium/playground/PolymorphicPlayground.kt @@ -0,0 +1,111 @@ +package io.bkbn.kompendium.playground + +import io.bkbn.kompendium.core.Kompendium +import io.bkbn.kompendium.core.Notarized.notarizedGet +import io.bkbn.kompendium.core.metadata.ResponseInfo +import io.bkbn.kompendium.core.metadata.method.GetInfo +import io.bkbn.kompendium.core.routes.redoc +import io.bkbn.kompendium.oas.OpenApiSpec +import io.bkbn.kompendium.oas.info.Contact +import io.bkbn.kompendium.oas.info.Info +import io.bkbn.kompendium.oas.info.License +import io.bkbn.kompendium.oas.server.Server +import io.bkbn.kompendium.playground.PolymorphicPlaygroundToC.polymorphicExample +import io.ktor.application.Application +import io.ktor.application.call +import io.ktor.application.install +import io.ktor.features.ContentNegotiation +import io.ktor.http.HttpStatusCode +import io.ktor.response.respond +import io.ktor.routing.routing +import io.ktor.serialization.json +import io.ktor.server.engine.embeddedServer +import io.ktor.server.netty.Netty +import kotlinx.serialization.Serializable +import java.net.URI + +/** + * Application entrypoint. Run this and head on over to `localhost:8081/docs` + * to see a very simple yet beautifully documented API + */ +fun main() { + embeddedServer( + Netty, + port = 8081, + module = Application::mainModule + ).start(wait = true) +} + +private fun Application.mainModule() { + // Installs Simple JSON Content Negotiation + install(ContentNegotiation) { + json() + } + // Installs the Kompendium Plugin and sets up baseline server metadata + install(Kompendium) { + spec = PolymorphicMetadata.spec + } + // Configures the routes for our API + routing { + redoc(pageTitle = "Polymorphic API Examples") + notarizedGet(polymorphicExample) { + call.respond(HttpStatusCode.OK, PolymorphicModels.OneJamma(1337)) + } + } +} + +// This is a table of contents to hold all the metadata for our various API endpoints +object PolymorphicPlaygroundToC { + val polymorphicExample = GetInfo( + summary = "C'mon and Slam", + description = "And welcome to the jam", + responseInfo = ResponseInfo( + status = HttpStatusCode.OK, + description = "You have successfully slammed and/or jammed", + examples = mapOf( + "one" to PolymorphicModels.OneJamma(42), + "two" to PolymorphicModels.AnothaJamma(4.2) + ) + ) + ) +} + +object PolymorphicMetadata { + val spec = OpenApiSpec( + info = Info( + title = "Simple Demo API with Polymorphic Models", + version = "1.33.7", + description = "Wow isn't this cool?", + termsOfService = URI("https://example.com"), + contact = Contact( + name = "Homer Simpson", + email = "chunkylover53@aol.com", + url = URI("https://gph.is/1NPUDiM") + ), + license = License( + name = "MIT", + url = URI("https://github.com/bkbnio/kompendium/blob/main/LICENSE") + ) + ), + servers = mutableListOf( + Server( + url = URI("https://myawesomeapi.com"), + description = "Production instance of my API" + ), + Server( + url = URI("https://staging.myawesomeapi.com"), + description = "Where the fun stuff happens" + ) + ) + ) +} + +object PolymorphicModels { + sealed interface SlammaJamma + + @Serializable + data class OneJamma(val a: Int) : SlammaJamma + + @Serializable + data class AnothaJamma(val b: Double) : SlammaJamma +} diff --git a/kompendium-playground/src/main/kotlin/io/bkbn/kompendium/playground/Spec.kt b/kompendium-playground/src/main/kotlin/io/bkbn/kompendium/playground/Spec.kt deleted file mode 100644 index 959c10ad6..000000000 --- a/kompendium-playground/src/main/kotlin/io/bkbn/kompendium/playground/Spec.kt +++ /dev/null @@ -1,36 +0,0 @@ -package io.bkbn.kompendium.playground - -import java.net.URI -import io.bkbn.kompendium.Kompendium -import io.bkbn.kompendium.models.oas.OpenApiSpecInfo -import io.bkbn.kompendium.models.oas.OpenApiSpecInfoContact -import io.bkbn.kompendium.models.oas.OpenApiSpecInfoLicense -import io.bkbn.kompendium.models.oas.OpenApiSpecServer - -val oas = Kompendium.openApiSpec.copy( - info = OpenApiSpecInfo( - title = "Test API", - version = "1.33.7", - description = "An amazing, fully-ish 😉 generated API spec", - termsOfService = URI("https://example.com"), - contact = OpenApiSpecInfoContact( - name = "Homer Simpson", - email = "chunkylover53@aol.com", - url = URI("https://gph.is/1NPUDiM") - ), - license = OpenApiSpecInfoLicense( - name = "MIT", - url = URI("https://github.com/bkbnio/kompendium/blob/main/LICENSE") - ) - ), - servers = mutableListOf( - OpenApiSpecServer( - url = URI("https://myawesomeapi.com"), - description = "Production instance of my API" - ), - OpenApiSpecServer( - url = URI("https://staging.myawesomeapi.com"), - description = "Where the fun stuff happens" - ) - ) -) diff --git a/kompendium-playground/src/main/kotlin/io/bkbn/kompendium/playground/SwaggerPlayground.kt b/kompendium-playground/src/main/kotlin/io/bkbn/kompendium/playground/SwaggerPlayground.kt new file mode 100644 index 000000000..13252b63c --- /dev/null +++ b/kompendium-playground/src/main/kotlin/io/bkbn/kompendium/playground/SwaggerPlayground.kt @@ -0,0 +1,51 @@ +package io.bkbn.kompendium.playground + +import io.bkbn.kompendium.core.Kompendium +import io.bkbn.kompendium.core.Notarized.notarizedGet +import io.bkbn.kompendium.swagger.swaggerUI +import io.ktor.application.Application +import io.ktor.application.call +import io.ktor.application.install +import io.ktor.features.ContentNegotiation +import io.ktor.http.HttpStatusCode +import io.ktor.response.respond +import io.ktor.routing.routing +import io.ktor.serialization.json +import io.ktor.server.engine.embeddedServer +import io.ktor.server.netty.Netty +import io.ktor.webjars.Webjars +import java.util.UUID + +/** + * Application entrypoint. Run this and head on over to `localhost:8081/docs` + * to see a very simple yet beautifully documented API + */ +fun main() { + embeddedServer( + Netty, + port = 8081, + module = Application::mainModule + ).start(wait = true) +} + +// Application Module +private fun Application.mainModule() { + // Installs Simple JSON Content Negotiation + install(ContentNegotiation) { + json() + } + install(Webjars) + // Installs the Kompendium Plugin and sets up baseline server metadata + install(Kompendium) { + spec = BasicMetadata.spec + } + // Configures the routes for our API + routing { + // This is all you need to do to add Swagger! Reachable at `/swagger-ui` + swaggerUI() + // Kompendium infers the route path from the Ktor Route. This will show up as the root path `/` + notarizedGet(BasicPlaygroundToC.simpleGetExample) { + call.respond(HttpStatusCode.OK, BasicModels.BasicResponse(c = UUID.randomUUID().toString())) + } + } +} diff --git a/kompendium-swagger-ui/Module.md b/kompendium-swagger-ui/Module.md new file mode 100644 index 000000000..51b850298 --- /dev/null +++ b/kompendium-swagger-ui/Module.md @@ -0,0 +1 @@ +# Module kompendium-swagger-ui diff --git a/kompendium-swagger-ui/build.gradle.kts b/kompendium-swagger-ui/build.gradle.kts index e9839a5f1..981a49d3f 100644 --- a/kompendium-swagger-ui/build.gradle.kts +++ b/kompendium-swagger-ui/build.gradle.kts @@ -1,76 +1,10 @@ plugins { - `java-library` - `maven-publish` - signing + id("io.bkbn.sourdough.library") } dependencies { - implementation(platform("org.jetbrains.kotlin:kotlin-bom")) - implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8") - implementation(libs.bundles.ktor) - api(libs.ktor.webjars) - implementation(libs.webjars.swagger.ui) - testImplementation("org.jetbrains.kotlin:kotlin-test") - testImplementation("org.jetbrains.kotlin:kotlin-test-junit") - testImplementation(libs.jackson.module.kotlin) - testImplementation(libs.ktor.server.test.host) -} - -java { - withSourcesJar() - withJavadocJar() -} - -publishing { - repositories { - maven { - name = "GithubPackages" - url = uri("https://maven.pkg.github.com/bkbnio/kompendium") - credentials { - username = System.getenv("GITHUB_ACTOR") - password = System.getenv("GITHUB_TOKEN") - } - } - } - publications { - create("kompendium") { - from(components["kotlin"]) - artifact(tasks.sourcesJar) - artifact(tasks.javadocJar) - groupId = project.group.toString() - artifactId = project.name.toLowerCase() - version = project.version.toString() - - pom { - name.set("Kompendium") - description.set("A minimally invasive OpenAPI spec generator for Ktor") - url.set("https://github.com/bkbnio/Kompendium") - licenses { - license { - name.set("MIT License") - url.set("https://mit-license.org/") - } - } - developers { - developer { - id.set("bkbnio") - name.set("Ryan Brink") - email.set("admin@bkbn.io") - } - } - scm { - connection.set("scm:git:git://github.com/bkbnio/Kompendium.git") - developerConnection.set("scm:git:ssh://github.com/bkbnio/Kompendium.git") - url.set("https://github.com/bkbnio/Kompendium.git") - } - } - } - } -} - -signing { - val signingKey: String? by project - val signingPassword: String? by project - useInMemoryPgpKeys(signingKey, signingPassword) - sign(publishing.publications) + val ktorVersion: String by project + implementation(group = "io.ktor", name = "ktor-server-core", version = ktorVersion) + implementation(group = "io.ktor", name = "ktor-webjars", version = ktorVersion) + implementation(group = "org.webjars", name = "swagger-ui", version = "4.1.3") } diff --git a/settings.gradle.kts b/settings.gradle.kts index d868ec877..9a87c3191 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -1,6 +1,8 @@ rootProject.name = "kompendium" +include("kompendium-annotations") include("kompendium-core") +include("kompendium-oas") include("kompendium-auth") include("kompendium-swagger-ui") include("kompendium-playground") @@ -8,4 +10,10 @@ include("kompendium-locations") // Feature Previews enableFeaturePreview("TYPESAFE_PROJECT_ACCESSORS") -enableFeaturePreview("VERSION_CATALOGS") + +pluginManagement { + repositories { + gradlePluginPortal() + mavenLocal() + } +}