refactoring

This commit is contained in:
Kristian Duda 2024-06-28 14:14:21 +02:00
parent 5c41217ca0
commit 9b9f9496c3
2 changed files with 46 additions and 32 deletions

View File

@ -1,5 +1,5 @@
import { AjaxError } from 'lib/shopify/ajax'; import { AjaxError } from 'lib/shopify/ajax';
import { Where, create, find, findByID, update } from 'lib/shopify/payload'; import { Payload, Where } from 'lib/shopify/payload';
import { import {
Cart as PayloadCart, Cart as PayloadCart,
Category as PayloadCategory, Category as PayloadCategory,
@ -20,6 +20,8 @@ import {
ProductVariant ProductVariant
} from './types'; } from './types';
const payload = new Payload({ baseUrl: process.env.CMS_URL });
const reshapeCartItems = (lines: PayloadCart['lines']): CartItem[] => { const reshapeCartItems = (lines: PayloadCart['lines']): CartItem[] => {
return (lines ?? []).map((item) => { return (lines ?? []).map((item) => {
const product = item.product as PayloadProduct; const product = item.product as PayloadProduct;
@ -65,7 +67,7 @@ const reshapeCart = (cart: PayloadCart): Cart => {
}; };
export async function createCart(): Promise<Cart> { export async function createCart(): Promise<Cart> {
const cart = await create<PayloadCart>('carts', { lines: [] }); const cart = await payload.create<PayloadCart>('carts', { lines: [] });
return reshapeCart(cart.doc); return reshapeCart(cart.doc);
} }
@ -73,19 +75,19 @@ export async function addToCart(
cartId: string, cartId: string,
lines: { merchandiseId: string; quantity: number }[] lines: { merchandiseId: string; quantity: number }[]
): Promise<Cart> { ): Promise<Cart> {
const prevCart = await findByID<PayloadCart>('carts', cartId); const prevCart = await payload.findByID<PayloadCart>('carts', cartId);
const cartItems = await mergeItems(prevCart.lines, lines, true); const cartItems = await mergeItems(prevCart.lines, lines, true);
const cart = await update<PayloadCart>('carts', cartId, { const cart = await payload.update<PayloadCart>('carts', cartId, {
lines: cartItems lines: cartItems
}); });
return reshapeCart(cart.doc); return reshapeCart(cart.doc);
} }
export async function removeFromCart(cartId: string, lineIds: string[]): Promise<Cart> { export async function removeFromCart(cartId: string, lineIds: string[]): Promise<Cart> {
const prevCart = await findByID<PayloadCart>('carts', cartId); const prevCart = await payload.findByID<PayloadCart>('carts', cartId);
const lines = prevCart?.lines?.filter((lineItem) => !lineIds.includes(lineItem.id!)) ?? []; const lines = prevCart?.lines?.filter((lineItem) => !lineIds.includes(lineItem.id!)) ?? [];
const cart = await update<PayloadCart>('carts', cartId, { lines }); const cart = await payload.update<PayloadCart>('carts', cartId, { lines });
return reshapeCart(cart.doc); return reshapeCart(cart.doc);
} }
@ -96,7 +98,7 @@ const mergeItems = async (
): Promise<PayloadCart['lines']> => { ): Promise<PayloadCart['lines']> => {
const map = new Map((cartItems ?? []).map((item) => [item.variant, item])); const map = new Map((cartItems ?? []).map((item) => [item.variant, item]));
const products = await find<PayloadProduct>('products', { const products = await payload.find<PayloadProduct>('products', {
where: { where: {
'variants.id': { 'variants.id': {
in: lines.map((line) => line.merchandiseId) in: lines.map((line) => line.merchandiseId)
@ -133,16 +135,16 @@ export async function updateCart(
cartId: string, cartId: string,
lines: { id: string; merchandiseId: string; quantity: number }[] lines: { id: string; merchandiseId: string; quantity: number }[]
): Promise<Cart> { ): Promise<Cart> {
const prevCart = await findByID<PayloadCart>('carts', cartId); const prevCart = await payload.findByID<PayloadCart>('carts', cartId);
const cartItems = await mergeItems(prevCart.lines, lines, false); const cartItems = await mergeItems(prevCart.lines, lines, false);
const cart = await update<PayloadCart>('carts', cartId, { lines: cartItems }); const cart = await payload.update<PayloadCart>('carts', cartId, { lines: cartItems });
return reshapeCart(cart.doc); return reshapeCart(cart.doc);
} }
export async function getCart(cartId: string): Promise<Cart | undefined> { export async function getCart(cartId: string): Promise<Cart | undefined> {
try { try {
const cart = await findByID<PayloadCart>('carts', cartId); const cart = await payload.findByID<PayloadCart>('carts', cartId);
return reshapeCart(cart); return reshapeCart(cart);
} catch (error: unknown) { } catch (error: unknown) {
if (error instanceof AjaxError) { if (error instanceof AjaxError) {
@ -156,7 +158,7 @@ export async function getCart(cartId: string): Promise<Cart | undefined> {
} }
export async function getCollection(handle: string): Promise<Collection | undefined> { export async function getCollection(handle: string): Promise<Collection | undefined> {
const category = await findByID<PayloadCategory>('categories', handle); const category = await payload.findByID<PayloadCategory>('categories', handle);
return reshapeCategory(category); return reshapeCategory(category);
} }
@ -270,7 +272,7 @@ export async function getCollectionProducts({
}); });
} }
const products = await find<PayloadProduct>('products', { const products = await payload.find<PayloadProduct>('products', {
where: { where: {
and: filters and: filters
} }
@ -293,7 +295,7 @@ const reshapeCategory = (category: PayloadCategory): Collection => {
}; };
export async function getCollections(): Promise<Collection[]> { export async function getCollections(): Promise<Collection[]> {
const categories = await find<PayloadCategory>('categories', {}); const categories = await payload.find<PayloadCategory>('categories', {});
return [ return [
{ {
handle: '', handle: '',
@ -335,7 +337,7 @@ export async function getPages(): Promise<Page[]> {
} }
export async function getProduct(handle: string): Promise<Product | undefined> { export async function getProduct(handle: string): Promise<Product | undefined> {
const product = await findByID<PayloadProduct>('products', handle); const product = await payload.findByID<PayloadProduct>('products', handle);
return reshapeProduct(product); return reshapeProduct(product);
} }
@ -369,6 +371,6 @@ export async function getProducts({
}; };
} }
const products = await find<PayloadProduct>('products', { where }); const products = await payload.find<PayloadProduct>('products', { where });
return products.docs.map(reshapeProduct); return products.docs.map(reshapeProduct);
} }

View File

@ -59,24 +59,36 @@ type FindParams = {
limit?: number; limit?: number;
}; };
export const find = <T>(collection: Collection, params: FindParams) => { type PayloadOptions = {
const query = qs.stringify(params, { addQueryPrefix: true }); baseUrl?: string;
const url = `${process.env.CMS_URL}/api/${collection}${query}`;
return ajax<PaginatedDocs<T>>('GET', url);
}; };
export const findByID = <T>(collection: Collection, id: string) => { export class Payload {
const url = `${process.env.CMS_URL}/api/${collection}/${id}`; readonly baseUrl?: string;
return ajax<T>('GET', url);
};
export const create = <T extends object>(collection: Collection, body: Partial<T>) => { constructor({ baseUrl }: PayloadOptions) {
const url = `${process.env.CMS_URL}/api/${collection}`; this.baseUrl = baseUrl;
return ajax<Doc<T>>('POST', url, body); }
};
export const update = <T extends object>(collection: Collection, id: string, body: Partial<T>) => { find = <T>(collection: Collection, params: FindParams) => {
const url = `${process.env.CMS_URL}/api/${collection}/${id}`; const query = qs.stringify(params, { addQueryPrefix: true });
return ajax<Doc<T>>('PATCH', url, body);
}; const url = `${this.baseUrl}/api/${collection}${query}`;
return ajax<PaginatedDocs<T>>('GET', url);
};
findByID = <T>(collection: Collection, id: string) => {
const url = `${this.baseUrl}/api/${collection}/${id}`;
return ajax<T>('GET', url);
};
create = <T extends object>(collection: Collection, body: Partial<T>) => {
const url = `${this.baseUrl}/api/${collection}`;
return ajax<Doc<T>>('POST', url, body);
};
update = <T extends object>(collection: Collection, id: string, body: Partial<T>) => {
const url = `${this.baseUrl}/api/${collection}/${id}`;
return ajax<Doc<T>>('PATCH', url, body);
};
}