63 lines
1.4 KiB
TypeScript
63 lines
1.4 KiB
TypeScript
/**
|
|
* Helper para garantir que o token seja passado para todas requisições Convex
|
|
*
|
|
* Este store reativa garante que quando o token mudar no authStore,
|
|
* todos os clientes Convex sejam atualizados automaticamente.
|
|
*/
|
|
|
|
import { authStore } from './auth.svelte';
|
|
import { browser } from '$app/environment';
|
|
|
|
const convexClients = new Set<any>();
|
|
|
|
/**
|
|
* Registrar um cliente Convex para receber atualizações de token
|
|
*/
|
|
export function registerConvexClient(client: any) {
|
|
if (!browser) return;
|
|
|
|
convexClients.add(client);
|
|
|
|
// Configurar token inicial
|
|
if (authStore.token && client.setAuth) {
|
|
client.setAuth(authStore.token);
|
|
}
|
|
|
|
// Retornar função de limpeza
|
|
return () => {
|
|
convexClients.delete(client);
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Atualizar token em todos clientes registrados
|
|
*/
|
|
function updateAllClients() {
|
|
if (!browser) return;
|
|
|
|
const token = authStore.token;
|
|
convexClients.forEach((client) => {
|
|
if (client && typeof client.setAuth === 'function') {
|
|
if (token) {
|
|
client.setAuth(token);
|
|
} else {
|
|
client.clearAuth?.();
|
|
}
|
|
}
|
|
});
|
|
}
|
|
|
|
// Observar mudanças no token e atualizar clientes
|
|
if (browser) {
|
|
// Usar uma abordagem reativa simples
|
|
let lastToken: string | null = null;
|
|
|
|
setInterval(() => {
|
|
const currentToken = authStore.token;
|
|
if (currentToken !== lastToken) {
|
|
lastToken = currentToken;
|
|
updateAllClients();
|
|
}
|
|
}, 500); // Verificar a cada 500ms
|
|
}
|