Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Flatten nested argument maps in QuerydslDataFetcher #1085

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -142,21 +142,34 @@ public String getDescription() {
* @param environment contextual info for the GraphQL request
* @return the resulting predicate
*/
@SuppressWarnings({"unchecked"})
protected Predicate buildPredicate(DataFetchingEnvironment environment) {
MultiValueMap<String, Object> parameters = new LinkedMultiValueMap<>();
QuerydslBindings bindings = new QuerydslBindings();

EntityPath<?> path = SimpleEntityPathResolver.INSTANCE.createPath(this.domainType.getType());
this.customizer.customize(bindings, path);

for (Map.Entry<String, Object> entry : getArgumentValues(environment).entrySet()) {
parameters.putAll(flatten(null, getArgumentValues(environment)));

return BUILDER.getPredicate(this.domainType, parameters, bindings);
}

@SuppressWarnings("unchecked")
private MultiValueMap<String, Object> flatten(@Nullable String prefix, Map<String, Object> inputParameters) {
MultiValueMap<String, Object> parameters = new LinkedMultiValueMap<>();

for (Map.Entry<String, Object> entry : inputParameters.entrySet()) {
Object value = entry.getValue();
List<Object> values = (value instanceof List) ? (List<Object>) value : Collections.singletonList(value);
parameters.put(entry.getKey(), values);
if (value instanceof Map<?, ?> nested) {
parameters.addAll(flatten(entry.getKey(), (Map<String, Object>) nested));
}
else {
List<Object> values = (value instanceof List) ? (List<Object>) value : Collections.singletonList(value);
parameters.put(((prefix != null) ? prefix + "." : "") + entry.getKey(), values);
}
}

return BUILDER.getPredicate(this.domainType, parameters, bindings);
return parameters;
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/*
* Copyright 2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.springframework.graphql;

import com.querydsl.core.types.Path;
import com.querydsl.core.types.PathMetadata;
import com.querydsl.core.types.dsl.EntityPathBase;
import com.querydsl.core.types.dsl.NumberPath;
import com.querydsl.core.types.dsl.StringPath;

import static com.querydsl.core.types.PathMetadataFactory.forVariable;

/**
* QAuthor is a Querydsl query type for Author
*/
public class QAuthor extends EntityPathBase<Author> {
private static final long serialVersionUID = 1773522017L;
public static final QAuthor author = new QAuthor("author");
public final StringPath firstName = createString("firstName");
public final NumberPath<Long> id = createNumber("id", Long.class);
public final StringPath lastName = createString("lastName");

public QAuthor(String variable) {
super(Author.class, forVariable(variable));
}

public QAuthor(Path<? extends Author> path) {
super(path.getType(), path.getMetadata());
}

public QAuthor(PathMetadata metadata) {
super(Author.class, metadata);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -18,30 +18,43 @@

import com.querydsl.core.types.Path;
import com.querydsl.core.types.PathMetadata;
import com.querydsl.core.types.PathMetadataFactory;
import com.querydsl.core.types.dsl.EntityPathBase;
import com.querydsl.core.types.dsl.NumberPath;
import com.querydsl.core.types.dsl.PathInits;
import com.querydsl.core.types.dsl.StringPath;

import static com.querydsl.core.types.PathMetadataFactory.forVariable;

/**
* Generated by Querydsl.
* QBook is a Querydsl query type for Book
*/
public class QBook extends EntityPathBase<Book> {
private static final long serialVersionUID = 1773522017L;
private static final PathInits INITS = PathInits.DIRECT2;
public static final QBook book = new QBook("book");
public final StringPath author = this.createString("author");
public final NumberPath<Long> id = this.createNumber("id", Long.class);
public final StringPath name = this.createString("name");
public final org.springframework.graphql.QAuthor author;
public final NumberPath<Long> id = createNumber("id", Long.class);
public final StringPath name = createString("name");

public QBook(String variable) {
super(Book.class, PathMetadataFactory.forVariable(variable));
this(Book.class, forVariable(variable), INITS);
}

public QBook(Path<? extends Book> path) {
super(path.getType(), path.getMetadata());
this(path.getType(), path.getMetadata(), PathInits.getFor(path.getMetadata(), INITS));
}

public QBook(PathMetadata metadata) {
super(Book.class, metadata);
this(metadata, PathInits.getFor(metadata, INITS));
}

public QBook(PathMetadata metadata, PathInits inits) {
this(Book.class, metadata, inits);
}

public QBook(Class<? extends Book> type, PathMetadata metadata, PathInits inits) {
super(type, metadata, inits);
this.author = inits.isInitialized("author") ? new org.springframework.graphql.QAuthor(forProperty("author")) : null;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -215,14 +215,14 @@ void shouldApplyCustomizerViaBuilder() {
.many();

graphQlSetup("books", fetcher).toWebGraphQlHandler()
.handleRequest(request("{ books(name: \"H\", author: \"Doug\") {name}}"))
.handleRequest(request("{ books(name: \"H\") {name}}"))
.block();

ArgumentCaptor<Predicate> predicateCaptor = ArgumentCaptor.forClass(Predicate.class);
verify(mockRepository).findBy(predicateCaptor.capture(), any());

Predicate predicate = predicateCaptor.getValue();
assertThat(predicate).isEqualTo(QBook.book.name.startsWith("H").and(QBook.book.author.eq("Doug")));
assertThat(predicate).isEqualTo(QBook.book.name.startsWith("H"));
}

@Test
Expand Down Expand Up @@ -346,6 +346,25 @@ void shouldNestForSingleArgumentInputType() {
assertThat(books.get(0).getName()).isEqualTo(book1.getName());
}

@Test
void shouldConsiderNestedArguments() {
Book book1 = new Book(42L, "Hitchhiker's Guide to the Galaxy", new Author(0L, "Douglas", "Adams"));
Book book2 = new Book(53L, "Breaking Bad", new Author(0L, "", "Heisenberg"));
mockRepository.saveAll(Arrays.asList(book1, book2));

String queryName = "booksByNestableCriteria";

Mono<ExecutionGraphQlResponse> responseMono =
graphQlSetup(queryName, QuerydslDataFetcher.builder(mockRepository).many())
.toGraphQlService()
.execute(request("{" + queryName + "(author: {firstName: \"Douglas\"}) {name}}"));

List<Book> books = ResponseHelper.forResponse(responseMono).toList(queryName, Book.class);

assertThat(books).hasSize(1);
assertThat(books.get(0).getName()).isEqualTo(book1.getName());
}

private static GraphQlSetup graphQlSetup(String fieldName, DataFetcher<?> fetcher) {
return GraphQlSetup.schemaResource(BookSource.schema).queryFetcher(fieldName, fetcher);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -343,12 +343,14 @@ void shouldRecordGraphQlErrorsAsTraceEvents() {

assertThat(response.errorCount()).isEqualTo(1);
assertThat(response.error(0).errorType()).isEqualTo("InvalidSyntax");
assertThat(response.error(0).message()).startsWith("Invalid syntax with offending token 'invalid'");
assertThat(response.error(0).message()).containsIgnoringCase("syntax")
.containsIgnoringCase("token").contains("'invalid'");

assertThat(observationHandler.getEvents()).hasSize(1);
Observation.Event errorEvent = observationHandler.getEvents().get(0);
assertThat(errorEvent.getName()).isEqualTo("InvalidSyntax");
assertThat(errorEvent.getContextualName()).startsWith("Invalid syntax with offending token 'invalid'");
assertThat(errorEvent.getContextualName()).containsIgnoringCase("syntax")
.containsIgnoringCase("token").contains("'invalid'");

TestObservationRegistryAssert.assertThat(this.observationRegistry).hasObservationWithNameEqualTo("graphql.request")
.that().hasLowCardinalityKeyValue("graphql.outcome", "REQUEST_ERROR")
Expand Down
7 changes: 7 additions & 0 deletions spring-graphql/src/test/resources/books/schema.graphqls
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ type Query {
bookById(id: ID): Book
booksById(id: [ID]): [Book]
books(id: ID, name: String, author: String): [Book!]!
booksByNestableCriteria(id: ID, name: String, author: AuthorCriteria): [Book!]!
booksByCriteria(criteria:BookCriteria): [Book]
booksByProjectedArguments(name: String, author: String): [Book]
booksByProjectedCriteria(criteria:BookCriteria): [Book]
Expand All @@ -21,6 +22,12 @@ input BookCriteria {
author: String
}

input AuthorCriteria {
id: ID
firstName: String
lastName: String
}

type Book {
id: ID
name: String
Expand Down