feat: 将搜索页面由Strapi迁移至Direcuts

- 路由页面相关源码修改
- 类型标注与组合式API
- 相关工具函数
This commit is contained in:
2025-10-24 16:18:26 +08:00
parent 05938550e6
commit f62c4a3987
11 changed files with 309 additions and 151 deletions

View File

@ -2,14 +2,14 @@
<div v-if="hasResults">
<div class="search-results">
<NuxtLink
v-for="(hit, hitIndex) in paginatedHits"
:key="`${getHitIdentifier(hit.content, hitIndex)}`"
:to="localePath(resolveHitLink(hit.content))"
v-for="hit in paginatedHits"
:key="`${hit.type}-${hit.id}`"
:to="localePath(resolveHitLink(hit))"
>
<el-card class="result-card">
<h3 class="result-title">{{ getHitTitle(hit.content) }}</h3>
<p v-if="getHitSummary(hit.content)" class="result-summary">
{{ getHitSummary(hit.content) }}
<h3 class="result-title">{{ hit.title }}</h3>
<p v-if="hit.summary" class="result-summary">
{{ hit.summary }}
</p>
<p v-if="hit.type" class="result-type">
<span>内容类型: </span>
@ -44,13 +44,8 @@
</template>
<script setup lang="ts">
interface HitItem {
content: SearchHit;
type: string;
}
const props = defineProps<{
hitItems: HitItem[];
searchItems: SearchItemView[];
currentPage: number;
category?: string;
}>();
@ -74,12 +69,12 @@
const pageSize = ref(5);
// 搜索相关
const hits = props.hitItems;
const items = props.searchItems;
const filteredHits = computed(() => {
if (props.category) {
return hits.filter((hit) => hit.type === props.category);
return items.filter((item) => item.type === props.category);
} else {
return hits;
return items;
}
});
const paginatedHits = computed(() => {
@ -106,64 +101,13 @@
return filteredHits.value.length > 0;
});
/**
* 获取搜索条目的唯一标识符
* 尝试根据搜索条目的相关词条获取唯一标识符
* 若未找到则fallback至给定的index
* @param hit 搜索条目
* @param index 条目索引
*/
const getHitIdentifier = (hit: SearchHit, index: number) => {
const candidate = [hit.objectID, hit.documentId, hit.id, hit.slug].find(
(value) =>
['string', 'number'].includes(typeof value) && String(value).length > 0
);
return candidate != null ? String(candidate) : String(index);
};
/**
* 获取搜索条目的标题
* @param hit 搜索条目
*/
const getHitTitle = (hit: SearchHit) => {
const candidate = [
hit.title,
hit.name,
hit.heading,
hit.documentTitle,
].find((value) => typeof value === 'string' && value.trim().length > 0);
return candidate ? String(candidate) : t('search.untitled');
};
/**
* 获取搜索条目的摘要
* @param hit 搜索条目
*/
const getHitSummary = (hit: SearchHit) => {
const candidate = [
hit.summary,
hit.description,
hit.snippet,
hit.content,
hit.text,
].find((value) => typeof value === 'string' && value.trim().length > 0);
return candidate ? String(candidate) : '';
};
/**
* 解析条目链接
* 根据条目类型返回正确的跳转链接
* @param hit 搜索条目
* @param item 搜索条目
*/
const resolveHitLink = (hit: SearchHit) => {
if (typeof hit.route === 'string' && hit.route.trim().length > 0) {
return localePath(hit.route);
}
const slugCandidate = [hit.slug, hit.documentId, hit.id, hit.objectID].find(
(value) =>
['string', 'number'].includes(typeof value) && String(value).length > 0
);
const resolveHitLink = (item: SearchItemView) => {
const slugCandidate = item.id;
if (!slugCandidate) {
return null;
@ -171,11 +115,11 @@
const slug = String(slugCandidate);
if (hit.indexUid === 'production') {
if (item.type === 'product') {
return localePath({ path: `/productions/${slug}` });
}
if (hit.indexUid === 'solution') {
if (item.type === 'solution') {
return localePath({ path: `/solutions/${slug}` });
}

View File

@ -87,5 +87,10 @@ export const useLocalizations = () => {
* @returns 语言映射对象
*/
getLocaleMapping: getMapping,
/** 所有可用的Directus语言代码列表(只读) **/
availableDirectusLocales: readonly(
Object.values(localeMap).map((item) => item.directus)
),
};
};

View File

@ -1,33 +1,25 @@
import { MeiliSearch } from 'meilisearch';
import type { SearchParams, SearchResponse } from 'meilisearch';
import type { SearchParams } from 'meilisearch';
interface RawSearchSection {
indexUid: string;
response: SearchResponse<Record<string, unknown>>;
}
export interface SearchHit extends Record<string, unknown> {
indexUid: string;
objectID?: string | number;
}
export interface SearchSection {
indexUid: string;
hits: SearchHit[];
estimatedTotalHits: number;
processingTimeMs: number;
}
const parseIndexes = (indexes: string | string[] | undefined): string[] => {
const parseIndexes = (
indexes: string | string[] | undefined,
locale?: string
): string[] => {
if (!indexes) {
return [];
}
let suffix = '';
if (locale) {
suffix = `_${locale}`;
}
if (Array.isArray(indexes)) {
return indexes.map((item) => item.trim()).filter(Boolean);
return indexes.map((item) => `${item.trim()}${suffix}`).filter(Boolean);
}
return indexes
.split(',')
.map((item) => item.trim())
.map((item) => `${item.trim()}${suffix}`)
.filter(Boolean);
};
@ -56,10 +48,22 @@ export const useMeilisearch = () => {
return meiliClient;
};
const search = async (
/**
* 泛型搜索函数
* @template T 文档类型, 如 MeiliProductIndex
* ---
* @param query 搜索关键词
* @param params 其他搜索参数
* @returns 搜索结果数组
*/
async function search<
K extends MeiliSearchItemType = MeiliSearchItemType,
T extends MeiliIndexMap[K] = MeiliIndexMap[K],
>(
query: string,
params: SearchParams = {}
): Promise<SearchSection[]> => {
params: SearchParams = {},
searchLocale?: string
): Promise<SearchSection<T>[]> {
const trimmedQuery = query.trim();
if (!trimmedQuery) {
return [];
@ -70,34 +74,35 @@ export const useMeilisearch = () => {
return [];
}
const activeIndexes = indexes.value;
const activeIndexes = indexes.value as K[];
if (!activeIndexes.length) {
console.warn('No Meilisearch indexes configured.');
return [];
}
const rawIndexMap = Object.fromEntries(
activeIndexes.map((index) => [`${index}_${searchLocale}`, index])
);
const indexesWithLocale = activeIndexes.map(
(index) => index + (searchLocale ? `_${searchLocale}` : '')
);
const requests = activeIndexes.map(async (indexUid) => {
const response = await client.index(indexUid).search(trimmedQuery, {
console.log(indexesWithLocale);
const requests = indexesWithLocale.map(async (indexUid) => {
const response = await client.index(indexUid).search<T>(trimmedQuery, {
limit: params.limit ?? 10,
...params,
});
const safeResponse = JSON.parse(JSON.stringify(response));
return {
indexUid,
response: {
hits: safeResponse.hits,
estimatedTotalHits:
safeResponse.estimatedTotalHits ?? safeResponse.hits.length,
processingTimeMs: safeResponse.processingTimeMs ?? 0,
query: safeResponse.query,
},
} satisfies RawSearchSection;
response,
} satisfies RawSearchSection<T>;
});
console.log((await requests[0])?.response.hits[0]?.locale);
const settled = await Promise.allSettled(requests);
console.log('Meilisearch settled results:', settled);
settled
.filter(
(result): result is PromiseRejectedResult =>
@ -108,22 +113,22 @@ export const useMeilisearch = () => {
});
return settled
.filter((result) => result.status === 'fulfilled')
.filter(
(result): result is PromiseFulfilledResult<RawSearchSection<T>> =>
result.status === 'fulfilled'
)
.map((result) => {
const fulfilled = result as PromiseFulfilledResult<RawSearchSection>;
const { indexUid, response } = result.value;
return {
indexUid: fulfilled.value.indexUid,
hits: fulfilled.value.response.hits.map((hit) => ({
...hit,
indexUid: fulfilled.value.indexUid,
})),
indexUid: indexUid,
rawIndex: rawIndexMap[indexUid],
hits: response.hits,
estimatedTotalHits:
fulfilled.value.response.estimatedTotalHits ??
fulfilled.value.response.hits.length,
processingTimeMs: fulfilled.value.response.processingTimeMs ?? 0,
response.estimatedTotalHits ?? response.hits.length,
processingTimeMs: response.processingTimeMs ?? 0,
};
});
};
}
return {
search,

View File

@ -0,0 +1,16 @@
/**
* 搜索索引转换器
* @param hit 搜索条目
* @returns 转换后的搜索条目视图模型
*
* ---
* @example
* const view = toSearchItemView(item, 'products');
*/
export function toSearchItemView<T extends MeiliSearchItemType>(
item: MeiliIndexMap[T],
type: T
): SearchItemView {
const converter = converters[type];
return converter ? converter(item) : null;
}

View File

@ -0,0 +1,35 @@
/**
* 各索引对应的转换函数表
*/
export const converters: {
[K in keyof MeiliIndexMap]: (item: MeiliIndexMap[K]) => SearchItemView;
} = {
products: (item: MeiliIndexMap['products']): SearchItemView => ({
id: item.id,
type: 'product',
title: item.name,
summary: item.summary,
}),
solutions: (item: MeiliIndexMap['solutions']): SearchItemView => ({
id: item.id,
type: 'solution',
title: item.title,
summary: item.summary,
}),
questions: (item: MeiliIndexMap['questions']): SearchItemView => ({
id: item.id,
type: 'question',
title: item.title,
summary: item.content.slice(0, 100) + '...',
}),
product_documents: (
item: MeiliIndexMap['product_documents']
): SearchItemView => ({
id: item.id,
type: 'document',
title: item.title,
}),
};

View File

@ -0,0 +1,13 @@
export interface SearchItemView {
/** 唯一标识符 **/
id: number;
/** 条目类型 **/
type: 'product' | 'solution' | 'question' | 'document';
/** 条目标题 **/
title: string;
/** 条目摘要 **/
summary?: string;
}

View File

@ -30,16 +30,16 @@
<el-tab-pane :label="`全部(${resultCount['all']})`" name="all">
<search-results
v-model:current-page="currentPage"
:hit-items="hits"
:search-items="searchItems"
/>
</el-tab-pane>
<el-tab-pane
:label="`产品(${resultCount['production'] || 0})`"
:label="`产品(${resultCount['product'] || 0})`"
name="production"
>
<search-results
v-model:current-page="currentPage"
:hit-items="hits"
:search-items="searchItems"
category="production"
/>
</el-tab-pane>
@ -49,7 +49,7 @@
>
<search-results
v-model:current-page="currentPage"
:hit-items="hits"
:search-items="searchItems"
category="solution"
/>
</el-tab-pane>
@ -59,7 +59,7 @@
>
<search-results
v-model:current-page="currentPage"
:hit-items="hits"
:search-items="searchItems"
category="question"
/>
</el-tab-pane>
@ -69,7 +69,7 @@
>
<search-results
v-model:current-page="currentPage"
:hit-items="hits"
:search-items="searchItems"
category="document"
/>
</el-tab-pane>
@ -92,8 +92,8 @@
// i18n相关
const { t } = useI18n();
const { getStrapiLocale } = useLocalizations();
const strapiLocale = getStrapiLocale();
const { getDirectusLocale } = useLocalizations();
const directusLocale = getDirectusLocale();
// 路由相关
const route = useRoute();
@ -110,40 +110,48 @@
pending: loading,
error,
} = await useAsyncData(
() => `search-${route.query.query ?? ''}`,
() => `search-${directusLocale}-${route.query.query ?? ''}`,
async () => {
const q = String(route.query.query ?? '').trim();
if (!q) return [];
return await search(q, { limit: 12 });
return await search(q, { limit: 12 }, directusLocale);
}
);
// 本地化+空Section过滤
// 空Section过滤
const filteredSections = computed(() =>
sections.value
.map((section) => ({
...section,
hits: section.hits.filter(
(hit) =>
!hit.locale ||
String(hit.locale).toLowerCase() === strapiLocale.toLowerCase()
),
}))
.filter((section) => section.hits.length > 0)
sections.value.filter((section) => section.hits.length > 0)
);
const typeMap = {
products: 'products',
solutions: 'solutions',
questions: 'questions',
product_documents: 'product_documents',
} as const;
// 展平hits
const hits = computed(() =>
filteredSections.value.flatMap((item) =>
item.hits.map((content) => ({ content, type: item.indexUid }))
)
filteredSections.value.flatMap((section) => {
const type = typeMap[section.rawIndex as keyof typeof typeMap];
if (!type) return [];
return section.hits.map((hit) => ({ type, content: hit }));
})
);
const searchItems = computed(() =>
hits.value.map((hit) => {
return toSearchItemView(hit.content, hit.type);
})
);
console.log(searchItems.value);
// 分类控制
const activeTab = ref('all');
const resultCount = computed(() => {
const map: Record<string, number> = { all: hits.value.length };
for (const hit of hits.value) {
map[hit.type] = (map[hit.type] ?? 0) + 1;
const map: Record<string, number> = { all: searchItems.value.length };
for (const item of searchItems.value) {
map[item.type] = (map[item.type] ?? 0) + 1;
}
return map;
});
@ -177,7 +185,7 @@
}
try {
const results = await search(trimmed, { limit: 12 });
const results = await search(trimmed, { limit: 12 }, directusLocale);
if (requestId === activeRequestId.value) {
sections.value = results;
}
@ -199,10 +207,10 @@
watch(
() => route.query.query,
(newQuery) => {
async (newQuery) => {
if (typeof newQuery === 'string' && newQuery.trim()) {
keyword.value = newQuery;
performSearch(newQuery);
await performSearch(newQuery);
} else {
loading.value = false;
}

View File

@ -0,0 +1,2 @@
export * from './meili-index';
export * from './search-result';

View File

@ -0,0 +1,88 @@
/**
* 产品索引文档结构
*/
export interface MeiliProductIndex {
/** 唯一标识符 **/
id: number;
/** 产品名称 **/
name: string;
/** 产品简介 **/
summary: string;
/** 产品详情 **/
description: string;
/** 产品类型 **/
type: string;
}
/**
* 解决方案索引文档结构
*/
export interface MeiliSolutionIndex {
/** 唯一标识符 **/
id: number;
/** 解决方案标题 **/
title: string;
/** 解决方案摘要 **/
summary: string;
/** 解决方案内容 **/
content: string;
/** 解决方案类型 **/
type: string;
}
/**
* 相关问题索引文档结构
*/
export interface MeiliQuestionIndex {
/** 唯一标识符 **/
id: number;
/** 问题标题 **/
title: string;
/** 问题内容 **/
content: string;
/** 相关产品 **/
products: string[];
/** 相关产品类型 **/
product_types: string[];
}
/**
* 相关文档索引文档结构
*/
export interface MeiliProductDocumentIndex {
/** 唯一标识符 **/
id: number;
/** 文档标题 **/
title: string;
/** 相关产品 **/
products: string[];
/** 相关产品类型 **/
product_types: string[];
}
/**
* 索引名与类型映射
*/
export interface MeiliIndexMap {
products: MeiliProductIndex;
solutions: MeiliSolutionIndex;
questions: MeiliQuestionIndex;
product_documents: MeiliProductDocumentIndex;
}
export type MeiliSearchItemType = keyof MeiliIndexMap;

View File

@ -0,0 +1,42 @@
import type { SearchResponse } from 'meilisearch';
/**
* 原始搜索分段结果
* @template T 索引类型
*/
export interface RawSearchSection<T> {
/** 索引名 **/
indexUid: string;
/** 响应数据 **/
response: SearchResponse<T>;
}
/**
* 搜索结果
*/
export interface SearchHit extends Record<string, unknown> {
objectID?: string | number;
}
/**
* 搜索分段结果
* @template T 索引类型
*/
export interface SearchSection<T> {
/** 索引名 **/
indexUid: string;
/** 原始索引名 **/
rawIndex: MeiliSearchItemType;
/** 命中条目 **/
hits: T[];
// hits: SearchHit[];
/** 条目总数 **/
estimatedTotalHits: number;
/** 处理时间 **/
processingTimeMs: number;
}