Skip to content

Instantly share code, notes, and snippets.

@Tiim
Last active Oct 15, 2022
Embed
What would you like to do?
import { browser } from '$app/environment';
import { urls } from '@/config';
import { createClient, queryStore } from '@urql/svelte';
import { derived, readable } from 'svelte/store';
/**
* Helper function to create an urql client in a server side only load function
*
*
* @param {import('@sveltejs/kit').Cookies} cookies
* @returns
*/
export function createServerClient(cookies) {
return createClient({
url: urls.gql,
fetch,
// FIXME: if you don't need to authenticate, delete the following object:
fetchOptions: {
credentials: 'include',
headers: {
// FIXME: if you want to set a cookie adjust the cookie name
Cookie: `gql-session=${cookies.get('gql-session')}`,
},
},
});
}
/**
* Helper method to send a graphql query but use the data from the sveltekit load function initially.
*
*
* @param {any} queryArgs
* @param {any} initialValue
* @returns
*/
export function queryStoreInitialData(queryArgs, initialValue) {
if (!initialValue || (!initialValue.error && !initialValue.data)) {
throw new Error('No initial value from server');
}
let query = readable({ fetching: true });
if (browser) {
query = queryStore(queryArgs);
}
return derived(query, (value, set) => {
if (value.fetching) {
set({ ...initialValue, source: 'server', fetching: true });
} else {
set({ ...value, source: 'client' });
}
});
}
/**
* Make the result object of a urql query serialisable.
*
*
* @template T
* @param {Promise<import('@urql/svelte').OperationResult<T, any >>|import('@urql/svelte').OperationResult<T, any >} result
* @returns {Promise<{fetching:false, error: undefined | {name?: string, message?: string; graphQLErrors?: any[]; networkError?: Error; response?: any;}, data: T|undefined}>}
*/
export async function toInitialValue(result) {
const { error, data } = await result;
// required to turn class array into array of javascript objects
const errorObject = error ? {} : undefined;
if (errorObject) {
console.warn(error);
errorObject.graphQLErrors = error?.graphQLErrors?.map((e) => ({ ...e }));
errorObject.networkError = { ...error?.networkError };
errorObject.response = { value: 'response omitted' };
}
return {
fetching: false,
error: { ...error, ...errorObject },
data,
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment