From 2c8cf68e8902d65628ac09af568807058b427330 Mon Sep 17 00:00:00 2001 From: Unchained Date: Fri, 6 Mar 2026 16:34:49 +0200 Subject: [PATCH] Refactor WooCommerce API to lazy initialization for build compatibility --- src/lib/woocommerce.ts | 35 ++++++++++++++++++++++++++++------- 1 file changed, 28 insertions(+), 7 deletions(-) diff --git a/src/lib/woocommerce.ts b/src/lib/woocommerce.ts index ded4213..4e0d8f1 100644 --- a/src/lib/woocommerce.ts +++ b/src/lib/woocommerce.ts @@ -1,11 +1,27 @@ import WooCommerceRestApi from "@woocommerce/woocommerce-rest-api"; -const api = new WooCommerceRestApi({ - url: process.env.NEXT_PUBLIC_WOOCOMMERCE_URL || "", - consumerKey: process.env.NEXT_PUBLIC_WOOCOMMERCE_CONSUMER_KEY || "", - consumerSecret: process.env.NEXT_PUBLIC_WOOCOMMERCE_CONSUMER_SECRET || "", - version: "wc/v3", -}); +// Lazy initialization - only create API client when needed +let apiInstance: WooCommerceRestApi | null = null; + +function getApi(): WooCommerceRestApi { + if (!apiInstance) { + const url = process.env.NEXT_PUBLIC_WOOCOMMERCE_URL; + const consumerKey = process.env.NEXT_PUBLIC_WOOCOMMERCE_CONSUMER_KEY; + const consumerSecret = process.env.NEXT_PUBLIC_WOOCOMMERCE_CONSUMER_SECRET; + + if (!url || !consumerKey || !consumerSecret) { + throw new Error("WooCommerce API credentials not configured"); + } + + apiInstance = new WooCommerceRestApi({ + url, + consumerKey, + consumerSecret, + version: "wc/v3", + }); + } + return apiInstance; +} export interface WooProduct { id: number; @@ -34,6 +50,7 @@ export interface WooCategory { export async function getProducts(perPage = 100): Promise { try { + const api = getApi(); const response = await api.get("products", { per_page: perPage }); return response.data; } catch (error) { @@ -44,6 +61,7 @@ export async function getProducts(perPage = 100): Promise { export async function getProduct(id: number): Promise { try { + const api = getApi(); const response = await api.get(`products/${id}`); return response.data; } catch (error) { @@ -54,6 +72,7 @@ export async function getProduct(id: number): Promise { export async function getProductBySlug(slug: string): Promise { try { + const api = getApi(); const response = await api.get("products", { slug }); return response.data[0] || null; } catch (error) { @@ -64,6 +83,7 @@ export async function getProductBySlug(slug: string): Promise export async function getCategories(): Promise { try { + const api = getApi(); const response = await api.get("product-categories", { per_page: 100 }); return response.data; } catch (error) { @@ -76,6 +96,7 @@ export async function getProductsByCategory( categoryId: number ): Promise { try { + const api = getApi(); const response = await api.get("products", { category: categoryId, per_page: 100, @@ -104,4 +125,4 @@ export function getProductImage(product: WooProduct): string { return "/placeholder-product.jpg"; } -export default api; +export default getApi;