Check if value is defined for update
Closed this issue · 2 comments
KrifaYounes commented
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
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
Great, thanks!