- 空值处理与类型控制:为相关关系型字段的数据处理添加空值处理与类型控制 - 调整目录结构:将文件目录按照实际查询划分为Product和ProductList两个文件
54 lines
1.3 KiB
TypeScript
54 lines
1.3 KiB
TypeScript
import { toProductView } from '~~/server/mappers/productMapper';
|
|
import { toProductListView } from '~~/server/mappers/productListMapper';
|
|
|
|
export const productService = {
|
|
async getProductList(locale: string) {
|
|
const query = await loadAssetAsString(
|
|
'assets/server',
|
|
'graphql/productList.graphql'
|
|
);
|
|
if (!query) {
|
|
throw createError({
|
|
statusCode: 500,
|
|
message: 'GraphQL query not found',
|
|
});
|
|
}
|
|
|
|
const data = await directus.query<{ products: Product[] }>(query, {
|
|
locale: locale,
|
|
});
|
|
|
|
const products = data?.products || [];
|
|
|
|
return products.map((product) => toProductListView(product));
|
|
},
|
|
async getProductById(id: string, locale: string) {
|
|
const query = await loadAssetAsString(
|
|
'assets/server',
|
|
'graphql/product.graphql'
|
|
);
|
|
if (!query) {
|
|
throw createError({
|
|
statusCode: 500,
|
|
message: 'GraphQL query not found',
|
|
});
|
|
}
|
|
|
|
const data = await directus.query<{ products_by_id: Product }>(query, {
|
|
id: id,
|
|
locale: locale,
|
|
});
|
|
|
|
const product = data?.products_by_id;
|
|
|
|
if (!product || product.status === 'archived') {
|
|
throw createError({
|
|
statusCode: 404,
|
|
statusMessage: 'Product not found',
|
|
});
|
|
}
|
|
|
|
return toProductView(product);
|
|
},
|
|
};
|