Skip to content

Commit

Permalink
chore: fix errors
Browse files Browse the repository at this point in the history
  • Loading branch information
hantsy committed Nov 26, 2024
1 parent 6a200a6 commit fe3fc99
Show file tree
Hide file tree
Showing 29 changed files with 290 additions and 240 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@

import com.netflix.graphql.dgs.DgsDirective;
import graphql.schema.DataFetcherFactories;
import graphql.schema.FieldCoordinates;
import graphql.schema.GraphQLFieldDefinition;
import graphql.schema.idl.SchemaDirectiveWiring;
import graphql.schema.idl.SchemaDirectiveWiringEnvironment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@DgsDirective(name = "uppercase")
@Slf4j
Expand All @@ -16,8 +16,8 @@ public GraphQLFieldDefinition onField(SchemaDirectiveWiringEnvironment<GraphQLFi

var field = env.getElement();
var parentType = env.getFieldsContainer();

var originalDataFetcher = env.getCodeRegistry().getDataFetcher(parentType, field);
var fieldCoordinates = FieldCoordinates.coordinates(parentType, field.getName());
var originalDataFetcher = env.getCodeRegistry().getDataFetcher(fieldCoordinates, field);
var dataFetcher = DataFetcherFactories.wrapDataFetcher(
originalDataFetcher,
(dataFetchingEnvironment, value) -> {
Expand All @@ -29,7 +29,7 @@ public GraphQLFieldDefinition onField(SchemaDirectiveWiringEnvironment<GraphQLFi
}
);

env.getCodeRegistry().dataFetcher(parentType, field, dataFetcher);
env.getCodeRegistry().dataFetcher(fieldCoordinates, dataFetcher);
return field;
}
}
29 changes: 16 additions & 13 deletions dgs-kotlin-co/src/main/kotlin/com/example/demo/DemoApplication.kt
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,13 @@ import com.example.demo.model.PostEntity
import com.example.demo.repository.CommentRepository
import com.example.demo.repository.PostRepository
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.runBlocking
import org.slf4j.LoggerFactory
import org.springframework.boot.ApplicationArguments
import org.springframework.boot.ApplicationRunner
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.context.event.ApplicationReadyEvent
import org.springframework.boot.runApplication
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.event.EventListener
import org.springframework.security.config.annotation.method.configuration.EnableReactiveMethodSecurity
import org.springframework.security.config.web.server.ServerHttpSecurity
import org.springframework.security.web.server.SecurityWebFilterChain
Expand All @@ -26,20 +25,24 @@ fun main(args: Array<String>) {
}

