-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcart.ts
86 lines (75 loc) · 2.35 KB
/
cart.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
'use server';
import 'server-only';
import { cookies } from 'next/headers';
import { firmhouseClient } from './firmhouse-client';
import { revalidatePath } from 'next/cache';
import { FirmhouseCart, SubscriptionStatus } from '@firmhouse/firmhouse-sdk';
import { redirect } from 'next/navigation';
import test from 'node:test';
const CART_TOKEN_COOKIE = 'firmhouse:cart';
export async function isInitialized(): Promise<boolean> {
return cookies().get(CART_TOKEN_COOKIE) !== undefined;
}
export async function getCartToken(): Promise<string> {
const token = cookies().get(CART_TOKEN_COOKIE)?.value;
if(!token) {
throw new Error("Token is not initialized")
}
return token
}
export async function clearCartToken(): Promise<void> {
cookies().delete(CART_TOKEN_COOKIE);
}
export async function getCartOrCreate() : Promise<FirmhouseCart> {
try {
const cartToken = await getCartToken()
const cart = await firmhouseClient.carts.get(cartToken)
if(cart.status !== SubscriptionStatus.Draft) {
throw new Error('Cart is already checked out')
}
return cart
} catch(e) {
// If the cart does not exists or already checked out we can redirect to create the cart
}
redirect('/cart/create')
}
export async function initializeCart() {
try {
const cartToken = await getCartToken()
const cart = await firmhouseClient.carts.getOrCreate(cartToken);
cookies().set(CART_TOKEN_COOKIE, cart.token);
return
} catch(e) {
cookies().set(CART_TOKEN_COOKIE, (await firmhouseClient.carts.create()).token)
}
}
export async function addToCart(productId: string, quantity = 1, pathToRevalidate = '/') {
if (!(await isInitialized())) {
await initializeCart();
}
const cartToken = await getCartToken();
await firmhouseClient.carts.addProduct(cartToken, {
productId,
quantity,
});
revalidatePath(pathToRevalidate);
}
export async function removeFromCart(id: string) {
await firmhouseClient.carts.removeProduct(await getCartToken(), id);
revalidatePath('/');
}
export async function updateQuantity(id: string, quantity: number) {
await firmhouseClient.carts.updateOrderedProductQuantity(
await getCartToken(),
id,
quantity
);
revalidatePath('/');
}
export async function updatePlan(planSlug: string) {
await firmhouseClient.carts.updatePlan(
await getCartToken(),
planSlug
);
revalidatePath('/');
}