feat(web): add consent sync utility

This commit is contained in:
Antoni Nuñez Romeu
2026-08-26 15:11:15 +02:00
parent 8f73fdc4f8
commit a23215ad6b
+75
View File
@@ -0,0 +1,75 @@
const CONSENT_KEY = 'farmafinder_consents';
const DEFAULT_CONSENTS = {
essential: true,
analytics: false,
preferences: false,
health_data: false,
};
export function getLocalConsents() {
try {
const stored = localStorage.getItem(CONSENT_KEY);
if (stored) {
const parsed = JSON.parse(stored);
return { ...DEFAULT_CONSENTS, ...parsed, essential: true };
}
} catch {}
return { ...DEFAULT_CONSENTS };
}
export function setLocalConsents(consents) {
try {
localStorage.setItem(CONSENT_KEY, JSON.stringify(consents));
} catch {}
}
export function hasConsentChoice() {
try {
return localStorage.getItem(CONSENT_KEY) !== null;
} catch {
return false;
}
}
export async function fetchServerConsents() {
try {
const res = await fetch('/api/consents', { credentials: 'include' });
if (res.ok) {
const serverConsents = await res.json();
setLocalConsents(serverConsents);
return serverConsents;
}
} catch {}
return null;
}
export async function saveConsents(consents) {
const toSave = { ...consents, essential: true };
setLocalConsents(toSave);
try {
const res = await fetch('/api/consents', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({
categories: {
analytics: toSave.analytics,
preferences: toSave.preferences,
health_data: toSave.health_data,
},
}),
});
if (res.ok) {
const serverConsents = await res.json();
setLocalConsents(serverConsents);
return serverConsents;
}
} catch {}
return toSave;
}
export function hasConsent(category) {
const consents = getLocalConsents();
return consents[category] === true;
}