refactor: 将Data到ViewModel的转换由App转移至Server端
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m15s
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m15s
- 将逻辑转移到Server端后,简化前端逻辑
This commit is contained in:
76
server/mappers/documentMapper.ts
Normal file
76
server/mappers/documentMapper.ts
Normal file
@ -0,0 +1,76 @@
|
||||
/**
|
||||
* 将 Directus 返回的 Document 数据转换为 ProductDocumentView 视图模型
|
||||
*
|
||||
* @param raw: 原始的 Document 数据
|
||||
* @returns 转换后的 ProductDocumentView 对象
|
||||
*
|
||||
* @example
|
||||
* const view = toProductDocumentView(rawDocument);
|
||||
*/
|
||||
export function toProductDocumentView(
|
||||
raw: ProductDocument
|
||||
): ProductDocumentView {
|
||||
const trans = raw.translations?.[0];
|
||||
const file = isObject<DirectusFile>(raw.file) ? raw.file : undefined;
|
||||
const fileId = file?.id ?? '';
|
||||
|
||||
const url = `/api/assets/${fileId}`;
|
||||
|
||||
return {
|
||||
id: raw.id,
|
||||
fileId: fileId,
|
||||
filename: file?.filename_download ?? '',
|
||||
title: trans?.title ?? '',
|
||||
url: url,
|
||||
size: file?.filesize ?? 0,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 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 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,
|
||||
name: item.product_type.translations?.[0]?.name ?? '',
|
||||
} satisfies DocumentListProductType)
|
||||
: ({
|
||||
id: -1,
|
||||
name: '',
|
||||
} satisfies DocumentListProductType);
|
||||
return {
|
||||
id: item.id,
|
||||
name: item.translations?.[0]?.name ?? '',
|
||||
type: productType,
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
id: raw.id,
|
||||
fileId: fileId,
|
||||
filename: file?.filename_download ?? '',
|
||||
title: trans?.title ?? '',
|
||||
url: url,
|
||||
size: file?.filesize ?? 0,
|
||||
products: related_products,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user