-
Notifications
You must be signed in to change notification settings - Fork 53
/
ChangeTodoStatusMutation.js
60 lines (53 loc) · 1.63 KB
/
ChangeTodoStatusMutation.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import { commitMutation, graphql } from 'react-relay';
import { ConnectionHandler } from 'relay-runtime';
const mutation = graphql`
mutation ChangeTodoStatusMutation($input: ChangeTodoStatusInput!) {
changeTodoStatus(input: $input) {
viewer {
id
numCompletedTodos
}
todo {
id
complete
}
}
}
`;
function sharedUpdater(store, user, todoProxy) {
// In principle this could add to the active connection, but such an
// interaction is not possible from the front end.
const userProxy = store.get(user.id);
const status = todoProxy.getValue('complete') ? 'active' : 'completed';
const connection = ConnectionHandler.getConnection(
userProxy, 'TodoList_todos', { status },
);
if (connection) {
ConnectionHandler.deleteNode(connection, todoProxy.getValue('id'));
}
}
function commit(environment, user, todo, complete) {
return commitMutation(environment, {
mutation,
variables: {
input: { id: todo.id, complete },
},
updater(store) {
const payload = store.getRootField('changeTodoStatus');
sharedUpdater(store, user, payload.getLinkedRecord('todo'));
},
optimisticUpdater(store) {
const todoProxy = store.get(todo.id);
todoProxy.setValue(complete, 'complete');
sharedUpdater(store, user, todoProxy);
const userProxy = store.get(user.id);
const numCompletedTodos = userProxy.getValue('numCompletedTodos');
if (numCompletedTodos != null) {
userProxy.setValue(
numCompletedTodos + (complete ? 1 : -1), 'numCompletedTodos',
);
}
},
});
}
export default { commit };