Files
MyGoNavi/frontend/src/utils/redisSearchPattern.ts
Syngnat a06f45da28 feat(redis): 新增 Key 精确搜索模式
- 增加 Redis Key 模糊/精确搜索切换
- 精确模式不再追加通配符并保留大小写敏感匹配
- 转义 Redis glob 特殊字符避免误匹配
- 补充搜索模式回归测试
2026-04-26 20:34:07 +08:00

53 lines
1.4 KiB
TypeScript

const REDIS_GLOB_SPECIAL_CHARS = /([*?\[\]\\])/g;
const ASCII_LETTER = /^[A-Za-z]$/;
export type RedisSearchMode = 'fuzzy' | 'exact';
const escapeRedisGlobLiteral = (value: string): string => {
return value.replace(REDIS_GLOB_SPECIAL_CHARS, '\\$1');
};
const toCaseInsensitiveRedisGlobLiteral = (value: string): string => {
return Array.from(value).map((char) => {
if (!ASCII_LETTER.test(char)) {
return escapeRedisGlobLiteral(char);
}
const lower = char.toLowerCase();
const upper = char.toUpperCase();
return `[${lower}${upper}]`;
}).join('');
};
export const normalizeRedisSearchInput = (
rawValue: string,
mode: RedisSearchMode = 'fuzzy',
): { keyword: string; pattern: string } => {
const keyword = String(rawValue || '').trim();
if (!keyword) {
return { keyword: '', pattern: '*' };
}
if (mode === 'exact') {
return {
keyword,
pattern: escapeRedisGlobLiteral(keyword),
};
}
return {
keyword,
pattern: `*${toCaseInsensitiveRedisGlobLiteral(keyword)}*`,
};
};
export const normalizeRedisSearchDraftChange = (rawValue: string, mode: RedisSearchMode = 'fuzzy'): {
keyword: string;
pattern: string;
shouldSearchImmediately: boolean;
} => {
const normalized = normalizeRedisSearchInput(rawValue, mode);
return {
...normalized,
shouldSearchImmediately: normalized.keyword === '',
};
};