94 lines
2.4 KiB
TypeScript
94 lines
2.4 KiB
TypeScript
import { isObject } from '../../server/utils/object';
|
|
|
|
/**
|
|
* 将 Directus 返回的 QuestionType 类型转换为 QuestionTypeView 视图模型
|
|
*
|
|
* @param raw: 原始的 QuestionType 数据
|
|
* @returns 转换后的 QuestionTypeView 对象
|
|
*
|
|
* @example
|
|
* const view = toQuestionTypeView(rawQuestionType);
|
|
*/
|
|
export function toQuestionTypeView(
|
|
raw: QuestionType | string | null
|
|
): QuestionTypeView {
|
|
if (typeof raw === 'string' || raw === null) {
|
|
return {
|
|
id: '',
|
|
type: '',
|
|
} satisfies QuestionTypeView;
|
|
}
|
|
const trans = raw.translations?.[0];
|
|
|
|
return {
|
|
id: raw.id.toString(),
|
|
type: trans?.name ?? '',
|
|
};
|
|
}
|
|
|
|
/**
|
|
* 将 Directus 返回的 Question 数据转换为 ProductQuestionView 视图模型
|
|
*
|
|
* @param raw: 原始的 Question 数据
|
|
* @returns 转换后的 ProductQuestionView 对象
|
|
*
|
|
* @example
|
|
* const view = toProductQuestionView(rawQuestion);
|
|
*/
|
|
export function toProductQuestionView(raw: Question): ProductQuestionView {
|
|
const trans = raw.translations?.[0];
|
|
|
|
return {
|
|
id: raw.id.toString(),
|
|
title: trans?.title ?? '',
|
|
content: trans?.content ?? '',
|
|
};
|
|
}
|
|
|
|
/**
|
|
* 将 Directus 返回的 Question 数据转换为 QuestionListView 视图模型
|
|
*
|
|
* @param raw: 原始的 Question 数据
|
|
* @returns 转换后的 QuestionListView 对象
|
|
* ---
|
|
* @example
|
|
* const view = toQuestionListView(rawQuestion);
|
|
*/
|
|
export function toQuestionListView(raw: Question): QuestionListView {
|
|
const trans = raw.translations?.[0];
|
|
|
|
const type = toQuestionTypeView(raw.type ?? null);
|
|
|
|
const related_products: QuestionListProduct[] = (raw.products ?? [])
|
|
.filter(isObject<ProductsQuestion>)
|
|
.map((item) => item.products_id)
|
|
.filter(isObject<Product>)
|
|
.map((item) => {
|
|
const translations = item.translations?.[0];
|
|
|
|
const product_type = isObject<ProductType>(item.product_type)
|
|
? ({
|
|
id: item.product_type.id.toString(),
|
|
name: item.product_type.translations?.[0]?.name ?? '',
|
|
} satisfies QuestionListProductType)
|
|
: ({
|
|
id: '',
|
|
name: '',
|
|
} satisfies QuestionListProductType);
|
|
|
|
return {
|
|
id: item.id.toString(),
|
|
name: translations?.name ?? '',
|
|
type: product_type,
|
|
};
|
|
});
|
|
|
|
return {
|
|
id: raw.id.toString(),
|
|
type: type,
|
|
title: trans?.title ?? '',
|
|
content: trans?.content ?? '',
|
|
products: related_products,
|
|
};
|
|
}
|