39 lines
1.1 KiB
TypeScript
39 lines
1.1 KiB
TypeScript
import { Client, cacheExchange, fetchExchange } from '@urql/core';
|
|
import { authExchange } from '@urql/exchange-auth';
|
|
import { get } from 'svelte/store';
|
|
import { user, refreshToken } from '../auth/authStore';
|
|
|
|
export function createClient() {
|
|
return new Client({
|
|
url: import.meta.env.PUBLIC_GRAPHQL_URI,
|
|
exchanges: [
|
|
cacheExchange,
|
|
authExchange(async (utils) => ({
|
|
addAuthToOperation(operation) {
|
|
const currentUser = get(user);
|
|
if (!currentUser?.access_token) return operation;
|
|
return utils.appendHeaders(operation, {
|
|
Authorization: `Bearer ${currentUser.access_token}`,
|
|
});
|
|
},
|
|
didAuthError(error) {
|
|
return error.graphQLErrors?.some(
|
|
(e) => e.extensions?.code === 'AUTH_NOT_AUTHENTICATED'
|
|
);
|
|
},
|
|
async refreshAuth() {
|
|
const newUser = await refreshToken();
|
|
if (!newUser) {
|
|
// Refresh failed, redirect to login
|
|
window.location.href = '/';
|
|
}
|
|
},
|
|
})),
|
|
fetchExchange,
|
|
],
|
|
});
|
|
}
|
|
|
|
// Singleton for use in components
|
|
export const client = createClient();
|