typebox-%2B-fastify by blockmatic/basilic
npx skills add https://github.com/blockmatic/basilic --skill 'TypeBox + Fastify'@fastify/type-provider-typebox 作为 TypeBox 类型提供者@sinclair/typebox 进行模式定义TypeBoxTypeProvider 从模式自动推断类型@fastify/swagger)request.params、、)从模式推断广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
request.queryrequest.bodyTypeBoxTypeProvider 确保类型安全:fastify.withTypeProvider<TypeBoxTypeProvider>()Type.* 构造函数定义模式operationId 以便生成 OpenAPItags 组织路由import { Type } from '@sinclair/typebox'
import type { FastifyPluginAsync } from 'fastify'
const UserSchema = Type.Object({
id: Type.String(),
email: Type.String({ format: 'email' }),
name: Type.String(),
})
const userRoutes: FastifyPluginAsync = async fastify => {
fastify.get('/users/:id', {
schema: {
operationId: 'getUser',
params: Type.Object({ id: Type.String() }),
response: {
200: UserSchema,
404: Type.Object({ code: Type.String(), message: Type.String() }),
},
},
}, async (request, reply) => {
// request.params.id 具有类型推断
const { id } = request.params
return reply.send(user)
})
}
Type.String()
Type.Number()
Type.Boolean()
Type.Object({ id: Type.String() })
Type.Array(Type.String())
Type.Optional(Type.String())
Type.Union([Type.String(), Type.Number()])
完整示例请参阅 路由模式模板。
使用 TypeBox 类型提供者、日志记录器和请求设置配置 Fastify 实例:
import type { TypeBoxTypeProvider } from '@fastify/type-provider-typebox'
import Fastify from 'fastify'
const fastify = Fastify({
logger: {
level: 'info',
transport: process.env.NODE_ENV === 'development' ? {
target: 'pino-pretty',
} : undefined,
},
trustProxy: true,
bodyLimit: 1048576, // 1MB
requestTimeout: 30000,
requestIdHeader: 'x-request-id',
requestIdLogLabel: 'reqId',
}).withTypeProvider<TypeBoxTypeProvider>()
完整设置请参阅 实例配置。
使用 fastify-plugin 创建具有非封装行为的可重用插件:
import type { FastifyPluginAsync } from 'fastify'
import fp from 'fastify-plugin'
const myPlugin: FastifyPluginAsync = async fastify => {
// 插件逻辑
}
export default fp(myPlugin, {
name: 'my-plugin',
})
使用钩子拦截请求、修改响应或处理错误:
fastify.addHook('onRequest', async (request, reply) => {
// 添加安全头、日志记录等
})
fastify.addHook('onResponse', async (request, reply) => {
// 修改响应、添加头等
})
fastify.addHook('onError', async (request, reply, error) => {
// 处理错误
})
使用 Fastify 的 inject() 方法进行黑盒测试:
const response = await fastify.inject({
method: 'GET',
url: '/users/123',
})
expect(response.statusCode).toBe(200)
const data = JSON.parse(response.body)
处理流式响应(例如,服务器发送事件、文本流):
fastify.post('/stream', {
schema: {
response: {
200: Type.String({ description: '流式响应' }),
},
},
}, async (request, reply) => {
reply.header('Content-Type', 'text/event-stream')
reply.header('Cache-Control', 'no-cache')
return reply.send(stream)
})
import rateLimit from '@fastify/rate-limit'
await fastify.register(rateLimit, {
max: 100,
timeWindow: 60000,
keyGenerator: request => request.ip,
})
import cors from '@fastify/cors'
await fastify.register(cors, {
origin: (origin, callback) => {
// 验证来源
callback(null, true)
},
credentials: false,
})
fastify.setErrorHandler((error, request, reply) => {
// 全局错误处理
reply.status(error.statusCode ?? 500).send({
code: 'ERROR',
message: error.message,
})
})
处理进程信号以实现优雅关闭:
const shutdown = async (signal: string) => {
fastify.log.info({ signal }, '正在关闭')
await fastify.close()
process.exit(0)
}
process.on('SIGTERM', () => shutdown('SIGTERM'))
process.on('SIGINT', () => shutdown('SIGINT'))
使用 @fastify/autoload 自动发现插件/路由:
import AutoLoad from '@fastify/autoload'
await fastify.register(AutoLoad, {
dir: path.join(__dirname, 'plugins'),
forceESM: true,
})
每周安装量
0
代码仓库
GitHub 星标数
89
首次出现时间
1970年1月1日
@fastify/type-provider-typebox for TypeBox type provider@sinclair/typebox for schema definitionsTypeBoxTypeProvider for automatic type inference from schemas@fastify/swagger)request.params, request.query, request.body) are inferred from schemasTypeBoxTypeProvider for type safety: fastify.withTypeProvider<TypeBoxTypeProvider>()Type.* constructors for schema definitionsoperationId in route schemas for OpenAPI generationtags for route organization in OpenAPI docsimport { Type } from '@sinclair/typebox'
import type { FastifyPluginAsync } from 'fastify'
const UserSchema = Type.Object({
id: Type.String(),
email: Type.String({ format: 'email' }),
name: Type.String(),
})
const userRoutes: FastifyPluginAsync = async fastify => {
fastify.get('/users/:id', {
schema: {
operationId: 'getUser',
params: Type.Object({ id: Type.String() }),
response: {
200: UserSchema,
404: Type.Object({ code: Type.String(), message: Type.String() }),
},
},
}, async (request, reply) => {
// request.params.id is typed
const { id } = request.params
return reply.send(user)
})
}
Type.String()
Type.Number()
Type.Boolean()
Type.Object({ id: Type.String() })
Type.Array(Type.String())
Type.Optional(Type.String())
Type.Union([Type.String(), Type.Number()])
See Route Schema Template for complete example.
Configure Fastify instance with TypeBox type provider, logger, and request settings:
import type { TypeBoxTypeProvider } from '@fastify/type-provider-typebox'
import Fastify from 'fastify'
const fastify = Fastify({
logger: {
level: 'info',
transport: process.env.NODE_ENV === 'development' ? {
target: 'pino-pretty',
} : undefined,
},
trustProxy: true,
bodyLimit: 1048576, // 1MB
requestTimeout: 30000,
requestIdHeader: 'x-request-id',
requestIdLogLabel: 'reqId',
}).withTypeProvider<TypeBoxTypeProvider>()
See Instance Configuration for complete setup.
Create reusable plugins with fastify-plugin for non-encapsulated behavior:
import type { FastifyPluginAsync } from 'fastify'
import fp from 'fastify-plugin'
const myPlugin: FastifyPluginAsync = async fastify => {
// Plugin logic
}
export default fp(myPlugin, {
name: 'my-plugin',
})
See Plugin Patterns and Plugin Template for examples.
Use hooks to intercept requests, modify responses, or handle errors:
fastify.addHook('onRequest', async (request, reply) => {
// Add security headers, logging, etc.
})
fastify.addHook('onResponse', async (request, reply) => {
// Modify response, add headers, etc.
})
fastify.addHook('onError', async (request, reply, error) => {
// Handle errors
})
See Hooks Guide and Hook Plugin Template for patterns.
Test routes using Fastify's inject() method for blackbox testing:
const response = await fastify.inject({
method: 'GET',
url: '/users/123',
})
expect(response.statusCode).toBe(200)
const data = JSON.parse(response.body)
See Testing Patterns and Test Utils Template for setup.
Handle streaming responses (e.g., Server-Sent Events, text streams):
fastify.post('/stream', {
schema: {
response: {
200: Type.String({ description: 'Streaming response' }),
},
},
}, async (request, reply) => {
reply.header('Content-Type', 'text/event-stream')
reply.header('Cache-Control', 'no-cache')
return reply.send(stream)
})
import rateLimit from '@fastify/rate-limit'
await fastify.register(rateLimit, {
max: 100,
timeWindow: 60000,
keyGenerator: request => request.ip,
})
import cors from '@fastify/cors'
await fastify.register(cors, {
origin: (origin, callback) => {
// Validate origin
callback(null, true)
},
credentials: false,
})
fastify.setErrorHandler((error, request, reply) => {
// Global error handling
reply.status(error.statusCode ?? 500).send({
code: 'ERROR',
message: error.message,
})
})
Handle process signals for graceful shutdown:
const shutdown = async (signal: string) => {
fastify.log.info({ signal }, 'Shutting down')
await fastify.close()
process.exit(0)
}
process.on('SIGTERM', () => shutdown('SIGTERM'))
process.on('SIGINT', () => shutdown('SIGINT'))
Use @fastify/autoload for automatic plugin/route discovery:
import AutoLoad from '@fastify/autoload'
await fastify.register(AutoLoad, {
dir: path.join(__dirname, 'plugins'),
forceESM: true,
})
Weekly Installs
0
Repository
GitHub Stars
89
First Seen
Jan 1, 1970
Vue.js测试最佳实践:Vue 3组件、组合式函数、Pinia与异步测试完整指南
3,700 周安装
AI图像生成工具 - 50+模型一键生成图片 | FLUX、Gemini、Grok等
16 周安装
Alchemy Web3技能:区块链数据查询API,支持以太坊、Polygon、Solana等80+链
19 周安装
Claude setperms 工具:一键配置开发环境权限和现代CLI工具
21 周安装
系统性调试指南:遵循4阶段流程,高效定位并修复根本原因
20 周安装
data-driven-testing 测试技能已弃用 | 测试最佳实践替代方案 | 0xbigboss/claude-code
58 周安装
specalign规范对齐工具:自动检测代码与文档差异,确保开发一致性
58 周安装