83 lines
2.2 KiB
TypeScript
83 lines
2.2 KiB
TypeScript
import { App, staticFiles, cors } from "fresh";
|
||
import { define, type State } from "./utils.ts";
|
||
|
||
export const app = new App<State>();
|
||
|
||
app.use(cors({
|
||
origin: "*",
|
||
allowHeaders: ["*"],
|
||
allowMethods: ["POST", "GET", "OPTIONS"],
|
||
exposeHeaders: ["Content-Length", "X-Kuma-Revision"],
|
||
maxAge: 600,
|
||
credentials: true,
|
||
}))
|
||
|
||
app.use(staticFiles());
|
||
|
||
// 模拟产品数据
|
||
const mockProductsList = [
|
||
{
|
||
id: 1,
|
||
name: "Xiaomi Buds 5 Pro",
|
||
description: "高音质无线蓝牙耳机,续航可达30小时",
|
||
price: 1199.19,
|
||
imageUrl: "https://cdn.cnbj0.fds.api.mi-img.com/b2c-shopapi-pms/pms_1740638541.0557913.png",
|
||
stock: 2000,
|
||
categoryId: 1,
|
||
},
|
||
{
|
||
id: 2,
|
||
name: "机械键盘MK71pro",
|
||
description: "青轴机械键盘,全键无冲",
|
||
price: 899.00,
|
||
imageUrl: "https://cdn.cnbj0.fds.api.mi-img.com/b2c-shopapi-pms/67D4F43CD4C647AD8F45892D6567E14A.png",
|
||
stock: 1000,
|
||
categoryId: 1,
|
||
},
|
||
{
|
||
id: 3,
|
||
name: "Xiaomi Watch S4 Sport",
|
||
description: "多功能智能手表,支持心率监测和GPS",
|
||
price: 1699.00,
|
||
imageUrl: "https://cdn.cnbj0.fds.api.mi-img.com/b2c-shopapi-pms/pms_1721233615.78223053.png",
|
||
stock: 200,
|
||
categoryId: 1,
|
||
}
|
||
];
|
||
|
||
const Res = <T extends Array<Object> | Object>(data: T) => {
|
||
return JSON.stringify({
|
||
code: 200,
|
||
message: "success",
|
||
data: data
|
||
});
|
||
}
|
||
|
||
// http://127.0.0.1:3000/api/productsList
|
||
app.get("/api/productsList", (ctx: { params: { name: any; }; }) => {
|
||
return new Response(Res(mockProductsList));
|
||
});
|
||
|
||
// http://127.0.0.1:3000/api/productsInfo?id=3
|
||
app.get("/api/productsInfo", (req: Request, ctx: { params: { id: number; }; }) => {
|
||
const id = (new URL(req.url)).searchParams.get('id')
|
||
|
||
if (!id) {
|
||
return new Response(Res("缺少id参数"));
|
||
}
|
||
|
||
const result = mockProductsList.find(product => product.id == Number(id))
|
||
if (!result) {
|
||
return new Response(Res("找不到数据"));
|
||
}
|
||
|
||
return new Response(Res(result));
|
||
});
|
||
|
||
const exampleLoggerMiddleware = define.middleware((ctx: { req: { method: any; url: any; }; next: () => any; }) => {
|
||
console.log(`${ctx.req.method} ${ctx.req.url}`);
|
||
return ctx.next();
|
||
});
|
||
|
||
app.use(exampleLoggerMiddleware);
|