Files
apps-registry/workloads/ecommerce/lib/headless/providers/medusa.ts
T
devopsandClaude Sonnet 5 d9c39ba2a1 fix(ecommerce): sacar cache de fetch que competia contra force-dynamic
medusaFetch() usaba next:{revalidate:60,tags:["medusa-products"]}, cache
en memoria por-pod que sobrevivia a force-dynamic en las paginas que lo
consumen. Con frontend-deploy en 2 replicas sin cacheHandler compartido,
el POST de /api/revalidate del subscriber de Medusa solo llegaba a uno
de los dos pods, dejando al otro sirviendo datos viejos hasta que el TTL
expirara solo -- reportado por el usuario: ediciones manuales de imagen
no se reflejaban en el storefront, pero la importacion por CSV (mucho
mas lenta) si, porque el TTL tenia tiempo de sobra para expirar en
ambos pods.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01QMP7ULbxbsB5g1vELNAT3D
2026-09-20 16:50:16 +00:00

491 lines
13 KiB
TypeScript

import type {
CatalogProvider,
Category,
FacetDistribution,
FacetedSearchResult,
Product,
ProductFilters,
ProductVariant,
} from "@/lib/headless/types";
type MedusaImage = {
url?: string | null;
};
type MedusaTag = {
value?: string | null;
};
type MedusaCategory = {
name?: string | null;
};
type MedusaCollection = {
title?: string | null;
};
type MedusaCalculatedPrice = {
calculated_amount?: number | null;
original_amount?: number | null;
currency_code?: string | null;
};
type MedusaVariant = {
id: string;
title?: string | null;
sku?: string | null;
manage_inventory?: boolean | null;
allow_backorder?: boolean | null;
inventory_quantity?: number | null;
calculated_price?: MedusaCalculatedPrice | null;
options?: Array<{
value?: string | null;
option?: {
title?: string | null;
} | null;
}> | null;
};
type MedusaProduct = {
id: string;
handle?: string | null;
title?: string | null;
subtitle?: string | null;
description?: string | null;
thumbnail?: string | null;
external_id?: string | null;
metadata?: Record<string, unknown> | null;
images?: MedusaImage[] | null;
tags?: MedusaTag[] | null;
categories?: MedusaCategory[] | null;
collection?: MedusaCollection | null;
variants?: MedusaVariant[] | null;
};
type MedusaProductsResponse = {
products: MedusaProduct[];
count?: number;
limit?: number;
offset?: number;
};
type MedusaProductCategory = {
id: string;
name?: string | null;
handle?: string | null;
parent_category_id?: string | null;
rank?: number | null;
};
type MedusaCategoriesResponse = {
product_categories: MedusaProductCategory[];
};
function backendUrl(): string {
const value = process.env.MEDUSA_BACKEND_URL;
if (!value) {
throw new Error("MEDUSA_BACKEND_URL no está configurado.");
}
return value.replace(/\/$/, "");
}
function regionId(): string {
const value = process.env.MEDUSA_REGION_ID;
if (!value) {
throw new Error("MEDUSA_REGION_ID no está configurado.");
}
return value;
}
async function medusaFetch<T>(
path: string,
searchParams?: URLSearchParams,
): Promise<T> {
const url = new URL(`${backendUrl()}${path}`);
if (searchParams) {
searchParams.forEach((value, key) => {
url.searchParams.append(key, value);
});
}
const publishableKey = process.env.MEDUSA_PUBLISHABLE_KEY;
// Sin next.revalidate/tags a proposito (reportado por el usuario
// 2026-09-20: imagenes editadas a mano en Medusa no se reflejaban en
// el storefront, pero por CSV si). Causa real: frontend-deploy corre 2
// replicas sin cacheHandler compartido -- cada pod tenia su propio
// cache en memoria de este fetch (next.revalidate:60), y el POST de
// /api/revalidate (revalidateTag) del subscriber de Medusa solo le
// llegaba a UNO de los dos pods via el Service, dejando al otro
// sirviendo la respuesta vieja hasta que el TTL expirara solo. Una
// edicion puntual + revisar al toque tenia ~50% de chance de pegarle
// al pod stale; una importacion CSV (minutos de duracion) le daba
// tiempo de sobra al TTL para expirar en ambos pods, disimulando el
// mismo bug. Las paginas que consumen esto ya son force-dynamic /
// dinamicas por diseño (ver comentario en app/page.tsx y
// app/product/[slug]/page.tsx) -- este next.revalidate competia contra
// esa intencion en vez de cumplirla. Sin este bloque, Next 15 no
// cachea el fetch por default dentro de una ruta dinamica.
const response = await fetch(url, {
headers: publishableKey
? { "x-publishable-api-key": publishableKey }
: undefined,
});
if (!response.ok) {
const body = await response.text().catch(() => "");
throw new Error(
`Medusa respondió HTTP ${response.status}: ${body.slice(0, 300)}`,
);
}
return (await response.json()) as T;
}
function stringMetadata(
metadata: Record<string, unknown> | null | undefined,
key: string,
): string {
const value = metadata?.[key];
return typeof value === "string" ? value : "";
}
function booleanMetadata(
metadata: Record<string, unknown> | null | undefined,
key: string,
): boolean {
const value = metadata?.[key];
return value === true || value === "true";
}
function normalizeCurrency(value?: string | null): string {
return (value || "COP").toUpperCase();
}
function mapVariant(variant: MedusaVariant): ProductVariant {
const option = variant.options?.[0];
const available =
variant.allow_backorder === true ||
variant.manage_inventory === false ||
(variant.inventory_quantity ?? 0) > 0;
// null = inventario no gestionado (backorder o manage_inventory=false),
// no hay un numero real que mostrar como "quedan N".
const inventoryQuantity =
variant.allow_backorder === true || variant.manage_inventory === false
? null
: (variant.inventory_quantity ?? 0);
return {
id: variant.id,
name: option?.option?.title || "Presentación",
value: option?.value || variant.title || "Estándar",
available,
inventoryQuantity,
};
}
function mapProduct(product: MedusaProduct): Product {
const slug = product.handle || product.id;
const variant = product.variants?.[0];
const calculated = variant?.calculated_price;
const category =
product.categories?.[0]?.name ||
stringMetadata(product.metadata, "category") ||
"Variedades";
const collection =
product.collection?.title ||
stringMetadata(product.metadata, "collection") ||
"";
const brand = stringMetadata(product.metadata, "brand") || "ARI Shopping";
const ageRange = stringMetadata(product.metadata, "ageRange") || "Todas";
const images = [
...(product.images || [])
.map((image) => image.url || "")
.filter(Boolean),
];
const thumbnail =
product.thumbnail || images[0] || "/images/brand/logo-ari.png";
const price =
typeof calculated?.calculated_amount === "number"
? calculated.calculated_amount
: null;
const original =
typeof calculated?.original_amount === "number"
? calculated.original_amount
: null;
const compareAtPrice =
original !== null && price !== null && original > price
? original
: null;
const available =
!variant ||
variant.allow_backorder === true ||
variant.manage_inventory === false ||
(variant.inventory_quantity ?? 0) > 0;
const tags = (product.tags || [])
.map((tag) => tag.value || "")
.filter(Boolean);
return {
id: product.external_id || product.id,
slug,
name: product.title || "Producto ARI Shopping",
shortDescription:
product.subtitle ||
product.title ||
"Producto ARI Shopping",
description:
product.description ||
"Producto disponible para confirmación de inventario con ARI Shopping.",
category,
collection,
brand,
ageRange,
price,
compareAtPrice,
currency: normalizeCurrency(calculated?.currency_code),
priceLabel: price === null ? "Consultar disponibilidad" : "",
available,
featured: booleanMetadata(product.metadata, "featured"),
isNew: booleanMetadata(product.metadata, "isNew"),
image: images[0] || thumbnail,
thumbnail,
images: images.length > 0 ? images : [thumbnail],
tags,
variants: (product.variants || []).map(mapVariant),
};
}
function matchesFilters(
product: Product,
filters?: ProductFilters,
): boolean {
if (!filters) return true;
const query = filters.query?.trim().toLocaleLowerCase("es");
if (
query &&
![
product.name,
product.shortDescription,
product.description,
product.category,
product.collection,
product.brand,
...product.tags,
]
.join(" ")
.toLocaleLowerCase("es")
.includes(query)
) {
return false;
}
if (
filters.category &&
filters.category !== "Todos" &&
product.category !== filters.category
) {
return false;
}
if (
filters.collection &&
product.collection !== filters.collection
) {
return false;
}
if (
filters.brand &&
filters.brand !== "Todas" &&
product.brand !== filters.brand
) {
return false;
}
if (
filters.ageRange &&
filters.ageRange !== "Todas" &&
product.ageRange !== filters.ageRange
) {
return false;
}
if (
typeof filters.minPrice === "number" &&
product.price !== null &&
product.price < filters.minPrice
) {
return false;
}
if (
typeof filters.maxPrice === "number" &&
product.price !== null &&
product.price > filters.maxPrice
) {
return false;
}
return true;
}
async function fetchProducts(
filters?: ProductFilters,
limit = 100,
): Promise<Product[]> {
const params = new URLSearchParams({
limit: String(limit),
// El validador de /store/products no acepta currency_code (400
// "Unrecognized fields"); el precio calculado solo se resuelve con
// region_id.
region_id: regionId(),
fields:
"+metadata,+images,+tags,+categories.*,+collection,+variants.inventory_quantity,+variants.calculated_price,+variants.options",
});
if (filters?.query) {
params.set("q", filters.query);
}
const response = await medusaFetch<MedusaProductsResponse>(
"/store/products",
params,
);
return response.products
.map(mapProduct)
.filter((product) => matchesFilters(product, filters));
}
async function fetchCategories(): Promise<Category[]> {
const params = new URLSearchParams({
limit: "100",
fields: "id,name,handle,rank,parent_category_id",
});
const response = await medusaFetch<MedusaCategoriesResponse>(
"/store/product-categories",
params,
);
// Ordenar por rank preserva el orden de la taxonomia tal como se creo
// (ver ADR 0005) -- los hijos de cada padre quedan en el mismo orden
// relativo porque el arbol se arma filtrando este arreglo ya ordenado.
return response.product_categories
.slice()
.sort((a, b) => (a.rank ?? 0) - (b.rank ?? 0))
.map((category) => ({
id: category.id,
name: category.name || "",
handle: category.handle || category.id,
parentId: category.parent_category_id ?? null,
}));
}
type MedusaSearchResponse = {
products: MedusaProduct[];
facetDistribution?: FacetDistribution;
count?: number;
};
// Pega contra /store/search (ADR 0006 Etapa 2) en vez de /store/products
// -- Meilisearch resuelve texto tolerante a errores de tipeo y facetas
// reales, la ruta del backend re-hidrata precio/inventario vía
// query.graph antes de responder, así que el shape de MedusaProduct es
// exactamente el mismo que ya mapea mapProduct().
async function fetchWithFacets(
filters?: ProductFilters,
limit = 24,
): Promise<FacetedSearchResult> {
const params = new URLSearchParams({
limit: String(limit),
region_id: regionId(),
});
if (filters?.query) params.set("q", filters.query);
if (filters?.category && filters.category !== "Todos") {
params.set("category", filters.category);
}
if (filters?.collection) params.set("collection", filters.collection);
if (filters?.brand && filters.brand !== "Todas") {
params.set("brand", filters.brand);
}
if (filters?.ageRange && filters.ageRange !== "Todas") {
params.set("ageRange", filters.ageRange);
}
if (typeof filters?.minPrice === "number") {
params.set("minPrice", String(filters.minPrice));
}
if (typeof filters?.maxPrice === "number") {
params.set("maxPrice", String(filters.maxPrice));
}
const response = await medusaFetch<MedusaSearchResponse>(
"/store/search",
params,
);
return {
products: response.products.map(mapProduct),
facetDistribution: response.facetDistribution ?? {},
count: response.count ?? response.products.length,
};
}
export const medusaCatalogProvider: CatalogProvider = {
async getProducts(filters) {
return fetchProducts(filters);
},
async getCategories() {
return fetchCategories();
},
async getProductBySlug(slug) {
const params = new URLSearchParams({
handle: slug,
limit: "1",
// El validador de /store/products no acepta currency_code (400
// "Unrecognized fields"); el precio calculado solo se resuelve con
// region_id.
region_id: regionId(),
fields:
"+metadata,+images,+tags,+categories.*,+collection,+variants.inventory_quantity,+variants.calculated_price,+variants.options",
});
const response = await medusaFetch<MedusaProductsResponse>(
"/store/products",
params,
);
const product = response.products[0];
return product ? mapProduct(product) : null;
},
async searchProducts(query, limit = 8) {
const { products } = await fetchWithFacets({ query }, limit);
return products;
},
async searchWithFacets(filters) {
return fetchWithFacets(filters, filters?.limit ?? 24);
},
};