50 lines
1.4 KiB
TypeScript
50 lines
1.4 KiB
TypeScript
import {
|
|
GUEST_CART_KEY,
|
|
GUEST_CART_URL_PARAM,
|
|
} from "@/lib/meshkee/config";
|
|
import { normalizeGuestLines } from "@/lib/meshkee/format";
|
|
import type { GuestCartLine } from "@/lib/meshkee/types";
|
|
|
|
function parseLines(raw: string | null): GuestCartLine[] {
|
|
if (!raw) return [];
|
|
try {
|
|
const parsed = JSON.parse(raw);
|
|
return Array.isArray(parsed) ? normalizeGuestLines(parsed) : [];
|
|
} catch {
|
|
return [];
|
|
}
|
|
}
|
|
|
|
export function readGuestCart(): GuestCartLine[] {
|
|
if (typeof window === "undefined") return [];
|
|
return parseLines(localStorage.getItem(GUEST_CART_KEY));
|
|
}
|
|
|
|
export function writeGuestCart(items: GuestCartLine[]) {
|
|
if (typeof window === "undefined") return;
|
|
const normalized = normalizeGuestLines(items);
|
|
localStorage.setItem(GUEST_CART_KEY, JSON.stringify(normalized));
|
|
}
|
|
|
|
export function clearGuestCart() {
|
|
if (typeof window === "undefined") return;
|
|
localStorage.removeItem(GUEST_CART_KEY);
|
|
}
|
|
|
|
export function encodeGuestCartForUrl(items: GuestCartLine[]): string {
|
|
const payload = normalizeGuestLines(items).map((item) => ({
|
|
id: item.id,
|
|
name: item.name,
|
|
...(item.slug ? { slug: item.slug } : {}),
|
|
price: item.price,
|
|
image: item.image ?? null,
|
|
quantity: item.quantity,
|
|
}));
|
|
return btoa(unescape(encodeURIComponent(JSON.stringify(payload))))
|
|
.replace(/\+/g, "-")
|
|
.replace(/\//g, "_")
|
|
.replace(/=+$/g, "");
|
|
}
|
|
|
|
export { GUEST_CART_URL_PARAM };
|