diff --git a/src/helper/collection.ts b/src/helper/collection.ts new file mode 100644 index 0000000..93c987b --- /dev/null +++ b/src/helper/collection.ts @@ -0,0 +1,119 @@ +type Translation = { + languages_code: string | { code: string }; + [key: string]: unknown; +}; + +/** + * 将数据中的 translations 字段根据指定的语言代码进行过滤 + * @param data 给定的数据 + * @param langCode 目标语言代码 + * @returns 过滤后的数据 + * + * --- + * @example + * const data = [ + * { + * id: 1, + * translations: [ + * { languages_code: 'zh-CN', name: '中文名称1' }, + * { languages_code: 'en-US', name: 'English Name1' } + * ] + * }, + * { + * id: 2, + * translations: [ + * { languages_code: 'zh-CN', name: '中文名称2' }, + * { languages_code: 'en-US', name: 'English Name2' } + * ] + * } + * ]; + * const filtered = filterTranslations(data, 'zh-CN'); + * console.log(filtered); + * // 输出: + * // [ + * // { + * // id: 1, + * // translations: [ + * // { languages_code: 'zh-CN', name: '中文名称1' } + * // ] + * // }, + * // { + * // id: 2, + * // translations: [ + * // { languages_code: 'zh-CN', name: '中文名称2' } + * // ] + * // } + * // ] + */ +export function filterTranslations(data: T[], langCode: string): T[] { + function deepFilter(obj: U): U { + if (Array.isArray(obj)) { + // 数组:递归处理每个元素 + return obj.map(deepFilter) as U; + } + + if (typeof obj === 'object' && obj !== null) { + const result: Record = {}; + + for (const [key, value] of Object.entries(obj)) { + if (key === 'translations' && Array.isArray(value)) { + // translations 数组过滤 + const filtered = value.filter((t): t is Translation => { + if ( + typeof t === 'object' && + t !== null && + 'languages_code' in t + ) { + const langField = t.languages_code; + const code = + typeof langField === 'string' + ? langField + : langField.code; + return code === langCode; + } + return false; + }); + result[key] = filtered; + } else { + // 递归处理其他字段 + result[key] = deepFilter(value); + } + } + return result as U; + } + + // 基本类型:直接返回 + return obj; + } + + return data.map(deepFilter); +} + +/** + * 将字段配置对象转换为 Directus 查询字段数组 + * @param fields 字段配置对象 + * @returns Directus 查询字段数组 + */ +export function buildQueryFields(fields: Record): string[] { + const result = new Set(); + + result.add('id'); // 确保包含id字段 + + for (const key in fields) { + const path = fields[key]; + if (!path) continue; + + const parts = path?.split('.') || []; + + // 如果字段中包含translations,则加入languages_code.code + const transIndex = parts.indexOf('translations'); + if (transIndex !== -1) { + const prefix = parts.slice(0, transIndex + 1).join('.'); + result.add(`${prefix}.languages_code.code`); + } + + result.add(path); + } + + return Array.from(result); +}