Skip to content

How do you return null from a @BatchMapping? #1136

@JBodkin-Amphora

Description

@JBodkin-Amphora

I've been trying to implement a controller which has a BatchMapping with a null value in the list being returned. Behind the scenes, this library is using reactive streams (flux/mono) which doesn't allow you to return a stream that has a null value.

What is the best way to return an optional relationship in the schema?

If you add the following test to the BatchLoadingTests file, you can reproduce the issue.

	@Test
	void batchLoaderWithNullValue() {
		String document = "{ " +
			"  booksByCriteria(criteria: {author:\"Orwell\"}) { " +
			"    author {" +
			"      firstName, " +
			"      lastName " +
			"    }" +
			"  }" +
			"}";

		this.registry.forTypePair(Long.class, Author.class)
			.registerBatchLoader((ids, env) -> Flux.fromIterable(ids.stream().<Author>map(id -> null).toList()));

		TestExecutionGraphQlService service = GraphQlSetup.schemaResource(BookSource.schema)
			.queryFetcher("booksByCriteria", env -> {
				Map<String, Object> criteria = env.getArgument("criteria");
				String authorName = (String) criteria.get("author");
				return BookSource.findBooksByAuthor(authorName).stream()
					.map(book -> new Book(book.getId(), book.getName(), book.getAuthorId()))
					.collect(Collectors.toList());
			})
			.dataFetcher("Book", "author", env -> {
				Book book = env.getSource();
				DataLoader<Long, Author> dataLoader = env.getDataLoader(Author.class.getName());
				return dataLoader.load(book.getAuthorId());
			})
			.dataLoaders(this.registry)
			.toGraphQlService();

		Mono<ExecutionGraphQlResponse> responseMono = service.execute(document);

		List<Book> books = ResponseHelper.forResponse(responseMono).toList("booksByCriteria", Book.class);
		assertThat(books).hasSize(2);

		Author author = books.get(0).getAuthor();
		assertThat(author).isNull();
	}

Metadata

Metadata

Assignees

No one assigned

    Labels

    status: invalidAn issue that we don't feel is valid

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions