-
Notifications
You must be signed in to change notification settings - Fork 6
/
store.js
111 lines (105 loc) · 2.44 KB
/
store.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
import Vue from 'vue';
import Vuex from 'vuex';
import apolloClient from './apollo.js';
import gql from 'graphql-tag';
Vue.use(Vuex);
// apolloClient.subscribe returns an Observable instance
// I've put the observer and observable here for simplicity but this should go into its own module
const fruitsSubscriptionObservable = apolloClient.subscribe({
query: gql`
subscription {
Fruit {
mutation
node {
id
name
color {
name
}
}
previousValues {
id
}
}
}
`,
});
let fruitsSubscriptionObserver;
const store = new Vuex.Store({
state: {
fruits: {},
},
mutations: {
SET_FRUITS(state, fruits){
// having an object instead of an array makes the other methods easier
// since we can use Vue.set() and Vue.delete()
const object = {};
fruits.map((fruit) => {
object[fruit.id] = fruit;
});
state.fruits = object;
},
ADD_FRUIT(state, fruit){
Vue.set(state.fruits, fruit.id, fruit);
},
UPDATE_FRUIT(state, fruit){
Vue.set(state.fruits, fruit.id, fruit);
},
DELETE_FRUIT(state, fruit){
Vue.delete(state.fruits, fruit.id);
},
},
actions: {
getFruits(context){
apolloClient.query({
query: gql`
{
allFruits {
id
name
color {
name
}
}
}
`
}).then((result) => {
context.commit('SET_FRUITS', result.data.allFruits);
});
},
// You call this action to start the sunscription
subscribeToFruits(context){
fruitsSubscriptionObserver = fruitsSubscriptionObserver.subscribe({
next(data){
// mutation will say the type of GraphQL mutation `CREATED`, `UPDATED` or `DELETED`
console.log(data.Fruit.mutation);
// node is the actual data of the result of the GraphQL mutation
console.log(data.Fruit);
// then call your store mutation as usual
switch (data.Fruit.mutation) {
case 'CREATED':
context.commit('ADD_FRUIT', data.Fruit.node);
break;
case 'UPDATED':
context.commit('UPDATE_FRUIT', data.Fruit.node);
break;
case 'DELETED':
context.commit('DELETE_FRUIT', data.Fruit.previousValues);
break;
}
},
error(error){
console.log(error);
}
});
},
// You call this action to stop the subscription
unsubscribeFromFruits(context){
if (fruitsSubscriptionObserver) {
fruitsSubscriptionObserver.unsubscribe();
fruitsSubscriptionObserver = null;
}
},
}
});
export default store;