@Component
class DataInitializer(val posts: PostRepository, val comments: CommentRepository) : ApplicationRunner {
private val log = LoggerFactory.getLogger(DataInitializer::class.java)
override fun run(args: ApplicationArguments?) {
class DataInitializer(val posts: PostRepository, val comments: CommentRepository) {

companion object {
private val log = LoggerFactory.getLogger(DataInitializer::class.java)
}

@EventListener(ApplicationReadyEvent::class)
suspend fun init() {
val data = listOf(
PostEntity(title = "Learn Spring", content = "content of Learn Spring"),
PostEntity(title = "Learn Dgs framework", content = "content of Learn Dgs framework")
)
runBlocking {
comments.deleteAll()
posts.deleteAll()

val saved = posts.saveAll(data).toList()
saved.forEach { log.debug("saved: {}", it) }
}
comments.deleteAll()
posts.deleteAll()

val saved = posts.saveAll(data).toList()
saved.forEach { log.debug("saved: {}", it) }
}
}

Expand All @@ -51,7 +54,7 @@ class SecurityConfig {
fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
return http
.csrf { it.disable() }
.httpBasic{}
.httpBasic {}
.securityMatcher(PathPatternParserServerWebExchangeMatcher("/graphql"))
.build()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ class ExceptionHandlers : DataFetcherExceptionHandler {
when (val exception = handlerParameters.exception) {
is PostNotFoundException, is AuthorNotFoundException -> {
val graphqlError = TypedGraphQLError.newNotFoundBuilder()
.message(exception.message)
.message(exception.message?: "Not Found")
.path(handlerParameters.path)
.build();
CompletableFuture.completedFuture(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ class AuthorsDataFetcher(

@DgsData(parentType = DgsConstants.AUTHOR.TYPE_NAME, field = DgsConstants.AUTHOR.Posts)
suspend fun posts(dfe: DgsDataFetchingEnvironment): List<Post> {
val a: Author = dfe.getSource()
val a: Author = dfe.getSource()!!
return postService.getPostsByAuthorId(a.id).toList()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,13 @@ class PostsDataFetcher(val postService: PostService) {
fun author(dfe: DgsDataFetchingEnvironment): CompletableFuture<Author> {
val dataLoader = dfe.getDataLoader<String, Author>("authorsLoader")
val post = dfe.getSource<Post>()
return dataLoader.load(post.authorId)
return dataLoader!!.load(post!!.authorId)
}

@DgsData(parentType = DgsConstants.POST.TYPE_NAME, field = DgsConstants.POST.Comments)
fun comments(dfe: DgsDataFetchingEnvironment): CompletableFuture<List<Comment>> {
val dataLoader = dfe.getDataLoader<String, List<Comment>>(CommentsDataLoader::class.java)
val (id) = dfe.getSource<Post>()
val (id) = dfe.getSource<Post>()!!
return dataLoader.load(id)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ val beans = beans {
if (!passwordEncoder.matches(password, user.password)) {
throw BadCredentialsException("username or password was not matched.")
}
if (!user.isEnabled()) {
if (!user.isEnabled) {
throw DisabledException("user is not enabled.")
}
AuthenticationTokenWithId(user.id, username, user.authorities)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ class ExceptionHandlers : DataFetcherExceptionHandler {
return when (val exception = handlerParameters.exception) {
is PostNotFoundException, is AuthorNotFoundException -> {
val graphqlError = TypedGraphQLError.newNotFoundBuilder()
.message(exception.message)
.message(exception.message?: "Not found")
.path(handlerParameters.path)
.build();
val result = DataFetcherExceptionHandlerResult.newResult()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ class AuthDataFetcher(

@DgsMutation
fun signIn(@InputArgument credentials: Credentials, dfe: DgsDataFetchingEnvironment): Map<String, Any> {
var auth = authenticationManager.authenticate(
val auth = authenticationManager.authenticate(
UsernamePasswordAuthenticationToken(
credentials.username,
credentials.password
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package com.example.demo.gql.datafetchers

import com.example.demo.gql.DgsConstants
import com.example.demo.gql.types.*
import com.example.demo.service.AuthorNotFoundException
import com.example.demo.service.AuthorService
import com.example.demo.service.PostService
import com.netflix.graphql.dgs.*
Expand All @@ -19,7 +20,7 @@ class AuthorsDataFetcher(

@DgsData(parentType = DgsConstants.AUTHOR.TYPE_NAME, field = DgsConstants.AUTHOR.Posts)
fun posts(dfe: DgsDataFetchingEnvironment): List<Post> {
val a: Author = dfe.getSource()
val a: Author = dfe.getSource()!!
return postService.getPostsByAuthorId(a.id)
}

Expand All @@ -30,7 +31,7 @@ class AuthorsDataFetcher(

@DgsData(parentType = DgsConstants.AUTHOR.TYPE_NAME, field = DgsConstants.AUTHOR.Profile)
fun profile(dfe: DgsDataFetchingEnvironment): Profile? {
val a: Author = dfe.getSource()
val a: Author = dfe.getSource()!!
return authorService.getProfileByUserId(a.id)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,16 @@ class PostsDataFetcher(val postService: PostService) {
@DgsData(parentType = DgsConstants.POST.TYPE_NAME, field = DgsConstants.POST.Author)
fun author(dfe: DgsDataFetchingEnvironment): CompletableFuture<Author> {
val dataLoader = dfe.getDataLoader<String, Author>("authorsLoader")
val post = dfe.getSource<Post>()
return dataLoader.load(post.authorId)
val post = dfe.getSource<Post>()!!
return dataLoader!!.load(post.authorId)
}

@DgsData(parentType = DgsConstants.POST.TYPE_NAME, field = DgsConstants.POST.Comments)
fun comments(dfe: DgsDataFetchingEnvironment): CompletableFuture<List<Comment>> {
val dataLoader = dfe.getDataLoader<String, List<Comment>>(
CommentsDataLoader::class.java
)
val (id) = dfe.getSource<Post>()
val (id) = dfe.getSource<Post>()!!
return dataLoader.load(id)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,14 @@ import com.example.demo.gql.types.Author
import com.example.demo.service.AuthorService
import com.netflix.graphql.dgs.DgsDataLoader
import org.dataloader.BatchLoader
import java.util.concurrent.CompletableFuture.completedFuture
import java.util.concurrent.CompletableFuture.supplyAsync
import java.util.concurrent.CompletionStage

@DgsDataLoader(name = "authorsLoader")
class AuthorsDataLoader(val authorService: AuthorService) : BatchLoader<String, Author> {
override fun load(keys: List<String>): CompletionStage<List<Author>> = supplyAsync {
override fun load(keys: List<String>): CompletionStage<List<Author>> = completedFuture(
authorService.getAuthorByIdIn(keys)
}
)
}

Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ class CommentsDataLoader(val postService: PostService) : MappedBatchLoader<Strin
mappedComments[it] = comments.filter { (_, _, postId) -> postId == it }
}
log.info("mapped comments: {}", mappedComments)
return CompletableFuture.supplyAsync { mappedComments }
return CompletableFuture.completedFuture(mappedComments)
}

companion object {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,43 +1,47 @@
package com.example.demo.gql.scalars

import com.netflix.graphql.dgs.DgsScalar
import graphql.GraphQLContext
import graphql.execution.CoercedVariables
import graphql.language.StringValue
import graphql.language.Value
import graphql.schema.Coercing
import graphql.schema.CoercingParseLiteralException
import graphql.schema.CoercingParseValueException
import graphql.schema.CoercingSerializeException
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter


//@DgsComponent
//class DateTimeScalar {
// @DgsRuntimeWiring
// fun addScalar(builder: RuntimeWiring.Builder): RuntimeWiring.Builder {
// return builder.scalar(ExtendedScalars.DateTime)
// }
//}
import java.util.*

@DgsScalar(name = "LocalDateTime")
class LocalDateTimeScalar : Coercing<LocalDateTime, String> {
@Throws(CoercingSerializeException::class)
override fun serialize(dataFetcherResult: Any): String? {
override fun serialize(dataFetcherResult: Any, graphQLContext: GraphQLContext, locale: Locale): String? {
return when (dataFetcherResult) {
is LocalDateTime -> dataFetcherResult.format(DateTimeFormatter.ISO_DATE_TIME)
else -> throw CoercingSerializeException("Not a valid DateTime")
}
}

@Throws(CoercingParseValueException::class)
override fun parseValue(input: Any): LocalDateTime {
override fun parseValue(input: Any, graphQLContext: GraphQLContext, locale: Locale): LocalDateTime? {
return LocalDateTime.parse(input.toString(), DateTimeFormatter.ISO_DATE_TIME)
}

@Throws(CoercingParseLiteralException::class)
override fun parseLiteral(input: Any): LocalDateTime {
override fun parseLiteral(
input: Value<*>,
variables: CoercedVariables,
graphQLContext: GraphQLContext,
locale: Locale
): LocalDateTime? {
when (input) {
is StringValue -> return LocalDateTime.parse(input.value, DateTimeFormatter.ISO_DATE_TIME)
else -> throw CoercingParseLiteralException("Value is not a valid ISO date time")
}
}

override fun valueToLiteral(input: Any, graphQLContext: GraphQLContext, locale: Locale): Value<*> {
return when (input) {
is String -> StringValue.newStringValue(input).build()
else -> throw CoercingParseValueException("Value is not a string")
}
}
}
Loading

0 comments on commit fe3fc99

Please sign in to comment.