diff options
| author | Ruben Beltran del Rio <ruben@unlimited.pizza> | 2022-05-01 00:56:06 +0200 |
|---|---|---|
| committer | Ruben Beltran del Rio <ruben@unlimited.pizza> | 2022-05-01 00:56:06 +0200 |
| commit | a7cf03c192470cbab13edeb1aec99e0c66dede10 (patch) | |
| tree | 581b4430d1de958dcb666bae80a7678332134602 /src/lib/stores/apollo.ts | |
| parent | 010f307346e525ac2e4239a0549d2c1a4d6d102b (diff) | |
Update / use typescript
Diffstat (limited to 'src/lib/stores/apollo.ts')
| -rw-r--r-- | src/lib/stores/apollo.ts | 64 |
1 files changed, 64 insertions, 0 deletions
diff --git a/src/lib/stores/apollo.ts b/src/lib/stores/apollo.ts new file mode 100644 index 0000000..12463c3 --- /dev/null +++ b/src/lib/stores/apollo.ts @@ -0,0 +1,64 @@ +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) + ); + } + ); +}; |