eh3rrera / graphql-java-spring-boot-example

Sample GraphQL server implemented with graphql-java and Spring Boot
MIT License
211 stars 151 forks source link

Check if value is defined for update #5

Closed KrifaYounes closed 6 years ago

KrifaYounes commented 6 years ago

I want to update lastName field of Author only if the field is defined on authorInput in updateAuthor method

how to do this ?

public Author updateAuthor(Long authorId, AuthorInput authorInput) {
        Author authorToUpdate = authorRepository.findOne(authorId);
        authorToUpdate.setFirstName(authorInput.getFirstName());

        // update lastName only if authorInput.getLastName is defined 
        authorToUpdate.setLastName(authorInput.getLastName());

        authorRepository.save(authorToUpdate);
        return authorToUpdate;
    }

type Author { id: ID! firstName: String! lastName: String books: [Book]
}

input AuthorInput { firstName: String lastName: String }

type Mutation { updateAuthor(authorId: Long!, authorInput: AuthorInput!) : Author! }

KrifaYounes commented 6 years ago

I found the answer


 public Author updateAuthor(Long authorId, AuthorInput authorInput, DataFetchingEnvironment env ) {
        Author authorToUpdate = authorRepository.findOne(authorId);

        Map<String, Object> arguments = env.getArguments();
        Map<String, Object> authorArgs = (Map<String, Object>) 
                arguments.get("authorInput");

        if (authorArgs.containsKey("firstName")) {
            authorToUpdate.setFirstName(authorInput.getFirstName());
        }

        if (authorArgs.containsKey("lastName")) {
            authorToUpdate.setLastName(authorInput.getLastName());
        }

        authorRepository.save(authorToUpdate);
        return authorToUpdate;
    }
eh3rrera commented 6 years ago

Great, thanks!