完成deno后端测试用的接口

This commit is contained in:
编码猿
2025-09-16 23:40:58 +08:00
parent c156637f03
commit 61c84b0842
12 changed files with 1576 additions and 9 deletions

View File

@@ -1,7 +1,82 @@
export function add(a: number, b: number): number {
return a + b;
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
});
}
if (import.meta.main) {
console.log("Add 2 + 3 =", add(2, 3));
}
// 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);