hono-typescript by mindrally/skills
npx skills add https://github.com/mindrally/skills --skill hono-typescript您是一位精通 Hono 和 TypeScript 开发的专家,深谙构建在 Cloudflare Workers、Deno、Bun 和 Node.js 上运行的超快速、边缘优先的 API。
any 类型 - 应创建必要的类型isLoading、hasError、canDelete广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
readonlyimport typesrc/
routes/
{resource}/
index.ts
handlers.ts
validators.ts
middleware/
auth.ts
cors.ts
logger.ts
services/
{domain}Service.ts
types/
index.ts
utils/
config/
index.ts
import { Hono } from 'hono';
// 为环境绑定定义类型
type Bindings = {
DB: D1Database;
KV: KVNamespace;
JWT_SECRET: string;
};
type Variables = {
user: User;
};
const app = new Hono<{ Bindings: Bindings; Variables: Variables }>();
使用方法链式调用来定义清晰的路由
使用 app.route() 对相关路由进行分组
使用带有适当类型的路由参数
const users = new Hono<{ Bindings: Bindings }>();
users.get('/', listUsers); users.get('/:id', getUser); users.post('/', zValidator('json', createUserSchema), createUser); users.put('/:id', zValidator('json', updateUserSchema), updateUser); users.delete('/:id', deleteUser);
app.route('/api/users', users);
在可用的情况下使用 Hono 内置的中间件
为自定义逻辑创建类型化的中间件
链式组合中间件以提高可组合性
import { cors } from 'hono/cors'; import { logger } from 'hono/logger'; import { jwt } from 'hono/jwt';
app.use('', logger()); app.use('/api/', cors()); app.use('/api/*', jwt({ secret: 'your-secret' }));
// 自定义中间件 const authMiddleware = async (c: Context, next: Next) => { const user = await validateUser(c); c.set('user', user); await next(); };
使用 @hono/zod-validator 进行请求验证
为所有请求输入定义模式
从 Zod 模式推断类型
import { z } from 'zod'; import { zValidator } from '@hono/zod-validator';
const createUserSchema = z.object({ name: z.string().min(1), email: z.string().email(), role: z.enum(['user', 'admin']).default('user'), });
type CreateUserInput = z.infer<typeof createUserSchema>;
app.post('/users', zValidator('json', createUserSchema), async (c) => { const data = c.req.valid('json'); // data 的类型为 CreateUserInput });
使用类型化的上下文以获得更好的类型安全
使用辅助方法处理响应:c.json()、c.text()、c.html()
通过上下文访问环境绑定
app.get('/users/:id', async (c) => { const id = c.req.param('id'); const db = c.env.DB;
const user = await db.prepare('SELECT * FROM users WHERE id = ?') .bind(id) .first();
if (!user) { return c.json({ error: 'User not found' }, 404); }
return c.json(user); });
使用 Hono 的 HTTPException 处理预期错误
创建全局错误处理中间件
返回一致的错误响应
import { HTTPException } from 'hono/http-exception';
// 抛出错误 if (!user) { throw new HTTPException(404, { message: 'User not found' }); }
// 全局错误处理器 app.onError((err, c) => { if (err instanceof HTTPException) { return c.json({ error: err.message }, err.status); } console.error(err); return c.json({ error: 'Internal Server Error' }, 500); });
使用 Workers KV 进行键值存储
使用 D1 处理 SQL 数据库
使用 R2 处理对象存储
使用 Durable Objects 处理有状态应用
// D1 数据库 const result = await c.env.DB.prepare('SELECT * FROM users').all();
// KV 存储 await c.env.KV.put('key', 'value'); const value = await c.env.KV.get('key');
// R2 存储 await c.env.BUCKET.put('file.txt', content);
使用 Hono 的测试客户端进行集成测试
使用 Vitest 或 Jest 作为测试运行器
分别测试处理程序和中间件
import { testClient } from 'hono/testing'; import { describe, it, expect } from 'vitest';
describe('User API', () => { const client = testClient(app);
it('should list users', async () => { const res = await client.api.users.$get(); expect(res.status).toBe(200); const data = await res.json(); expect(Array.isArray(data)).toBe(true); }); });
hono/tiny 预设以获得最小的包大小hono/secure-headers 中间件Hono 可在多个运行时上运行。请相应配置:
// Cloudflare Workers
export default app;
// Node.js
import { serve } from '@hono/node-server';
serve(app);
// Bun
export default app;
// Deno
Deno.serve(app.fetch);
每周安装量
116
代码仓库
GitHub 星标数
43
首次出现
2026年1月25日
安全审计
安装于
gemini-cli97
opencode96
codex92
github-copilot88
cursor87
amp83
You are an expert in Hono and TypeScript development with deep knowledge of building ultrafast, edge-first APIs that run on Cloudflare Workers, Deno, Bun, and Node.js.
any type - create necessary types insteadisLoading, hasError, canDeletereadonly for immutable propertiesimport type for type-only importssrc/
routes/
{resource}/
index.ts
handlers.ts
validators.ts
middleware/
auth.ts
cors.ts
logger.ts
services/
{domain}Service.ts
types/
index.ts
utils/
config/
index.ts
import { Hono } from 'hono';
// Type your environment bindings
type Bindings = {
DB: D1Database;
KV: KVNamespace;
JWT_SECRET: string;
};
type Variables = {
user: User;
};
const app = new Hono<{ Bindings: Bindings; Variables: Variables }>();
Use method chaining for clean route definitions
Group related routes with app.route()
Use route parameters with proper typing
const users = new Hono<{ Bindings: Bindings }>();
users.get('/', listUsers); users.get('/:id', getUser); users.post('/', zValidator('json', createUserSchema), createUser); users.put('/:id', zValidator('json', updateUserSchema), updateUser); users.delete('/:id', deleteUser);
app.route('/api/users', users);
Use Hono's built-in middleware where available
Create typed middleware for custom logic
Chain middleware for composability
import { cors } from 'hono/cors'; import { logger } from 'hono/logger'; import { jwt } from 'hono/jwt';
app.use('', logger()); app.use('/api/', cors()); app.use('/api/*', jwt({ secret: 'your-secret' }));
// Custom middleware const authMiddleware = async (c: Context, next: Next) => { const user = await validateUser(c); c.set('user', user); await next(); };
Use @hono/zod-validator for request validation
Define schemas for all request inputs
Infer types from Zod schemas
import { z } from 'zod'; import { zValidator } from '@hono/zod-validator';
const createUserSchema = z.object({ name: z.string().min(1), email: z.string().email(), role: z.enum(['user', 'admin']).default('user'), });
type CreateUserInput = z.infer<typeof createUserSchema>;
app.post('/users', zValidator('json', createUserSchema), async (c) => { const data = c.req.valid('json'); // data is typed as CreateUserInput });
Use typed context for better type safety
Use helper methods for responses: c.json(), c.text(), c.html()
Access environment bindings through context
app.get('/users/:id', async (c) => { const id = c.req.param('id'); const db = c.env.DB;
const user = await db.prepare('SELECT * FROM users WHERE id = ?') .bind(id) .first();
if (!user) { return c.json({ error: 'User not found' }, 404); }
return c.json(user); });
Use Hono's HTTPException for expected errors
Create global error handler middleware
Return consistent error responses
import { HTTPException } from 'hono/http-exception';
// Throwing errors if (!user) { throw new HTTPException(404, { message: 'User not found' }); }
// Global error handler app.onError((err, c) => { if (err instanceof HTTPException) { return c.json({ error: err.message }, err.status); } console.error(err); return c.json({ error: 'Internal Server Error' }, 500); });
Use Workers KV for key-value storage
Use D1 for SQL databases
Use R2 for object storage
Use Durable Objects for stateful applications
// D1 Database const result = await c.env.DB.prepare('SELECT * FROM users').all();
// KV Storage await c.env.KV.put('key', 'value'); const value = await c.env.KV.get('key');
// R2 Storage await c.env.BUCKET.put('file.txt', content);
Use Hono's test client for integration tests
Use Vitest or Jest as test runner
Test handlers and middleware separately
import { testClient } from 'hono/testing'; import { describe, it, expect } from 'vitest';
describe('User API', () => { const client = testClient(app);
it('should list users', async () => { const res = await client.api.users.$get(); expect(res.status).toBe(200); const data = await res.json(); expect(Array.isArray(data)).toBe(true); }); });
hono/tiny preset for minimal bundle sizehono/secure-headers middlewareHono runs on multiple runtimes. Configure appropriately:
// Cloudflare Workers
export default app;
// Node.js
import { serve } from '@hono/node-server';
serve(app);
// Bun
export default app;
// Deno
Deno.serve(app.fetch);
Weekly Installs
116
Repository
GitHub Stars
43
First Seen
Jan 25, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
gemini-cli97
opencode96
codex92
github-copilot88
cursor87
amp83
Lark CLI IM 即时消息管理工具:机器人/用户身份操作聊天、消息、文件下载
31,500 周安装