aboutsummaryrefslogtreecommitdiff
path: root/src/stores/apollo.js
blob: f84a183f4060cb4741d6fc745526cc6bc45bd1cf (plain)
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
import { ApolloError } from '@apollo/client/core';
import { readable } from 'svelte/store';
import { client } from '$/config/apollo';

/*
 * This is a generic store for use with apollo
 */

export const store = function store({ key, query, initialValue = null, variables = {} }) {

  return readable(
    {
      loading: true,
      data: initialValue,
      error: undefined
    },
    (set) => {

      const handleError = function (error) {

        return set({
          loading: false,
          data: initialValue,
          error
        });
      };

      client.watchQuery({ query, variables }).subscribe(
        (result) => {

          if (result.errors) {
            const error = new ApolloError({ graphQLErrors: result.errors });
            return handleError(error);
          }

          set({
            loading: false,
            data: result.data[key],
            error: undefined
          });
        },
        (error) => handleError(error)
      );
    }
  );
};