feat(storefront): increase blog list limit to 200, resolve wiki taurine alias and expand related products search
Deploy Canina / deploy (push) Successful in 2m42s
Deploy Canina / deploy (push) Successful in 2m42s
This commit is contained in:
1 parent
0ad39bb92c
commit
d3a0a61d79
3 files changed
+87
-10
No files matched your search
@@ -34,7 +34,7 @@ async function getBlogs() {
|
||||
const apiUrl = process.env.INTERNAL_API_URL || process.env.NEXT_PUBLIC_API_URL || 'http://localhost:4001/api';
|
||||
const apiBase = apiUrl.endsWith('/api') ? apiUrl : `${apiUrl.replace(/\/$/, '')}/api`;
|
||||
try {
|
||||
const res = await fetch(`${apiBase}/blogs?limit=50`, {
|
||||
const res = await fetch(`${apiBase}/blogs?limit=200`, {
|
||||
next: { tags: ['blogs'], revalidate: 3600 },
|
||||
});
|
||||
if (!res.ok) {
|
||||
|
||||
@@ -13,10 +13,17 @@ function getApiBase(): string {
|
||||
return apiUrl.endsWith('/api') ? apiUrl : `${apiUrl.replace(/\/$/, '')}/api`;
|
||||
}
|
||||
|
||||
const WIKI_SLUG_ALIASES: Record<string, string> = {
|
||||
'taurine': 'taurin',
|
||||
'تائورین': 'تورین',
|
||||
};
|
||||
|
||||
async function getWikiTerm(rawKey: string) {
|
||||
const normalizedKey = normalizeRouteSlug(rawKey);
|
||||
if (!normalizedKey) return null;
|
||||
const encodedKey = safeEncodeSlug(normalizedKey);
|
||||
|
||||
const lookupKey = WIKI_SLUG_ALIASES[normalizedKey.toLowerCase()] || WIKI_SLUG_ALIASES[normalizedKey] || normalizedKey;
|
||||
const encodedKey = safeEncodeSlug(lookupKey);
|
||||
const apiBase = getApiBase();
|
||||
|
||||
try {
|
||||
@@ -41,6 +48,7 @@ async function getWikiTerm(rawKey: string) {
|
||||
return {
|
||||
key: ing.slug,
|
||||
term: ing.nameFa || ing.nameEn || ing.slug,
|
||||
rawIngredient: ing,
|
||||
definition: ing.description || `بررسی تخصصی ترکیب دارویی و خواص ${ing.nameFa || ing.nameEn} در کاتالوگ مکملهای کنینا آلمان.`,
|
||||
metaTitle: `خواص دارویی ${ing.nameFa || ing.nameEn} | دانشنامه کنینا ایران`,
|
||||
metaDescription: (ing.description || '').slice(0, 155),
|
||||
@@ -54,15 +62,53 @@ async function getWikiTerm(rawKey: string) {
|
||||
return null;
|
||||
}
|
||||
|
||||
async function getRelatedProducts(termName: string) {
|
||||
async function getRelatedProducts(term: any) {
|
||||
try {
|
||||
const apiBase = getApiBase();
|
||||
const res = await fetch(`${apiBase}/products?search=${encodeURIComponent(termName)}&limit=4`, {
|
||||
next: { revalidate: 3600, tags: ['products'] },
|
||||
});
|
||||
if (!res.ok) return [];
|
||||
const json = await res.json();
|
||||
return json.data || json || [];
|
||||
const searchCandidates: string[] = [];
|
||||
if (typeof term === 'string') {
|
||||
searchCandidates.push(term);
|
||||
} else if (term) {
|
||||
if (term.key) searchCandidates.push(term.key);
|
||||
if (term.wikiId) searchCandidates.push(term.wikiId);
|
||||
if (term.rawIngredient) {
|
||||
if (term.rawIngredient.scientificName) searchCandidates.push(term.rawIngredient.scientificName);
|
||||
if (term.rawIngredient.nameEn) searchCandidates.push(term.rawIngredient.nameEn);
|
||||
if (term.rawIngredient.slug) searchCandidates.push(term.rawIngredient.slug);
|
||||
if (term.rawIngredient.nameFa) {
|
||||
const cleanFa = term.rawIngredient.nameFa.replace(/\s*\([^)]*\)\s*/g, ' ').trim();
|
||||
searchCandidates.push(cleanFa);
|
||||
if (cleanFa.startsWith('ال-') || cleanFa.startsWith('ال ')) {
|
||||
searchCandidates.push(cleanFa.replace(/^ال[- ]/, ''));
|
||||
}
|
||||
}
|
||||
}
|
||||
if (term.term) {
|
||||
const cleanTerm = String(term.term).replace(/\s*\([^)]*\)\s*/g, ' ').trim();
|
||||
searchCandidates.push(cleanTerm);
|
||||
}
|
||||
}
|
||||
|
||||
const uniqueCandidates = Array.from(new Set(searchCandidates.filter(Boolean)));
|
||||
const productMap = new Map<string, any>();
|
||||
|
||||
for (const candidate of uniqueCandidates) {
|
||||
const res = await fetch(`${apiBase}/products?search=${encodeURIComponent(candidate)}&limit=4`, {
|
||||
next: { revalidate: 3600, tags: ['products'] },
|
||||
});
|
||||
if (res.ok) {
|
||||
const json = await res.json();
|
||||
const list = Array.isArray(json.data) ? json.data : Array.isArray(json) ? json : [];
|
||||
for (const p of list) {
|
||||
if (p?.id && !productMap.has(p.id)) {
|
||||
productMap.set(p.id, p);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (productMap.size >= 4) break;
|
||||
}
|
||||
|
||||
return Array.from(productMap.values()).slice(0, 4);
|
||||
} catch (error) {
|
||||
console.error('[Wiki] Error fetching related products for ingredient:', error);
|
||||
return [];
|
||||
@@ -119,7 +165,7 @@ export default async function WikiTermPage({ params }: { params: Promise<{ slug:
|
||||
notFound();
|
||||
}
|
||||
|
||||
const relatedProducts = await getRelatedProducts(term.term);
|
||||
const relatedProducts = await getRelatedProducts(term);
|
||||
const encodedSlug = safeEncodeSlug(normalizedKey);
|
||||
|
||||
const medicalSchema = generateMedicalWebPageSchema({
|
||||
|
||||
@@ -111,6 +111,37 @@ describe('WikiTermPage slug decoding and single-encoding', () => {
|
||||
expect(fetchMock.mock.calls[0][0]).toBe('http://backend:3000/api/wiki/EPA%2FDHA');
|
||||
});
|
||||
|
||||
it('resolves alias taurine to taurin and searches related products', async () => {
|
||||
const fetchMock = vi.fn()
|
||||
// First call: /wiki/taurin (fails)
|
||||
.mockResolvedValueOnce({ ok: false, status: 404 })
|
||||
// Second call: /ingredients/taurin (succeeds)
|
||||
.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
slug: 'taurin',
|
||||
nameFa: 'تورین (Taurine)',
|
||||
scientificName: 'Taurine',
|
||||
description: 'اسید آمینه ضروری',
|
||||
}),
|
||||
})
|
||||
// Third call: /products?search=taurin
|
||||
.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({ data: [{ id: 'p1', name: 'مکمل تورین گربه', slug: 'canina-taurin' }] }),
|
||||
});
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
const jsx = await WikiTermPage({
|
||||
params: Promise.resolve({ slug: 'taurine' }),
|
||||
});
|
||||
expect(jsx).toBeDefined();
|
||||
// First attempted /wiki/taurin because of alias
|
||||
expect(fetchMock.mock.calls[0][0]).toBe('http://backend:3000/api/wiki/taurin');
|
||||
// Second attempted /ingredients/taurin
|
||||
expect(fetchMock.mock.calls[1][0]).toBe('http://backend:3000/api/ingredients/taurin');
|
||||
});
|
||||
|
||||
it('returns notFound() when neither scientific term nor ingredient exists', async () => {
|
||||
const fetchMock = vi.fn()
|
||||
// 1. wiki term 404
|
||||
|
||||
Reference in new issue
Block a user