refactor: integrate current user data across components
- Replaced instances of `authStore` with `currentUser` to streamline user authentication handling. - Updated permission checks and user-related data retrieval to utilize the new `useQuery` for better performance and clarity. - Cleaned up component structures and improved formatting for consistency and readability. - Enhanced error handling and user feedback mechanisms in various components to improve user experience.
This commit is contained in:
@@ -2,7 +2,7 @@
|
||||
import { onMount } from "svelte";
|
||||
import { useConvexClient } from "convex-svelte";
|
||||
import { api } from "@sgse-app/backend/convex/_generated/api";
|
||||
import { authStore } from "$lib/stores/auth.svelte";
|
||||
import { useQuery } from "convex-svelte";
|
||||
import {
|
||||
registrarServiceWorker,
|
||||
solicitarPushSubscription,
|
||||
@@ -11,6 +11,7 @@
|
||||
} from "$lib/utils/notifications";
|
||||
|
||||
const client = useConvexClient();
|
||||
const currentUser = useQuery(api.auth.getCurrentUser, {});
|
||||
|
||||
// Capturar erros de Promise não tratados relacionados a message channel
|
||||
// Este erro geralmente vem de extensões do Chrome ou comunicação com Service Worker
|
||||
@@ -19,15 +20,14 @@
|
||||
"unhandledrejection",
|
||||
(event: PromiseRejectionEvent) => {
|
||||
const reason = event.reason;
|
||||
const errorMessage =
|
||||
reason?.message || reason?.toString() || "";
|
||||
|
||||
const errorMessage = reason?.message || reason?.toString() || "";
|
||||
|
||||
// Filtrar apenas erros relacionados a message channel fechado
|
||||
if (
|
||||
errorMessage.includes("message channel closed") ||
|
||||
errorMessage.includes("asynchronous response") ||
|
||||
(errorMessage.includes("message channel") &&
|
||||
errorMessage.includes("closed"))
|
||||
(errorMessage.includes("message channel") &&
|
||||
errorMessage.includes("closed"))
|
||||
) {
|
||||
// Prevenir que o erro apareça no console
|
||||
event.preventDefault();
|
||||
@@ -35,7 +35,7 @@
|
||||
return false;
|
||||
}
|
||||
},
|
||||
{ capture: true }
|
||||
{ capture: true },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -45,14 +45,17 @@
|
||||
|
||||
// Aguardar usuário estar autenticado
|
||||
checkAuth = setInterval(async () => {
|
||||
if (authStore.usuario && mounted) {
|
||||
if (currentUser?.data && mounted) {
|
||||
clearInterval(checkAuth!);
|
||||
checkAuth = null;
|
||||
try {
|
||||
await registrarPushSubscription();
|
||||
} catch (error) {
|
||||
// Silenciar erros de push subscription para evitar spam no console
|
||||
if (error instanceof Error && !error.message.includes("message channel")) {
|
||||
if (
|
||||
error instanceof Error &&
|
||||
!error.message.includes("message channel")
|
||||
) {
|
||||
console.error("Erro ao configurar push notifications:", error);
|
||||
}
|
||||
}
|
||||
@@ -85,11 +88,14 @@
|
||||
|
||||
// Solicitar subscription com timeout para evitar travamentos
|
||||
const subscriptionPromise = solicitarPushSubscription();
|
||||
const timeoutPromise = new Promise<null>((resolve) =>
|
||||
setTimeout(() => resolve(null), 5000)
|
||||
const timeoutPromise = new Promise<null>((resolve) =>
|
||||
setTimeout(() => resolve(null), 5000),
|
||||
);
|
||||
|
||||
const subscription = await Promise.race([subscriptionPromise, timeoutPromise]);
|
||||
const subscription = await Promise.race([
|
||||
subscriptionPromise,
|
||||
timeoutPromise,
|
||||
]);
|
||||
|
||||
if (!subscription) {
|
||||
// Não logar para evitar spam no console quando VAPID key não está configurada
|
||||
@@ -100,22 +106,34 @@
|
||||
const subscriptionData = subscriptionToJSON(subscription);
|
||||
|
||||
// Registrar no backend com timeout
|
||||
const mutationPromise = client.mutation(api.pushNotifications.registrarPushSubscription, {
|
||||
endpoint: subscriptionData.endpoint,
|
||||
keys: subscriptionData.keys,
|
||||
userAgent: navigator.userAgent,
|
||||
});
|
||||
|
||||
const timeoutMutationPromise = new Promise<{ sucesso: false; erro: string }>((resolve) =>
|
||||
setTimeout(() => resolve({ sucesso: false, erro: "Timeout" }), 5000)
|
||||
const mutationPromise = client.mutation(
|
||||
api.pushNotifications.registrarPushSubscription,
|
||||
{
|
||||
endpoint: subscriptionData.endpoint,
|
||||
keys: subscriptionData.keys,
|
||||
userAgent: navigator.userAgent,
|
||||
},
|
||||
);
|
||||
|
||||
const resultado = await Promise.race([mutationPromise, timeoutMutationPromise]);
|
||||
const timeoutMutationPromise = new Promise<{
|
||||
sucesso: false;
|
||||
erro: string;
|
||||
}>((resolve) =>
|
||||
setTimeout(() => resolve({ sucesso: false, erro: "Timeout" }), 5000),
|
||||
);
|
||||
|
||||
const resultado = await Promise.race([
|
||||
mutationPromise,
|
||||
timeoutMutationPromise,
|
||||
]);
|
||||
|
||||
if (resultado.sucesso) {
|
||||
console.log("✅ Push subscription registrada com sucesso");
|
||||
} else if (resultado.erro && !resultado.erro.includes("Timeout")) {
|
||||
console.error("❌ Erro ao registrar push subscription:", resultado.erro);
|
||||
console.error(
|
||||
"❌ Erro ao registrar push subscription:",
|
||||
resultado.erro,
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
// Ignorar erros relacionados a message channel fechado
|
||||
@@ -128,7 +146,7 @@
|
||||
|
||||
// Remover subscription ao fazer logout
|
||||
$effect(() => {
|
||||
if (!authStore.usuario) {
|
||||
if (!currentUser?.data) {
|
||||
removerPushSubscription().then(() => {
|
||||
console.log("Push subscription removida");
|
||||
});
|
||||
@@ -137,4 +155,3 @@
|
||||
</script>
|
||||
|
||||
<!-- Componente invisível - apenas lógica -->
|
||||
|
||||
|
||||
Reference in New Issue
Block a user