├── .env ├── .github ├── dependabot.yml └── workflows │ └── gradle.yml ├── .gitignore ├── .sdkmanrc ├── LICENSE ├── NOTICE ├── README.md ├── build.gradle.kts ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle.kts └── src ├── main ├── kotlin │ └── com │ │ └── example │ │ └── demo │ │ ├── DemoApplication.kt │ │ ├── datafetchers │ │ ├── ArtworkUploadDataFetcher.kt │ │ ├── ReviewsDataFetcher.kt │ │ └── ShowsDataFetcher.kt │ │ ├── dataloaders │ │ └── ReviewsDataLoader.kt │ │ ├── generated │ │ ├── DgsConstants.kt │ │ └── types │ │ │ ├── Image.kt │ │ │ ├── Review.kt │ │ │ ├── Show.kt │ │ │ ├── SubmittedReview.kt │ │ │ ├── Subscription.kt │ │ │ └── TitleFormat.kt │ │ ├── instrumentation │ │ └── ExampleTracingInstrumentation.kt │ │ ├── scalars │ │ └── DateTimeScalarRegistration.kt │ │ └── services │ │ ├── ReviewsService.kt │ │ └── ShowsService.kt └── resources │ ├── application.properties │ └── schema │ └── schema.graphqls └── test └── kotlin └── com └── example └── demo ├── DgsExampleSmokeTest.kt └── datafetchers ├── ReviewSubscriptionTest.kt └── ShowsDataFetcherTest.kt /.env: -------------------------------------------------------------------------------- 1 | sdk env 2 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "gradle" 4 | directory: "/" 5 | schedule: 6 | interval: "daily" 7 | - package-ecosystem: "github-actions" 8 | directory: "/" 9 | schedule: 10 | interval: "daily" 11 | -------------------------------------------------------------------------------- /.github/workflows/gradle.yml: -------------------------------------------------------------------------------- 1 | # This workflow will build a Java project with Gradle 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-gradle 3 | 4 | name: Java CI with Gradle 5 | 6 | on: 7 | push: 8 | branches: [ main ] 9 | pull_request: 10 | branches: [ main ] 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - uses: actions/checkout@v4.1.1 19 | - name: Set up JDK 17 20 | uses: actions/setup-java@v4 21 | with: 22 | distribution: 'zulu' 23 | java-version: 17 24 | - name: Grant execute permission for gradlew 25 | run: chmod +x gradlew 26 | - name: Build with Gradle 27 | run: ./gradlew build 28 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/**/build/ 6 | !**/src/test/**/build/ 7 | 8 | ### STS ### 9 | .apt_generated 10 | .classpath 11 | .factorypath 12 | .project 13 | .settings 14 | .springBeans 15 | .sts4-cache 16 | bin/ 17 | !**/src/main/**/bin/ 18 | !**/src/test/**/bin/ 19 | 20 | ### IntelliJ IDEA ### 21 | .idea 22 | *.iws 23 | *.iml 24 | *.ipr 25 | out/ 26 | !**/src/main/**/out/ 27 | !**/src/test/**/out/ 28 | 29 | ### NetBeans ### 30 | /nbproject/private/ 31 | /nbbuild/ 32 | /dist/ 33 | /nbdist/ 34 | /.nb-gradle/ 35 | 36 | ### VS Code ### 37 | .vscode/ 38 | uploaded-images -------------------------------------------------------------------------------- /.sdkmanrc: -------------------------------------------------------------------------------- 1 | # Enable auto-env through the sdkman_auto_env config 2 | # Add key=value pairs of SDKs to use below 3 | java=17.0.3-zulu 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Netflix/dgs-examples-kotlin/33595ca9e11bac17f31b1c7d4fcc956d6b43050e/NOTICE -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Kotlin DGS Framework example 2 | ===== 3 | 4 | This repository is an example application for the [DGS Framework](https://netflix.github.io/dgs). 5 | The example is a standalone GraphQL server in Java. 6 | 7 | It shows the following features: 8 | * [Datafetchers](https://github.com/Netflix/dgs-examples-kotlin/blob/main/src/main/kotlin/com/example/demo/datafetchers/ShowsDataFetcher.kt#L34) 9 | * [Mutations](https://github.com/Netflix/dgs-examples-kotlin/blob/main/src/main/kotlin/com/example/demo/datafetchers/ReviewsDataFetcher.kt#L56) 10 | * [DataLoader to prevent the N+1 problem](https://github.com/Netflix/dgs-examples-kotlin/blob/main/src/main/kotlin/com/example/demo/datafetchers/ReviewsDataFetcher.kt#L46) 11 | * [Query testing](https://github.com/Netflix/dgs-examples-kotlin/blob/main/src/test/kotlin/com/example/demo/datafetchers/ShowsDataFetcherTest.kt#L74) 12 | * [Using a generated Query API](https://github.com/Netflix/dgs-examples-kotlin/blob/main/src/test/kotlin/com/example/demo/datafetchers/ShowsDataFetcherTest.kt#L124) 13 | * [File Upload](https://github.com/Netflix/dgs-examples-kotlin/blob/main/src/main/kotlin/com/example/demo/datafetchers/ArtworkUploadDataFetcher.kt#L34) 14 | * [Using the Gradle codegen plugin](https://github.com/Netflix/dgs-examples-kotlin/blob/main/build.gradle.kts#L50) 15 | * [A custom instrumentation implementation](https://github.com/Netflix/dgs-examples-kotlin/blob/main/src/main/kotlin/com/example/demo/instrumentation/ExampleTracingInstrumentation.kt) 16 | * [Subscriptions](https://github.com/Netflix/dgs-examples-kotlin/blob/main/src/main/kotlin/com/example/demo/datafetchers/ReviewsDataFetcher.kt#L64) 17 | * [Testing a subscription](https://github.com/Netflix/dgs-examples-kotlin/blob/main/src/test/kotlin/com/example/demo/datafetchers/ReviewSubscriptionTest.kt#L57) 18 | * [Registering an optional scalar from graphql-java](https://github.com/Netflix/dgs-examples-kotlin/blob/main/src/main/kotlin/com/example/demo/scalars/DateTimeScalarRegistration.kt#L32) 19 | 20 | Other examples 21 | --- 22 | 23 | There are other examples of using the DGS framework as well: 24 | 25 | * [Java implementation of this example](https://github.com/Netflix/dgs-examples-java) 26 | * [Federation examples (with Apollo Gateway)](https://github.com/Netflix/dgs-federation-example) 27 | 28 | Shows and Reviews 29 | ---- 30 | 31 | This example is built around two main types: [Show](https://github.com/Netflix/dgs-examples-kotlin/blob/main/src/main/resources/schema/schema.graphqls#L14) and [Review](https://github.com/Netflix/dgs-examples-kotlin/blob/main/src/main/resources/schema/schema.graphqls#L22). 32 | A `Show` represents a series or movie you would find on Netflix. 33 | For ease of running the demo, the list of shows is hardcoded in [ShowsServiceImpl](https://github.com/Netflix/dgs-examples-kotlin/blob/main/src/main/kotlin/com/example/demo/services/ShowsService.kt#L32). 34 | A show can have `Reviews`. 35 | Again, for ease of running the demo, a list of reviews is generated during startup for each show in [DefaultReviewsService](https://github.com/Netflix/dgs-examples-kotlin/blob/main/src/main/kotlin/com/example/demo/services/ReviewsService.kt#L61). 36 | 37 | Reviews can also be added by users of the API using a [mutation](https://github.com/Netflix/dgs-examples-kotlin/blob/main/src/main/resources/schema/schema.graphqls#L6), and a [GraphQL Subscription](https://github.com/Netflix/dgs-examples-kotlin/blob/main/src/main/resources/schema/schema.graphqls#L11) is available to watch for added reviews. 38 | 39 | There's also a mutation available to add [Artwork](https://github.com/Netflix/dgs-examples-kotlin/blob/main/src/main/resources/schema/schema.graphqls#L7) for a show, demonstrating file uploads. 40 | Uploaded files are stored in a folder `uploaded-images` in the work directory where ethe application is started. 41 | 42 | Starting the example 43 | ---- 44 | 45 | The example requires Java 11. 46 | Run the application in an IDE using its [main class](https://github.com/Netflix/dgs-examples-kotlin/blob/main/src/main/kotlin/com/example/demo/DemoApplication.kt) or using Gradle: 47 | 48 | ``` 49 | ./gradlew bootRun 50 | ``` 51 | 52 | Interact with the application using GraphiQL on http://localhost:8080/graphiql. 53 | -------------------------------------------------------------------------------- /build.gradle.kts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import org.gradle.api.tasks.testing.logging.TestExceptionFormat.FULL 18 | import org.gradle.api.tasks.testing.logging.TestLogEvent.* 19 | 20 | 21 | plugins { 22 | kotlin("jvm") version "2.1.0" 23 | kotlin("plugin.spring") version "2.1.0" 24 | id("org.springframework.boot") version "3.3.5" 25 | id("io.spring.dependency-management") version "1.1.6" 26 | id("nebula.dependency-recommender") version "11.0.0" 27 | id("nebula.netflixoss") version "11.3.2" 28 | } 29 | 30 | group = "com.example" 31 | version = "0.0.1-SNAPSHOT" 32 | 33 | java { 34 | toolchain { 35 | languageVersion.set(JavaLanguageVersion.of(17)) 36 | } 37 | } 38 | 39 | repositories { 40 | mavenCentral() 41 | // ---- 42 | // Before we release the DGS Framework our CI Pipeline tests this project against the current snapshot. 43 | // To support that we need to have `mavenLocal` support. 44 | mavenLocal() 45 | // ---- 46 | } 47 | 48 | dependencyManagement { 49 | imports { 50 | mavenBom("com.netflix.graphql.dgs:graphql-dgs-platform-dependencies:9.1.3") 51 | } 52 | } 53 | 54 | dependencies { 55 | //implementation(platform("com.netflix.graphql.dgs:graphql-dgs-platform-dependencies:9.1.3")) 56 | implementation("com.netflix.graphql.dgs:graphql-dgs-spring-graphql-starter") 57 | implementation("com.netflix.graphql.dgs:graphql-dgs-client") 58 | implementation("com.netflix.graphql.dgs:graphql-dgs-extended-scalars") 59 | implementation("name.nkonev.multipart-spring-graphql:multipart-spring-graphql:1.1.4") 60 | implementation("org.springframework.boot:spring-boot-starter-web") 61 | implementation("com.fasterxml.jackson.module:jackson-module-kotlin") 62 | implementation("jakarta.annotation:jakarta.annotation-api:3.0.+") 63 | implementation("net.datafaker:datafaker:2.1.0") 64 | implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core") 65 | implementation("org.jetbrains.kotlinx:kotlinx-coroutines-jdk8") 66 | testImplementation("name.nkonev.multipart-spring-graphql:multipart-spring-graphql:1.1.4") 67 | 68 | constraints { 69 | implementation("com.graphql-java:graphql-java") { 70 | version { 71 | strictly("[22,23[") 72 | } 73 | } 74 | } 75 | 76 | testImplementation("com.netflix.graphql.dgs:graphql-dgs-spring-graphql-starter-test") 77 | testImplementation("org.springframework.boot:spring-boot-starter-test") 78 | testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.9.0") 79 | } 80 | 81 | tasks.withType { 82 | useJUnitPlatform() 83 | testLogging { 84 | events(FAILED, STANDARD_ERROR, SKIPPED) 85 | exceptionFormat = FULL 86 | showExceptions = true 87 | showCauses = true 88 | showStackTraces = true 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Netflix/dgs-examples-kotlin/33595ca9e11bac17f31b1c7d4fcc956d6b43050e/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | # This is normally unused 84 | # shellcheck disable=SC2034 85 | APP_BASE_NAME=${0##*/} 86 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 87 | APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit 88 | 89 | # Use the maximum available, or set MAX_FD != -1 to use that value. 90 | MAX_FD=maximum 91 | 92 | warn () { 93 | echo "$*" 94 | } >&2 95 | 96 | die () { 97 | echo 98 | echo "$*" 99 | echo 100 | exit 1 101 | } >&2 102 | 103 | # OS specific support (must be 'true' or 'false'). 104 | cygwin=false 105 | msys=false 106 | darwin=false 107 | nonstop=false 108 | case "$( uname )" in #( 109 | CYGWIN* ) cygwin=true ;; #( 110 | Darwin* ) darwin=true ;; #( 111 | MSYS* | MINGW* ) msys=true ;; #( 112 | NONSTOP* ) nonstop=true ;; 113 | esac 114 | 115 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 116 | 117 | 118 | # Determine the Java command to use to start the JVM. 119 | if [ -n "$JAVA_HOME" ] ; then 120 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 121 | # IBM's JDK on AIX uses strange locations for the executables 122 | JAVACMD=$JAVA_HOME/jre/sh/java 123 | else 124 | JAVACMD=$JAVA_HOME/bin/java 125 | fi 126 | if [ ! -x "$JAVACMD" ] ; then 127 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 128 | 129 | Please set the JAVA_HOME variable in your environment to match the 130 | location of your Java installation." 131 | fi 132 | else 133 | JAVACMD=java 134 | if ! command -v java >/dev/null 2>&1 135 | then 136 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | fi 142 | 143 | # Increase the maximum file descriptors if we can. 144 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 145 | case $MAX_FD in #( 146 | max*) 147 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 148 | # shellcheck disable=SC3045 149 | MAX_FD=$( ulimit -H -n ) || 150 | warn "Could not query maximum file descriptor limit" 151 | esac 152 | case $MAX_FD in #( 153 | '' | soft) :;; #( 154 | *) 155 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 156 | # shellcheck disable=SC3045 157 | ulimit -n "$MAX_FD" || 158 | warn "Could not set maximum file descriptor limit to $MAX_FD" 159 | esac 160 | fi 161 | 162 | # Collect all arguments for the java command, stacking in reverse order: 163 | # * args from the command line 164 | # * the main class name 165 | # * -classpath 166 | # * -D...appname settings 167 | # * --module-path (only if needed) 168 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 169 | 170 | # For Cygwin or MSYS, switch paths to Windows format before running java 171 | if "$cygwin" || "$msys" ; then 172 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 173 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 174 | 175 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 176 | 177 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 178 | for arg do 179 | if 180 | case $arg in #( 181 | -*) false ;; # don't mess with options #( 182 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 183 | [ -e "$t" ] ;; #( 184 | *) false ;; 185 | esac 186 | then 187 | arg=$( cygpath --path --ignore --mixed "$arg" ) 188 | fi 189 | # Roll the args list around exactly as many times as the number of 190 | # args, so each arg winds up back in the position where it started, but 191 | # possibly modified. 192 | # 193 | # NB: a `for` loop captures its iteration list before it begins, so 194 | # changing the positional parameters here affects neither the number of 195 | # iterations, nor the values presented in `arg`. 196 | shift # remove old arg 197 | set -- "$@" "$arg" # push replacement arg 198 | done 199 | fi 200 | 201 | 202 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 203 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 204 | 205 | # Collect all arguments for the java command; 206 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 207 | # shell script including quotes and variable substitutions, so put them in 208 | # double quotes to make sure that they get re-expanded; and 209 | # * put everything else in single quotes, so that it's not re-expanded. 210 | 211 | set -- \ 212 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 213 | -classpath "$CLASSPATH" \ 214 | org.gradle.wrapper.GradleWrapperMain \ 215 | "$@" 216 | 217 | # Stop when "xargs" is not available. 218 | if ! command -v xargs >/dev/null 2>&1 219 | then 220 | die "xargs is not available" 221 | fi 222 | 223 | # Use "xargs" to parse quoted args. 224 | # 225 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 226 | # 227 | # In Bash we could simply go: 228 | # 229 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 230 | # set -- "${ARGS[@]}" "$@" 231 | # 232 | # but POSIX shell has neither arrays nor command substitution, so instead we 233 | # post-process each arg (as a line of input to sed) to backslash-escape any 234 | # character that might be a shell metacharacter, then use eval to reverse 235 | # that process (while maintaining the separation between arguments), and wrap 236 | # the whole thing up as a single "set" statement. 237 | # 238 | # This will of course break if any of these variables contains a newline or 239 | # an unmatched quote. 240 | # 241 | 242 | eval "set -- $( 243 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 244 | xargs -n1 | 245 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 246 | tr '\n' ' ' 247 | )" '"$@"' 248 | 249 | exec "$JAVACMD" "$@" 250 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | @rem This is normally unused 30 | set APP_BASE_NAME=%~n0 31 | set APP_HOME=%DIRNAME% 32 | 33 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 34 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 35 | 36 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 37 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 38 | 39 | @rem Find java.exe 40 | if defined JAVA_HOME goto findJavaFromJavaHome 41 | 42 | set JAVA_EXE=java.exe 43 | %JAVA_EXE% -version >NUL 2>&1 44 | if %ERRORLEVEL% equ 0 goto execute 45 | 46 | echo. 47 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 48 | echo. 49 | echo Please set the JAVA_HOME variable in your environment to match the 50 | echo location of your Java installation. 51 | 52 | goto fail 53 | 54 | :findJavaFromJavaHome 55 | set JAVA_HOME=%JAVA_HOME:"=% 56 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 57 | 58 | if exist "%JAVA_EXE%" goto execute 59 | 60 | echo. 61 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 62 | echo. 63 | echo Please set the JAVA_HOME variable in your environment to match the 64 | echo location of your Java installation. 65 | 66 | goto fail 67 | 68 | :execute 69 | @rem Setup the command line 70 | 71 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 72 | 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if %ERRORLEVEL% equ 0 goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | set EXIT_CODE=%ERRORLEVEL% 85 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 86 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 87 | exit /b %EXIT_CODE% 88 | 89 | :mainEnd 90 | if "%OS%"=="Windows_NT" endlocal 91 | 92 | :omega 93 | -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | rootProject.name = "dgs-examples-kotlin" 18 | -------------------------------------------------------------------------------- /src/main/kotlin/com/example/demo/DemoApplication.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.example.demo 18 | 19 | import org.springframework.boot.autoconfigure.SpringBootApplication 20 | import org.springframework.boot.runApplication 21 | 22 | @SpringBootApplication 23 | class DemoApplication 24 | 25 | fun main(args: Array) { 26 | runApplication(*args) 27 | } 28 | -------------------------------------------------------------------------------- /src/main/kotlin/com/example/demo/datafetchers/ArtworkUploadDataFetcher.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.example.demo.datafetchers 18 | 19 | import com.example.demo.generated.DgsConstants 20 | import com.example.demo.generated.types.Image 21 | import com.netflix.graphql.dgs.DgsComponent 22 | import com.netflix.graphql.dgs.DgsData 23 | import com.netflix.graphql.dgs.DgsMutation 24 | import com.netflix.graphql.dgs.InputArgument 25 | import org.springframework.web.multipart.MultipartFile 26 | import java.nio.file.Files 27 | import java.nio.file.Paths 28 | import java.util.* 29 | import kotlin.streams.toList 30 | 31 | @DgsComponent 32 | class ArtworkUploadDataFetcher { 33 | @DgsMutation 34 | fun addArtwork(@InputArgument showId: Int, @InputArgument upload: MultipartFile): List { 35 | val uploadDir = Paths.get("uploaded-images") 36 | if (!Files.exists(uploadDir)) { 37 | Files.createDirectories(uploadDir) 38 | } 39 | 40 | Files.newOutputStream( 41 | uploadDir.resolve( 42 | "show-$showId-${UUID.randomUUID()}.${upload.originalFilename?.substringAfterLast(".")}" 43 | ) 44 | ).use { it.write(upload.bytes) } 45 | 46 | return Files.list(uploadDir) 47 | .filter { it.fileName.toString().startsWith("show-$showId-") } 48 | .map { it.fileName.toString() } 49 | .map { Image(url = it) }.toList() 50 | } 51 | } -------------------------------------------------------------------------------- /src/main/kotlin/com/example/demo/datafetchers/ReviewsDataFetcher.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.example.demo.datafetchers 18 | 19 | import com.example.demo.dataloaders.ReviewsDataLoader 20 | import com.example.demo.generated.DgsConstants 21 | import com.example.demo.generated.types.Review 22 | import com.example.demo.generated.types.Show 23 | import com.example.demo.generated.types.SubmittedReview 24 | import com.example.demo.services.ReviewsService 25 | import com.netflix.graphql.dgs.* 26 | import org.dataloader.DataLoader 27 | import org.reactivestreams.Publisher 28 | import java.util.concurrent.CompletableFuture 29 | 30 | @DgsComponent 31 | class ReviewsDataFetcher(private val reviewsService: ReviewsService) { 32 | 33 | /** 34 | * This datafetcher will be called to resolve the "reviews" field on a Show. 35 | * It's invoked for each individual Show, so if we would load 10 shows, this method gets called 10 times. 36 | * To avoid the N+1 problem this datafetcher uses a DataLoader. 37 | * Although the DataLoader is called for each individual show ID, it will batch up the actual loading to a single method call to the "load" method in the ReviewsDataLoader. 38 | * For this to work correctly, the datafetcher needs to return a CompletableFuture. 39 | */ 40 | @DgsData(parentType = DgsConstants.SHOW.TYPE_NAME, field = DgsConstants.SHOW.Reviews) 41 | fun reviews(dfe: DgsDataFetchingEnvironment): CompletableFuture> { 42 | //Instead of loading a DataLoader by name, we can use the DgsDataFetchingEnvironment and pass in the DataLoader classname. 43 | val reviewsDataLoader: DataLoader> = dfe.getDataLoader(ReviewsDataLoader::class.java) 44 | 45 | //Because the reviews field is on Show, the getSource() method will return the Show instance. 46 | val show : Show? = dfe.getSource() 47 | 48 | //Load the reviews from the DataLoader. This call is async and will be batched by the DataLoader mechanism. 49 | return show?.id?.let { reviewsDataLoader.load(it) } ?: CompletableFuture.completedFuture(emptyList()) 50 | } 51 | 52 | @DgsMutation 53 | fun addReview(@InputArgument review: SubmittedReview): List { 54 | reviewsService.saveReview(review) 55 | 56 | return reviewsService.reviewsForShow(review.showId)?: emptyList() 57 | } 58 | 59 | @DgsSubscription 60 | fun reviewAdded(@InputArgument showId: Int): Publisher { 61 | return reviewsService.getReviewsPublisher() 62 | } 63 | } -------------------------------------------------------------------------------- /src/main/kotlin/com/example/demo/datafetchers/ShowsDataFetcher.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.example.demo.datafetchers 18 | 19 | import com.example.demo.generated.types.Show 20 | import com.example.demo.services.ShowsService 21 | import com.netflix.graphql.dgs.DgsComponent 22 | import com.netflix.graphql.dgs.DgsQuery 23 | import com.netflix.graphql.dgs.InputArgument 24 | 25 | import kotlinx.coroutines.coroutineScope 26 | 27 | @DgsComponent 28 | class ShowsDataFetcher(private val showsService: ShowsService) { 29 | 30 | /** 31 | * This datafetcher resolves the `shows` field on Query. 32 | * It uses an @InputArgument to get the titleFilter from the Query if one is defined. 33 | * As an implementation detail, it leverages Kotlin Coroutines as an output type. 34 | * 35 | */ 36 | @DgsQuery 37 | suspend fun shows(@InputArgument titleFilter : String?): List = coroutineScope { 38 | if(titleFilter != null) { 39 | showsService.shows().filter { it.title.contains(titleFilter) } 40 | } else { 41 | showsService.shows() 42 | } 43 | } 44 | } -------------------------------------------------------------------------------- /src/main/kotlin/com/example/demo/dataloaders/ReviewsDataLoader.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.example.demo.dataloaders 18 | 19 | import com.example.demo.generated.types.Review 20 | import com.example.demo.services.ReviewsService 21 | import com.netflix.graphql.dgs.DgsDataLoader 22 | import org.dataloader.MappedBatchLoader 23 | import java.util.concurrent.CompletableFuture 24 | import java.util.concurrent.CompletionStage 25 | import kotlin.streams.toList 26 | 27 | @DgsDataLoader(name = "reviews") 28 | class ReviewsDataLoader(val reviewsService: ReviewsService): MappedBatchLoader> { 29 | /** 30 | * This method will be called once, even if multiple datafetchers use the load() method on the DataLoader. 31 | * This way reviews can be loaded for all the Shows in a single call instead of per individual Show. 32 | */ 33 | override fun load(keys: MutableSet): CompletionStage>> { 34 | return CompletableFuture.supplyAsync { reviewsService.reviewsForShows(keys.stream().toList()) } 35 | } 36 | 37 | } -------------------------------------------------------------------------------- /src/main/kotlin/com/example/demo/generated/DgsConstants.kt: -------------------------------------------------------------------------------- 1 | package com.example.demo.generated 2 | 3 | import kotlin.String 4 | 5 | public object DgsConstants { 6 | public const val QUERY_TYPE: String = "Query" 7 | 8 | public const val Mutation_TYPE: String = "Mutation" 9 | 10 | public const val Subscription_TYPE: String = "Subscription" 11 | 12 | public object QUERY { 13 | public const val TYPE_NAME: String = "Query" 14 | 15 | public const val Shows: String = "shows" 16 | 17 | public object SHOWS_INPUT_ARGUMENT { 18 | public const val TitleFilter: String = "titleFilter" 19 | } 20 | } 21 | 22 | public object MUTATION { 23 | public const val TYPE_NAME: String = "Mutation" 24 | 25 | public const val AddReview: String = "addReview" 26 | 27 | public const val AddArtwork: String = "addArtwork" 28 | 29 | public object ADDREVIEW_INPUT_ARGUMENT { 30 | public const val Review: String = "review" 31 | } 32 | 33 | public object ADDARTWORK_INPUT_ARGUMENT { 34 | public const val ShowId: String = "showId" 35 | 36 | public const val Upload: String = "upload" 37 | } 38 | } 39 | 40 | public object SUBSCRIPTION { 41 | public const val TYPE_NAME: String = "Subscription" 42 | 43 | public const val ReviewAdded: String = "reviewAdded" 44 | 45 | public object REVIEWADDED_INPUT_ARGUMENT { 46 | public const val ShowId: String = "showId" 47 | } 48 | } 49 | 50 | public object SHOW { 51 | public const val TYPE_NAME: String = "Show" 52 | 53 | public const val Id: String = "id" 54 | 55 | public const val Title: String = "title" 56 | 57 | public const val ReleaseYear: String = "releaseYear" 58 | 59 | public const val Reviews: String = "reviews" 60 | 61 | public const val Artwork: String = "artwork" 62 | 63 | public object TITLE_INPUT_ARGUMENT { 64 | public const val Format: String = "format" 65 | } 66 | } 67 | 68 | public object REVIEW { 69 | public const val TYPE_NAME: String = "Review" 70 | 71 | public const val Username: String = "username" 72 | 73 | public const val StarScore: String = "starScore" 74 | 75 | public const val SubmittedDate: String = "submittedDate" 76 | } 77 | 78 | public object IMAGE { 79 | public const val TYPE_NAME: String = "Image" 80 | 81 | public const val Url: String = "url" 82 | } 83 | 84 | public object TITLEFORMAT { 85 | public const val TYPE_NAME: String = "TitleFormat" 86 | 87 | public const val Uppercase: String = "uppercase" 88 | } 89 | 90 | public object SUBMITTEDREVIEW { 91 | public const val TYPE_NAME: String = "SubmittedReview" 92 | 93 | public const val ShowId: String = "showId" 94 | 95 | public const val Username: String = "username" 96 | 97 | public const val StarScore: String = "starScore" 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /src/main/kotlin/com/example/demo/generated/types/Image.kt: -------------------------------------------------------------------------------- 1 | package com.example.demo.generated.types 2 | 3 | import com.fasterxml.jackson.`annotation`.JsonProperty 4 | import kotlin.String 5 | 6 | public data class Image( 7 | @JsonProperty("url") 8 | public val url: String? = null, 9 | ) { 10 | public companion object 11 | } 12 | -------------------------------------------------------------------------------- /src/main/kotlin/com/example/demo/generated/types/Review.kt: -------------------------------------------------------------------------------- 1 | package com.example.demo.generated.types 2 | 3 | import com.fasterxml.jackson.`annotation`.JsonProperty 4 | import java.time.OffsetDateTime 5 | import kotlin.Int 6 | import kotlin.String 7 | 8 | public data class Review( 9 | @JsonProperty("username") 10 | public val username: String? = null, 11 | @JsonProperty("starScore") 12 | public val starScore: Int? = null, 13 | @JsonProperty("submittedDate") 14 | public val submittedDate: OffsetDateTime? = null, 15 | ) { 16 | public companion object 17 | } 18 | -------------------------------------------------------------------------------- /src/main/kotlin/com/example/demo/generated/types/Show.kt: -------------------------------------------------------------------------------- 1 | package com.example.demo.generated.types 2 | 3 | import com.fasterxml.jackson.`annotation`.JsonProperty 4 | import kotlin.Int 5 | import kotlin.String 6 | import kotlin.collections.List 7 | 8 | public data class Show( 9 | @JsonProperty("id") 10 | public val id: Int, 11 | @JsonProperty("title") 12 | public val title: String, 13 | @JsonProperty("releaseYear") 14 | public val releaseYear: Int? = null, 15 | @JsonProperty("reviews") 16 | public val reviews: List? = null, 17 | @JsonProperty("artwork") 18 | public val artwork: List? = null, 19 | ) { 20 | public companion object 21 | } 22 | -------------------------------------------------------------------------------- /src/main/kotlin/com/example/demo/generated/types/SubmittedReview.kt: -------------------------------------------------------------------------------- 1 | package com.example.demo.generated.types 2 | 3 | import com.fasterxml.jackson.`annotation`.JsonProperty 4 | import kotlin.Int 5 | import kotlin.String 6 | 7 | public data class SubmittedReview( 8 | @JsonProperty("showId") 9 | public val showId: Int, 10 | @JsonProperty("username") 11 | public val username: String, 12 | @JsonProperty("starScore") 13 | public val starScore: Int, 14 | ) { 15 | public companion object 16 | } 17 | -------------------------------------------------------------------------------- /src/main/kotlin/com/example/demo/generated/types/Subscription.kt: -------------------------------------------------------------------------------- 1 | package com.example.demo.generated.types 2 | 3 | import com.fasterxml.jackson.`annotation`.JsonProperty 4 | 5 | public data class Subscription( 6 | @JsonProperty("reviewAdded") 7 | public val reviewAdded: Review? = null, 8 | ) { 9 | public companion object 10 | } 11 | -------------------------------------------------------------------------------- /src/main/kotlin/com/example/demo/generated/types/TitleFormat.kt: -------------------------------------------------------------------------------- 1 | package com.example.demo.generated.types 2 | 3 | import com.fasterxml.jackson.`annotation`.JsonProperty 4 | import kotlin.Boolean 5 | 6 | public data class TitleFormat( 7 | @JsonProperty("uppercase") 8 | public val uppercase: Boolean? = null, 9 | ) { 10 | public companion object 11 | } 12 | -------------------------------------------------------------------------------- /src/main/kotlin/com/example/demo/instrumentation/ExampleTracingInstrumentation.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.example.demo.instrumentation 18 | 19 | import graphql.ExecutionResult 20 | import graphql.execution.instrumentation.InstrumentationContext 21 | import graphql.execution.instrumentation.InstrumentationState 22 | import graphql.execution.instrumentation.SimplePerformantInstrumentation 23 | import graphql.execution.instrumentation.parameters.InstrumentationCreateStateParameters 24 | import graphql.execution.instrumentation.parameters.InstrumentationExecutionParameters 25 | import graphql.execution.instrumentation.parameters.InstrumentationFieldFetchParameters 26 | import graphql.schema.DataFetcher 27 | import graphql.schema.GraphQLNonNull 28 | import graphql.schema.GraphQLObjectType 29 | import org.slf4j.Logger 30 | import org.slf4j.LoggerFactory 31 | import org.springframework.stereotype.Component 32 | import java.util.concurrent.CompletableFuture 33 | 34 | /** 35 | * Example Instrumentation class that prints the time each datafetcher takes. 36 | */ 37 | @Component 38 | class ExampleTracingInstrumentation: SimplePerformantInstrumentation() { 39 | 40 | val logger : Logger = LoggerFactory.getLogger(ExampleTracingInstrumentation::class.java) 41 | 42 | override fun createState(parameters: InstrumentationCreateStateParameters): InstrumentationState { 43 | return TraceState() 44 | } 45 | 46 | override fun beginExecution(parameters: InstrumentationExecutionParameters, state: InstrumentationState): InstrumentationContext? { 47 | require(state is TraceState) 48 | state.traceStartTime = System.currentTimeMillis() 49 | 50 | return super.beginExecution(parameters, state) 51 | } 52 | 53 | override fun instrumentDataFetcher(dataFetcher: DataFetcher<*>, parameters: InstrumentationFieldFetchParameters, state: InstrumentationState): DataFetcher<*> { 54 | 55 | // We only care about user code 56 | if(parameters.isTrivialDataFetcher || parameters.executionStepInfo.path.toString().startsWith("/__schema")) { 57 | return dataFetcher 58 | } 59 | 60 | val dataFetcherName = findDatafetcherTag(parameters) 61 | 62 | return DataFetcher { environment -> 63 | val startTime = System.currentTimeMillis() 64 | val result = dataFetcher.get(environment) 65 | if(result is CompletableFuture<*>) { 66 | result.whenComplete { _,_ -> 67 | val totalTime = System.currentTimeMillis() - startTime 68 | logger.info("Async datafetcher '$dataFetcherName' took ${totalTime}ms") 69 | } 70 | } else { 71 | val totalTime = System.currentTimeMillis() - startTime 72 | logger.info("Datafetcher '$dataFetcherName': ${totalTime}ms") 73 | } 74 | 75 | result 76 | } 77 | } 78 | 79 | override fun instrumentExecutionResult(executionResult: ExecutionResult, parameters: InstrumentationExecutionParameters, state: InstrumentationState): CompletableFuture { 80 | require(state is TraceState) 81 | val totalTime = System.currentTimeMillis() - state.traceStartTime 82 | logger.info("Total execution time: ${totalTime}ms") 83 | 84 | return super.instrumentExecutionResult(executionResult, parameters, state) 85 | } 86 | 87 | private fun findDatafetcherTag(parameters: InstrumentationFieldFetchParameters): String { 88 | val type = parameters.executionStepInfo.parent.type 89 | val parentType = if (type is GraphQLNonNull) { 90 | type.wrappedType as GraphQLObjectType 91 | } else { 92 | type as GraphQLObjectType 93 | } 94 | 95 | return "${parentType.name}.${parameters.executionStepInfo.path.segmentName}" 96 | } 97 | 98 | data class TraceState(var traceStartTime: Long = 0): InstrumentationState 99 | } -------------------------------------------------------------------------------- /src/main/kotlin/com/example/demo/scalars/DateTimeScalarRegistration.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.example.demo.scalars 18 | 19 | import com.netflix.graphql.dgs.DgsComponent 20 | import com.netflix.graphql.dgs.DgsRuntimeWiring 21 | import graphql.scalars.ExtendedScalars 22 | import graphql.schema.idl.RuntimeWiring 23 | 24 | /** 25 | * graphql-java provides optional scalars in the graphql-java-extended-scalars library. 26 | * We can wire a scalar from this library by adding the scalar to the RuntimeWiring. 27 | */ 28 | @DgsComponent 29 | class DateTimeScalarRegistration { 30 | 31 | @DgsRuntimeWiring 32 | fun addScalar(builder: RuntimeWiring.Builder): RuntimeWiring.Builder { 33 | return builder.scalar(ExtendedScalars.DateTime) 34 | } 35 | } -------------------------------------------------------------------------------- /src/main/kotlin/com/example/demo/services/ReviewsService.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.example.demo.services 18 | 19 | import com.example.demo.generated.types.Review 20 | import com.example.demo.generated.types.SubmittedReview 21 | import net.datafaker.Faker 22 | import org.reactivestreams.Publisher 23 | import org.slf4j.LoggerFactory 24 | import org.springframework.stereotype.Service 25 | import reactor.core.publisher.ConnectableFlux 26 | import reactor.core.publisher.Flux 27 | import reactor.core.publisher.FluxSink 28 | import java.time.OffsetDateTime 29 | import java.time.ZoneId 30 | import java.time.ZoneOffset 31 | import java.util.concurrent.TimeUnit 32 | import java.util.stream.IntStream 33 | import org.springframework.beans.factory.InitializingBean 34 | 35 | interface ReviewsService { 36 | fun reviewsForShow(showId: Int): List? 37 | fun reviewsForShows(showIds: List): Map> 38 | fun saveReview(reviewInput: SubmittedReview) 39 | fun getReviewsPublisher(): Publisher 40 | } 41 | 42 | /** 43 | * This service emulates a data store. 44 | * For convenience in the demo we just generate Reviews in memory, but imagine this would be backed by for example a database. 45 | * If this was indeed backed by a database, it would be very important to avoid the N+1 problem, which means we need to use a DataLoader to call this class. 46 | */ 47 | @Service 48 | class DefaultReviewsService(private val showsService: ShowsService): ReviewsService, InitializingBean { 49 | private val logger = LoggerFactory.getLogger(ReviewsService::class.java) 50 | 51 | private val reviews = mutableMapOf>() 52 | private lateinit var reviewsStream : FluxSink 53 | private lateinit var reviewsPublisher: ConnectableFlux 54 | 55 | override fun afterPropertiesSet() { 56 | val faker = Faker() 57 | 58 | //For each show we generate a random set of reviews. 59 | showsService.shows().forEach { show -> 60 | val generatedReviews = IntStream.range(0, faker.number().numberBetween(1, 20)).mapToObj { 61 | val date = 62 | faker.date().past(300, TimeUnit.DAYS).toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime() 63 | Review( 64 | username = faker.name().username(), 65 | starScore = faker.number().numberBetween(0, 6), 66 | submittedDate = OffsetDateTime.of(date, ZoneOffset.UTC) 67 | ) 68 | }.toList().toMutableList() 69 | 70 | reviews[show.id] = generatedReviews 71 | } 72 | 73 | val publisher = Flux.create { emitter -> 74 | reviewsStream = emitter 75 | } 76 | 77 | 78 | reviewsPublisher = publisher.publish() 79 | reviewsPublisher.connect() 80 | 81 | } 82 | 83 | 84 | /** 85 | * Hopefully nobody calls this for multiple shows within a single query, that would indicate the N+1 problem! 86 | */ 87 | override fun reviewsForShow(showId: Int): List? { 88 | return reviews[showId] 89 | } 90 | 91 | /** 92 | * This is the method we want to call when loading reviews for multiple shows. 93 | * If this code was backed by a relational database, it would select reviews for all requested shows in a single SQL query. 94 | */ 95 | override fun reviewsForShows(showIds: List): Map> { 96 | logger.info("Loading reviews for shows ${showIds.joinToString()}") 97 | 98 | return reviews.filter { showIds.contains(it.key) } 99 | } 100 | 101 | override fun saveReview(reviewInput: SubmittedReview) { 102 | val reviewsForMovie = reviews.getOrPut(reviewInput.showId, { mutableListOf() }) 103 | val review = Review( 104 | username = reviewInput.username, 105 | starScore = reviewInput.starScore, 106 | submittedDate = OffsetDateTime.now() 107 | ) 108 | reviewsForMovie.add(review) 109 | reviewsStream.next(review) 110 | 111 | logger.info("Review added {}", review) 112 | } 113 | 114 | override fun getReviewsPublisher(): Publisher { 115 | return reviewsPublisher 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /src/main/kotlin/com/example/demo/services/ShowsService.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.example.demo.services 18 | 19 | import com.example.demo.generated.types.Show 20 | import org.springframework.stereotype.Service 21 | 22 | interface ShowsService { 23 | fun shows(): List 24 | } 25 | 26 | /** 27 | * This service gives a fixed in-memory collection of Shows. 28 | * In a more realistic implementation the Shows could be loaded from a datastore. 29 | */ 30 | @Service 31 | class BasicShowsService : ShowsService { 32 | override fun shows(): List { 33 | return listOf( 34 | Show(id = 1, title = "Stranger Things", releaseYear = 2016), 35 | Show(id = 2, title = "Ozark", releaseYear = 2017), 36 | Show(id = 3, title = "The Crown", releaseYear = 2016), 37 | Show(id = 4, title = "Dead to Me", releaseYear = 2019), 38 | Show(id = 5, title = "Orange is the New Black", releaseYear = 2013) 39 | ) 40 | } 41 | } -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright 2021 Netflix, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | 17 | spring.web.resources.static-locations=file:uploaded-images -------------------------------------------------------------------------------- /src/main/resources/schema/schema.graphqls: -------------------------------------------------------------------------------- 1 | type Query { 2 | shows(titleFilter: String): [Show] 3 | } 4 | 5 | type Mutation { 6 | addReview(review: SubmittedReview): [Review] 7 | addArtwork(showId: Int!, upload: Upload!): [Image]! @skipcodegen 8 | } 9 | 10 | type Subscription { 11 | reviewAdded(showId: Int!): Review 12 | } 13 | 14 | type Show { 15 | id: Int! 16 | title(format: TitleFormat): String! 17 | releaseYear: Int 18 | reviews: [Review] 19 | artwork: [Image] 20 | } 21 | 22 | input TitleFormat { 23 | uppercase: Boolean 24 | } 25 | 26 | type Review { 27 | username: String 28 | starScore: Int 29 | submittedDate: DateTime 30 | } 31 | 32 | input SubmittedReview { 33 | showId: Int! 34 | username: String! 35 | starScore: Int! 36 | } 37 | 38 | type Image { 39 | url: String 40 | } 41 | 42 | scalar DateTime 43 | scalar Upload 44 | directive @skipcodegen on FIELD_DEFINITION -------------------------------------------------------------------------------- /src/test/kotlin/com/example/demo/DgsExampleSmokeTest.kt: -------------------------------------------------------------------------------- 1 | package com.example.demo 2 | 3 | import org.junit.jupiter.api.Test 4 | import org.springframework.beans.factory.annotation.Autowired 5 | import org.springframework.boot.autoconfigure.EnableAutoConfiguration 6 | import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc 7 | import org.springframework.boot.test.context.SpringBootTest 8 | import org.springframework.http.MediaType 9 | import org.springframework.test.web.servlet.MockMvc 10 | import org.springframework.test.web.servlet.request.MockMvcRequestBuilders 11 | import org.springframework.test.web.servlet.result.MockMvcResultMatchers 12 | 13 | /** 14 | * Example of a smoke test that will interact with the HTTP /graphql endpoint via MockMVC 15 | */ 16 | @SpringBootTest 17 | @EnableAutoConfiguration 18 | @AutoConfigureMockMvc 19 | class DgsExampleSmokeTest { 20 | 21 | @Autowired 22 | lateinit var mvc: MockMvc 23 | 24 | @Test 25 | fun `Queries for shows`() { 26 | mvc.perform( 27 | MockMvcRequestBuilders 28 | .post("/graphql") 29 | .contentType(MediaType.APPLICATION_JSON) 30 | .content( 31 | """ 32 | | { 33 | | "query": "query some_movies { shows { title releaseYear } }" 34 | | }""".trimMargin() 35 | ) 36 | ).andExpect(MockMvcResultMatchers.status().isOk) 37 | .andExpect( 38 | MockMvcResultMatchers.content().json( 39 | """ 40 | | { 41 | | "data": { 42 | | "shows":[ 43 | | { "title":"Stranger Things", "releaseYear":2016 }, 44 | | { "title":"Ozark", "releaseYear":2017 }, 45 | | { "title":"The Crown","releaseYear":2016 }, 46 | | {"title":"Dead to Me","releaseYear":2019}, 47 | | {"title":"Orange is the New Black","releaseYear":2013} 48 | | ] 49 | | } 50 | |} 51 | |""".trimMargin(), 52 | false 53 | ) 54 | ) 55 | } 56 | } -------------------------------------------------------------------------------- /src/test/kotlin/com/example/demo/datafetchers/ReviewSubscriptionTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.example.demo.datafetchers 18 | 19 | import com.example.demo.generated.types.Review 20 | import com.example.demo.scalars.DateTimeScalarRegistration 21 | import com.example.demo.services.DefaultReviewsService 22 | import com.example.demo.services.ShowsService 23 | import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper 24 | import com.netflix.graphql.dgs.DgsQueryExecutor 25 | import com.netflix.graphql.dgs.scalars.UploadScalar 26 | import com.netflix.graphql.dgs.test.EnableDgsTest 27 | import graphql.ExecutionResult 28 | import org.assertj.core.api.Assertions 29 | import org.intellij.lang.annotations.Language 30 | import org.junit.jupiter.api.Test 31 | import org.reactivestreams.Publisher 32 | import org.reactivestreams.Subscriber 33 | import org.reactivestreams.Subscription 34 | import org.springframework.beans.factory.annotation.Autowired 35 | import org.springframework.boot.test.context.SpringBootTest 36 | import org.springframework.boot.test.mock.mockito.MockBean 37 | import java.util.concurrent.CopyOnWriteArrayList 38 | 39 | /** 40 | * Test the review added subscription. 41 | * The subscription query returns a Publisher. 42 | * Each time a review is added, a new ExecutionResult is given to subscriber. 43 | * Normally, this publisher is consumed by the Websocket/SSE subscription handler and you don't deal with this code directly, but for testing purposes it's useful to use the stream directly. 44 | */ 45 | @SpringBootTest(classes = [DefaultReviewsService::class, ReviewsDataFetcher::class, DateTimeScalarRegistration::class, UploadScalar::class]) 46 | @EnableDgsTest 47 | class ReviewSubscriptionTest { 48 | @Autowired 49 | lateinit var dgsQueryExecutor: DgsQueryExecutor 50 | 51 | @MockBean 52 | lateinit var showsService: ShowsService 53 | 54 | @Test 55 | fun reviewSubscription() { 56 | val executionResult = dgsQueryExecutor.execute("subscription { reviewAdded(showId: 1) {starScore} }") 57 | val reviewPublisher = executionResult.getData>() 58 | val reviews = CopyOnWriteArrayList() 59 | 60 | reviewPublisher.subscribe(object: Subscriber { 61 | override fun onSubscribe(s: Subscription) { 62 | s.request(2) 63 | } 64 | 65 | override fun onNext(t: ExecutionResult) { 66 | val data = t.getData>() 67 | reviews.add(jacksonObjectMapper().convertValue(data["reviewAdded"], Review::class.java)) 68 | } 69 | 70 | override fun onError(t: Throwable?) { 71 | } 72 | 73 | override fun onComplete() { 74 | } 75 | }) 76 | 77 | addReview() 78 | addReview() 79 | 80 | Assertions.assertThat(reviews.size).isEqualTo(2) 81 | 82 | } 83 | 84 | private fun addReview(): ExecutionResult { 85 | // val graphQLQueryRequest = 86 | // GraphQLQueryRequest( 87 | // AddReviewGraphQLQuery.Builder() 88 | // .review(SubmittedReview(1, "testuser", 5)) 89 | // .build(), 90 | // AddReviewProjectionRoot() 91 | // .username() 92 | // .starScore() 93 | // ) 94 | 95 | @Language("GraphQL") 96 | val query = """ 97 | mutation AddReview { 98 | addReview(review: { 99 | showId: 1 100 | username: "testuser" 101 | starScore: 5 102 | }) { 103 | username 104 | starScore 105 | } 106 | } 107 | """.trimIndent() 108 | 109 | return dgsQueryExecutor.execute(query) 110 | } 111 | } -------------------------------------------------------------------------------- /src/test/kotlin/com/example/demo/datafetchers/ShowsDataFetcherTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.example.demo.datafetchers 18 | 19 | import com.example.demo.dataloaders.ReviewsDataLoader 20 | import com.example.demo.generated.types.Review 21 | import com.example.demo.generated.types.Show 22 | import com.example.demo.scalars.DateTimeScalarRegistration 23 | import com.example.demo.services.ReviewsService 24 | import com.example.demo.services.ShowsService 25 | import com.netflix.graphql.dgs.DgsQueryExecutor 26 | import com.netflix.graphql.dgs.scalars.UploadScalar 27 | import com.netflix.graphql.dgs.test.EnableDgsTest 28 | import org.assertj.core.api.Assertions.assertThat 29 | import org.junit.jupiter.api.BeforeEach 30 | import org.junit.jupiter.api.Disabled 31 | import org.junit.jupiter.api.Test 32 | import org.mockito.Mockito.`when` 33 | import org.springframework.beans.factory.annotation.Autowired 34 | import org.springframework.boot.test.context.SpringBootTest 35 | import org.springframework.boot.test.mock.mockito.MockBean 36 | import java.time.OffsetDateTime 37 | 38 | @SpringBootTest(classes = [ShowsDataFetcher::class, ReviewsDataFetcher::class, ReviewsDataLoader::class,DateTimeScalarRegistration::class, UploadScalar::class]) 39 | @EnableDgsTest 40 | class ShowsDataFetcherTest { 41 | 42 | @Autowired 43 | lateinit var dgsQueryExecutor: DgsQueryExecutor 44 | 45 | @MockBean 46 | lateinit var showsService: ShowsService 47 | 48 | @MockBean 49 | lateinit var reviewsService: ReviewsService 50 | 51 | @BeforeEach 52 | fun before() { 53 | `when`(showsService.shows()).thenAnswer { listOf(Show(id = 1, title = "mock title", releaseYear = 2020)) } 54 | `when`(reviewsService.reviewsForShows(listOf(1))).thenAnswer { 55 | mapOf( 56 | Pair( 57 | 1, listOf( 58 | Review("DGS User", 5, OffsetDateTime.now()), 59 | Review("DGS User 2", 3, OffsetDateTime.now()), 60 | ) 61 | ) 62 | ) 63 | } 64 | } 65 | 66 | @Test 67 | fun shows() { 68 | val titles: List = dgsQueryExecutor.executeAndExtractJsonPath( 69 | """ 70 | { 71 | shows { 72 | title 73 | releaseYear 74 | } 75 | } 76 | """.trimIndent(), "data.shows[*].title" 77 | ) 78 | 79 | assertThat(titles).contains("mock title") 80 | } 81 | 82 | @Test 83 | @Disabled("Unstable test in Github Actions") 84 | fun showsWithException() { 85 | `when`(showsService.shows()).thenThrow(RuntimeException("nothing to see here")) 86 | 87 | val result = dgsQueryExecutor.execute( 88 | """ 89 | { 90 | shows { 91 | title 92 | releaseYear 93 | } 94 | } 95 | """.trimIndent() 96 | ) 97 | 98 | assertThat(result.errors).isNotEmpty 99 | assertThat(result.errors[0].message).isEqualTo("java.lang.RuntimeException: nothing to see here") 100 | } 101 | 102 | // @Test 103 | // fun showsWithQueryApi() { 104 | // val graphQLQueryRequest = 105 | // GraphQLQueryRequest( 106 | // ShowsGraphQLQuery.Builder() 107 | // .build(), 108 | // ShowsProjectionRoot().title() 109 | // ) 110 | // val titles = dgsQueryExecutor.executeAndExtractJsonPath>( 111 | // graphQLQueryRequest.serialize(), 112 | // "data.shows[*].title" 113 | // ) 114 | // assertThat(titles).contains("mock title") 115 | // } 116 | // 117 | // @Test 118 | // fun showWithReviews() { 119 | // val graphQLQueryRequest = 120 | // GraphQLQueryRequest( 121 | // ShowsGraphQLQuery.Builder() 122 | // .build(), 123 | // ShowsProjectionRoot() 124 | // .title(TitleFormat(uppercase = true)).parent 125 | // .reviews() 126 | // .username() 127 | // .starScore() 128 | // ) 129 | // val shows = dgsQueryExecutor.executeAndExtractJsonPathAsObject( 130 | // graphQLQueryRequest.serialize(), 131 | // "data.shows[*]", 132 | // object : TypeRef>() {}) 133 | // assertThat(shows.size).isEqualTo(1) 134 | // assertThat(shows[0].reviews?.size).isEqualTo(2) 135 | // } 136 | // 137 | // @Test 138 | // fun addReviewMutation() { 139 | // 140 | // val graphQLQueryRequest = 141 | // GraphQLQueryRequest( 142 | // AddReviewGraphQLQuery.Builder() 143 | // .review(SubmittedReview(1, "testuser", 5)) 144 | // .build(), 145 | // AddReviewProjectionRoot() 146 | // .username() 147 | // .starScore() 148 | // ) 149 | // 150 | // val executionResult = dgsQueryExecutor.execute(graphQLQueryRequest.serialize()) 151 | // assertThat(executionResult.errors).isEmpty() 152 | // 153 | // verify(reviewsService).reviewsForShow(1) 154 | // } 155 | } --------------------------------------------------------------------------------