I'm trying to create delete operation. I have a user and tasks to do. Each user has a list of tasks assigned. Here is my code of delete operation:
const Mutation = new GraphQLObjectType({
name: 'Mutation',
fields: {
deleteUser: {
type: UserType,
args: {
id: { type: new GraphQLNonNull(GraphQLID) }
},
resolve(parent, args){
var id = (args.id).toString()
let todos = Todo.find({ user_id: id });
let user = User.findById(args.id);
todos.remove();
user.findOneAndRemove();
return todos;
}
}
}
})
And here are my defined types:
const ToDoType = new GraphQLObjectType({
name: 'todoItem',
fields: () => ({
id: {type: GraphQLID},
title: {type: GraphQLString},
completed: {type: GraphQLBoolean},
user: {
type: UserType,
resolve(parent, args){
return User.findById(parent.user_id);
}
}
})
});
const UserType = new GraphQLObjectType({
name: 'user',
fields: () => ({
id: {type: GraphQLID},
name: {type: GraphQLString},
email: {type: GraphQLString},
login: {type: GraphQLString},
todos: {
type: new GraphQLList(ToDoType),
resolve(parent, args){
return Todo.find({ user_id: parent.id })
}
}
})
});
The problem is that while deleting user I want to delete all his "to do's" but according to what I put in return I can delete only one thing.. So now I have "return todos" and it deletes only todo assigned to user, but not the user. When I put there "return user" it will delete only user without his tasks. How can I delete user and his tasks at once?
The code as shown appears to actually mutate the data to delete both the user, and all their todos. I believe the confusion you're having is that the mutation operation has the "type" (i.e. what it will return) of User. That is therefore what you'd need to return from the mutation function.
More conceptually, it might be a good idea to return from that both the user and all their data, so that if the API user wanted to capture some or all of that, they could, though given privacy implications that might not be ideal. An alternative approach would be to have the mutation just return a success-or-failure status.