Fase 2 ADR 0006 Etapa 2: plugin de Meilisearch + ruta de facetas
Instala @rokmohar/medusa-plugin-meilisearch@^1.4.1 (linea v1, la unica compatible con nuestro Medusa 2.18.0 exacto -- confirmado contra peerDependencies reales de npm: @medusajs/* ^2.15.2, satisfecho por 2.18.0). Conectado via un array `plugins:` nuevo en medusa-config.ts (primer uso en este repo, no `modules:`), env vars leidos con `?? ""` en vez de required() -- si Meilisearch esta caido o mal configurado, el plugin se degrada solo en vez de tumbar el arranque de Medusa entero. No se escribe un subscriber propio: se verifico contra el codigo fuente real del paquete (descargado el tarball exacto de npm, inspeccionado en /app/node_modules dentro de una imagen Docker de verdad) que trae sus propios subscribers de product/category/ collection/variant/etc, descubiertos por Medusa en runtime desde dentro del propio paquete -- confirmado que sobreviven a `npm prune --omit=dev` y llegan intactos a la imagen final. Tambien trae un job de indexado inicial de una sola corrida al boot (numberOfExecutions: 1, no un cron recurrente -- no viola la restriccion del ADR de "nunca cron"). Nueva ruta Store API propia (src/api/store/search/route.ts): las rutas /store/meilisearch/* que trae el plugin no devuelven facetDistribution (verificado leyendo su codigo fuente), asi que esta ruta pide facets explicitamente via additionalOptions.facets, y despues re-hidrata los productos via query.graph (mismos campos que ya usa el storefront) en vez de confiar en precios/inventario indexados -- mismo patron "safe path" que ya usa la ruta oficial del plugin para /store/meilisearch/products. Transformer custom en medusa-config.ts que espeja mapProduct() del storefront (category/collection/brand/ageRange desde metadata, disponibilidad desde la primera variante) para que el documento indexado sea exactamente lo que el storefront ya muestra. Validado en vivo: build completo de Docker (target builder) corre limpio -- npm ci, medusa build (typecheck + compile backend/frontend), npm prune -- cero errores. package-lock.json regenerado con un contenedor node:22.18.0-bookworm-slim real (mismo base image que el Dockerfile), no a mano. Dockerfile: dummy MEILISEARCH_HOST/MEILISEARCH_API_KEY en el stage de build (insurance barata, no son required() asi que no eran estrictamente necesarios para que el build pasara, y de hecho paso sin ellos en la prueba -- se dejan de todas formas por consistencia con el resto de dummies de esa capa).
This commit is contained in:
1 parent
688a7d8e97
commit
6be8dd409c
5 files changed
+336
-3
No files matched your search
@@ -0,0 +1,161 @@
|
||||
import type { MedusaRequest, MedusaResponse } from "@medusajs/framework";
|
||||
import { ContainerRegistrationKeys } from "@medusajs/framework/utils";
|
||||
import {
|
||||
MEILISEARCH_MODULE,
|
||||
type MeiliSearchService,
|
||||
} from "@rokmohar/medusa-plugin-meilisearch";
|
||||
|
||||
// Las rutas /store/meilisearch/* que trae el plugin (ver ADR 0006 nota de
|
||||
// implementacion) no devuelven facetDistribution -- necesitamos esta
|
||||
// ruta propia para pedirlo explicitamente via additionalOptions.facets,
|
||||
// que el servicio del plugin reenvia tal cual al cliente Meilisearch.
|
||||
const FACETS = ["category", "collection", "brand", "ageRange"];
|
||||
|
||||
// Mismos campos que ya usa el storefront contra /store/products
|
||||
// (workloads/ecommerce/lib/headless/providers/medusa.ts) -- una vez que
|
||||
// Meilisearch nos da los ids candidatos, volvemos a Medusa via
|
||||
// query.graph para precio/inventario reales, nunca confiamos en el
|
||||
// valor indexado (puede tener unos segundos de retraso respecto al
|
||||
// evento de sincronizacion).
|
||||
const PRODUCT_FIELDS = [
|
||||
"id",
|
||||
"handle",
|
||||
"title",
|
||||
"subtitle",
|
||||
"description",
|
||||
"thumbnail",
|
||||
"external_id",
|
||||
"metadata",
|
||||
"images.url",
|
||||
"tags.value",
|
||||
"categories.name",
|
||||
"collection.title",
|
||||
"variants.id",
|
||||
"variants.title",
|
||||
"variants.sku",
|
||||
"variants.manage_inventory",
|
||||
"variants.allow_backorder",
|
||||
"variants.inventory_quantity",
|
||||
"variants.calculated_price.calculated_amount",
|
||||
"variants.calculated_price.original_amount",
|
||||
"variants.calculated_price.currency_code",
|
||||
"variants.options.value",
|
||||
"variants.options.option.title",
|
||||
];
|
||||
|
||||
function stringParam(
|
||||
query: MedusaRequest["query"],
|
||||
name: string,
|
||||
): string | undefined {
|
||||
const value = query[name];
|
||||
return typeof value === "string" && value.length > 0 ? value : undefined;
|
||||
}
|
||||
|
||||
function numberParam(
|
||||
query: MedusaRequest["query"],
|
||||
name: string,
|
||||
): number | undefined {
|
||||
const value = stringParam(query, name);
|
||||
if (!value) return undefined;
|
||||
const parsed = Number(value);
|
||||
return Number.isFinite(parsed) ? parsed : undefined;
|
||||
}
|
||||
|
||||
// Meilisearch usa comillas dobles para valores de filtro con espacios;
|
||||
// escapamos las que vengan en el propio valor para no romper la sintaxis.
|
||||
function escapeFilterValue(value: string): string {
|
||||
return value.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
|
||||
}
|
||||
|
||||
export async function GET(req: MedusaRequest, res: MedusaResponse) {
|
||||
const meilisearchService = req.scope.resolve<MeiliSearchService>(
|
||||
MEILISEARCH_MODULE,
|
||||
);
|
||||
const query = req.scope.resolve(ContainerRegistrationKeys.QUERY);
|
||||
|
||||
const q = stringParam(req.query, "q") ?? "";
|
||||
const limit = numberParam(req.query, "limit") ?? 24;
|
||||
const offset = numberParam(req.query, "offset") ?? 0;
|
||||
|
||||
const filterParts: string[] = [];
|
||||
for (const facet of ["category", "collection", "brand", "ageRange"]) {
|
||||
const value = stringParam(req.query, facet);
|
||||
if (value) {
|
||||
filterParts.push(`${facet} = "${escapeFilterValue(value)}"`);
|
||||
}
|
||||
}
|
||||
const minPrice = numberParam(req.query, "minPrice");
|
||||
const maxPrice = numberParam(req.query, "maxPrice");
|
||||
if (typeof minPrice === "number") filterParts.push(`price >= ${minPrice}`);
|
||||
if (typeof maxPrice === "number") filterParts.push(`price <= ${maxPrice}`);
|
||||
|
||||
const indexes = await meilisearchService.getIndexesByType("products");
|
||||
|
||||
if (indexes.length === 0) {
|
||||
// Meilisearch no configurado o el indice "products" esta
|
||||
// deshabilitado -- degradar a "sin resultados" en vez de 500, el
|
||||
// frontend cae de nuevo a su propio filtrado si esta ruta falla.
|
||||
res.json({ products: [], facetDistribution: {}, count: 0, limit, offset });
|
||||
return;
|
||||
}
|
||||
|
||||
const results = await Promise.all(
|
||||
indexes.map((indexKey) =>
|
||||
meilisearchService.search(indexKey, q, {
|
||||
filter: filterParts.length ? filterParts.join(" AND ") : undefined,
|
||||
paginationOptions: { limit, offset },
|
||||
additionalOptions: { facets: FACETS },
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const hits = results.flatMap((result) => result.hits);
|
||||
const totalCount = results.reduce(
|
||||
(sum, result) => sum + result.estimatedTotalHits,
|
||||
0,
|
||||
);
|
||||
|
||||
const facetDistribution: Record<string, Record<string, number>> = {};
|
||||
for (const result of results) {
|
||||
const resultFacets = (
|
||||
result as unknown as {
|
||||
facetDistribution?: Record<string, Record<string, number>>;
|
||||
}
|
||||
).facetDistribution;
|
||||
if (!resultFacets) continue;
|
||||
for (const [facet, values] of Object.entries(resultFacets)) {
|
||||
facetDistribution[facet] ??= {};
|
||||
for (const [value, count] of Object.entries(values)) {
|
||||
facetDistribution[facet][value] =
|
||||
(facetDistribution[facet][value] ?? 0) + count;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const productIds = hits.map((hit) => (hit as { id: string }).id);
|
||||
|
||||
if (productIds.length === 0) {
|
||||
res.json({ products: [], facetDistribution, count: 0, limit, offset });
|
||||
return;
|
||||
}
|
||||
|
||||
const { data: products = [] } = await query.graph({
|
||||
entity: "product",
|
||||
fields: PRODUCT_FIELDS,
|
||||
filters: { id: productIds },
|
||||
});
|
||||
|
||||
// Preserva el ranking de relevancia de Meilisearch -- query.graph no
|
||||
// garantiza el mismo orden que la busqueda.
|
||||
const orderedProducts = [...products].sort(
|
||||
(a, b) => productIds.indexOf(a.id) - productIds.indexOf(b.id),
|
||||
);
|
||||
|
||||
res.json({
|
||||
products: orderedProducts,
|
||||
facetDistribution,
|
||||
count: totalCount,
|
||||
limit,
|
||||
offset,
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user