[ PROMPT_NODE_24490 ]
Workers 设计模式
[ SKILL_DOCUMENTATION ]
# Workers 开发模式
## 错误处理
typescript
class HTTPError extends Error {
constructor(public status: number, message: string) { super(message); }
}
export default {
async fetch(request: Request, env: Env): Promise {
try {
return await handleRequest(request, env);
} catch (error) {
if (error instanceof HTTPError) {
return new Response(JSON.stringify({ error: error.message }), {
status: error.status, headers: { 'Content-Type': 'application/json' }
});
}
return new Response('Internal Server Error', { status: 500 });
}
},
};
## CORS
typescript
const corsHeaders = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS' };
if (request.method === 'OPTIONS') return new Response(null, { headers: corsHeaders });
## 路由
typescript
const router = { 'GET /api/users': handleGetUsers, 'POST /api/users': handleCreateUser };
const handler = router[`${request.method} ${url.pathname}`];
return handler ? handler(request, env) : new Response('Not Found', { status: 404 });
**生产环境**: 使用 Hono, itty-router 或 Worktop (参考 [frameworks.md](./frameworks.md))
## 请求验证 (Zod)
typescript
import { z } from 'zod';
const userSchema = z.object({
name: z.string().min(1).max(100),
email: z.string().email(),
age: z.number().int().positive().optional(),
});
async function handleCreateUser(request: Request) {
try {
const body = await request.json();
const validated = userSchema.parse(body); // 数据无效时抛出异常
return new Response(JSON.stringify({ id: 1, ...validated }), {
status: 201,
headers: { 'Content-Type': 'application/json' },
});
} catch (err) {
if (err instanceof z.ZodError) {
return new Response(JSON.stringify({ errors: err.errors }), { status: 400 });
}
throw err;
}
}
**配合 Hono**: 使用 `@hono/zod-validator` 进行自动验证 (参考 [frameworks.md](./frameworks.md))
## 性能
typescript
// ❌ 串行
const user = await fetch('/api/user/1');
const posts = await fetch('/api/posts?user=1');
// ✅ 并行
const [user, posts] = await Promise.all([fetch('/api/user/1'), fetch('/api/posts?user=1')]);
## 流式传输
typescript
const stream = new ReadableStream({
async start(controller) {
for (let i = 0; i < 1000; i++) {
controller.enqueue(new TextEncoder().encode(`Item ${i}n`));
if (i % 100 ==