]>
Commit | Line | Data |
---|---|---|
1 | import { ApolloError } from '@apollo/client/core'; | |
2 | import { readable } from 'svelte/store'; | |
3 | import { client } from '$/config/apollo'; | |
4 | ||
5 | /* | |
6 | * This is a generic store for use with apollo | |
7 | */ | |
8 | ||
9 | export const store = function store({ key, query, initialValue = null, variables = {} }) { | |
10 | ||
11 | return readable({ | |
12 | loading: true, | |
13 | data: initialValue, | |
14 | error: undefined | |
15 | }, (set) => { | |
16 | ||
17 | const handleError = function (error) { | |
18 | ||
19 | return set({ | |
20 | loading: false, | |
21 | data: initialValue, | |
22 | error | |
23 | }); | |
24 | }; | |
25 | ||
26 | client.watchQuery({ query, variables }).subscribe((result) => { | |
27 | ||
28 | if (result.errors) { | |
29 | const error = new ApolloError({ graphQLErrors: result.errors }); | |
30 | return handleError(error); | |
31 | } | |
32 | ||
33 | set({ | |
34 | loading: false, | |
35 | data: result.data[key], | |
36 | error: undefined | |
37 | }); | |
38 | }, (error) => handleError(error)); | |
39 | }); | |
40 | }; |