- 空值处理与类型控制:为相关关系型字段的数据处理添加空值处理与类型控制 - 调整目录结构:将文件目录按照实际查询划分为Product和ProductList两个文件
80 lines
2.1 KiB
TypeScript
80 lines
2.1 KiB
TypeScript
import { isObject } from '../../server/utils/object';
|
|
|
|
/**
|
|
* 将 Directus 返回的 DocumentType 数据转换为 DocumentTypeView 视图模型
|
|
*
|
|
* @param raw: 原始的 DocumentType 数据
|
|
* @returns 转换后的 DocumentTypeView 对象
|
|
*
|
|
* @example
|
|
* const view = toDocumentTypeView(rawDocumentType);
|
|
*/
|
|
export function toDocumentTypeView(
|
|
raw: DocumentType | string | null
|
|
): DocumentTypeView {
|
|
if (typeof raw === 'string' || raw === null) {
|
|
return {
|
|
id: '-1',
|
|
name: '',
|
|
} satisfies DocumentTypeView;
|
|
}
|
|
const trans = raw.translations?.[0];
|
|
|
|
return {
|
|
id: raw.id.toString(),
|
|
name: trans?.name ?? '',
|
|
};
|
|
}
|
|
|
|
/**
|
|
* 将 Directus 返回的 Document 数据转换为 DocumentListView 视图模型
|
|
*
|
|
* @param raw: 原始的 Document 数据
|
|
* @returns 转换后的 DocumentListView 对象
|
|
*
|
|
* @example
|
|
* const view = toDocumentListView(rawDocument);
|
|
*/
|
|
export function toDocumentListView(raw: ProductDocument): DocumentListView {
|
|
const trans = raw.translations?.[0];
|
|
|
|
const type = toDocumentTypeView(raw.type ?? null);
|
|
|
|
const file = isObject<DirectusFile>(raw.file) ? raw.file : undefined;
|
|
const fileId = file?.id ?? '';
|
|
|
|
const url = `/api/assets/${fileId}`;
|
|
|
|
const related_products: DocumentListProduct[] = (raw.products ?? [])
|
|
.filter(isObject<ProductsProductDocument>)
|
|
.map((item) => item.products_id)
|
|
.filter(isObject<Product>)
|
|
.map((item) => {
|
|
const productType = isObject<ProductType>(item.product_type)
|
|
? ({
|
|
id: item.product_type.id.toString(),
|
|
name: item.product_type.translations?.[0]?.name ?? '',
|
|
} satisfies DocumentListProductType)
|
|
: ({
|
|
id: '',
|
|
name: '',
|
|
} satisfies DocumentListProductType);
|
|
return {
|
|
id: item.id.toString(),
|
|
name: item.translations?.[0]?.name ?? '',
|
|
type: productType,
|
|
};
|
|
});
|
|
|
|
return {
|
|
id: raw.id.toString(),
|
|
fileId: fileId,
|
|
filename: file?.filename_download ?? '',
|
|
title: trans?.title ?? '',
|
|
url: url,
|
|
size: file?.filesize ?? 0,
|
|
type: type,
|
|
products: related_products,
|
|
};
|
|
}
|