aboutsummaryrefslogtreecommitdiff
path: root/src/lib/stores/apollo.ts
diff options
context:
space:
mode:
authorRuben Beltran del Rio <ruben@unlimited.pizza>2023-12-24 12:31:07 +0100
committerRuben Beltran del Rio <ruben@unlimited.pizza>2023-12-24 12:31:07 +0100
commit3d65cb04707cf3af11885995fd1110a5971d8b00 (patch)
tree7499ab3483d59138d9b421902ab4d282ea534b8f /src/lib/stores/apollo.ts
parent6ccc6f60fc85e665c8a07a169efbe8d09c9d9e8e (diff)
Don't remember what this WIP was aboutHEADmain
Diffstat (limited to 'src/lib/stores/apollo.ts')
-rw-r--r--src/lib/stores/apollo.ts62
1 files changed, 62 insertions, 0 deletions
diff --git a/src/lib/stores/apollo.ts b/src/lib/stores/apollo.ts
new file mode 100644
index 0000000..4ef1986
--- /dev/null
+++ b/src/lib/stores/apollo.ts
@@ -0,0 +1,62 @@
+import { ApolloError } from '@apollo/client/core';
+import { readable } from 'svelte/store';
+import { client } from '$lib/config/apollo';
+import type { DocumentNode, ApolloQueryResult } from '@apollo/client/core';
+
+import type { Readable } from 'svelte/store';
+
+/*
+ * This is a generic store for use with apollo
+ */
+
+type ApolloStoreConfiguration<Type> = {
+ key: string;
+ query: DocumentNode;
+ initialValue?: Type | void;
+ variables?: object;
+};
+
+type ApolloStoreState<Type> = {
+ loading: boolean;
+ data: Type | void;
+ error: Error | void;
+};
+
+export const store = function store<Type>({
+ key,
+ query,
+ initialValue = null,
+ variables = {}
+}: ApolloStoreConfiguration<Type>): Readable<ApolloStoreState<Type>> {
+ const initialState: ApolloStoreState<Type> = {
+ loading: true,
+ data: initialValue,
+ error: undefined
+ };
+
+ return readable(initialState, (set) => {
+ const handleError = function (error: Error) {
+ return set({
+ loading: false,
+ data: initialValue,
+ error
+ });
+ };
+
+ client.watchQuery({ query, variables }).subscribe(
+ (result: ApolloQueryResult<Type>) => {
+ if (result.errors) {
+ const error = new ApolloError({ graphQLErrors: result.errors });
+ return handleError(error);
+ }
+
+ set({
+ loading: false,
+ data: result.data[key],
+ error: undefined
+ });
+ },
+ (error: Error) => handleError(error)
+ );
+ });
+};