]> git.r.bdr.sh - rbdr/forum/blob - src/stores/apollo.js
Add tests for header
[rbdr/forum] / src / stores / apollo.js
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 {
13 loading: true,
14 data: initialValue,
15 error: undefined
16 },
17 (set) => {
18
19 const handleError = function (error) {
20
21 return set({
22 loading: false,
23 data: initialValue,
24 error
25 });
26 };
27
28 client.watchQuery({ query, variables }).subscribe(
29 (result) => {
30
31 if (result.errors) {
32 const error = new ApolloError({ graphQLErrors: result.errors });
33 return handleError(error);
34 }
35
36 set({
37 loading: false,
38 data: result.data[key],
39 error: undefined
40 });
41 },
42 (error) => handleError(error)
43 );
44 }
45 );
46 };