Skip to content

Instantly share code, notes, and snippets.

@Tiim
Last active October 15, 2022 20:56
Show Gist options
  • Save Tiim/1adeb4d74ce7ae09d0d0aa4176a6195d to your computer and use it in GitHub Desktop.
Save Tiim/1adeb4d74ce7ae09d0d0aa4176a6195d to your computer and use it in GitHub Desktop.
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