-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcustom-fastify.ts
More file actions
177 lines (162 loc) · 4.99 KB
/
custom-fastify.ts
File metadata and controls
177 lines (162 loc) · 4.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
/**
* Custom Fastify Instance Example
*
* This example demonstrates how to use @bitfocusas/api with your own
* Fastify instance. This is useful when you want to:
* - Integrate with an existing Fastify application
* - Have more control over Fastify configuration
* - Share a Fastify instance across multiple modules
* - Use custom Fastify plugins before attaching the API server
*
* Run with: npx tsx examples/custom-fastify.ts
*/
import fastify from 'fastify'
import { APIServer, z } from '../src/index'
// Create your own Fastify instance with custom configuration
const customFastify = fastify({
logger: {
level: 'info',
transport: {
target: 'pino-pretty',
options: {
translateTime: 'HH:MM:ss Z',
ignore: 'pid,hostname',
colorize: true,
},
},
},
// Add any other Fastify options you need
disableRequestLogging: false,
})
// Register your own plugins before attaching the API server
customFastify.register(async (instance) => {
// Example: Add a custom hook
instance.addHook('onRequest', async (request, _reply) => {
request.log.info({ url: request.url, method: request.method }, 'Incoming request')
})
// Example: Add a custom route
instance.get('/health', async () => {
return { status: 'ok', timestamp: new Date().toISOString() }
})
})
// Create API server with your existing Fastify instance
const app = new APIServer({
fastify: customFastify, // 🔑 Pass your Fastify instance here
apiTitle: 'Custom Fastify Example',
apiDescription: 'API server attached to a custom Fastify instance',
apiTags: [
{ name: 'Users', description: 'User management endpoints' },
{ name: 'System', description: 'System status and health' },
],
})
// Define your endpoints as usual
app.createEndpoint({
method: 'GET',
url: '/users',
query: z.object({
limit: z.coerce.number().int().positive().max(100).default(10).describe('Maximum number of users to return'),
}),
response: z.object({
users: z.array(
z.object({
id: z.string().describe('User ID'),
name: z.string().describe('User name'),
email: z.string().describe('User email'),
}),
),
total: z.number().describe('Total number of users'),
}),
config: {
description: 'List users with pagination',
tags: ['Users'],
},
handler: async (request) => {
// Simulated user data
const users = [
{ id: '1', name: 'Alice', email: 'alice@example.com' },
{ id: '2', name: 'Bob', email: 'bob@example.com' },
{ id: '3', name: 'Charlie', email: 'charlie@example.com' },
]
const { limit } = request.query
return {
users: users.slice(0, limit),
total: users.length,
}
},
})
app.createEndpoint({
method: 'POST',
url: '/users',
body: z.object({
name: z.string().min(1).describe('User name'),
email: z.string().email().describe('User email'),
}),
response: z.object({
id: z.string().describe('Created user ID'),
name: z.string().describe('User name'),
email: z.string().describe('User email'),
createdAt: z.string().describe('Creation timestamp'),
}),
config: {
description: 'Create a new user',
tags: ['Users'],
},
// Stricter rate limit for user creation (10 requests per minute)
rateLimit: { max: 10, timeWindow: '1m' },
handler: async (request) => {
const { name, email } = request.body
// In a real app, you'd save to database
return {
id: crypto.randomUUID(),
name,
email,
createdAt: new Date().toISOString(),
}
},
})
// Health check endpoint with rate limiting disabled
app.createEndpoint({
method: 'GET',
url: '/status',
response: z.object({
status: z.string().describe('Service status'),
uptime: z.number().describe('Uptime in seconds'),
timestamp: z.string().describe('Current timestamp'),
}),
config: {
description: 'Service status check (no rate limiting)',
tags: ['System'],
},
// Disable rate limiting for monitoring endpoints
rateLimit: false,
handler: async () => {
return {
status: 'healthy',
uptime: process.uptime(),
timestamp: new Date().toISOString(),
}
},
})
// Setup graceful shutdown
app.setupGracefulShutdown()
// Call app.start() to attach endpoints (but it won't start the server)
// You're responsible for starting your Fastify instance
await app.start()
// Start your Fastify instance yourself
const port = 3000
const host = '127.0.0.1'
await customFastify.listen({ port, host })
console.log('\n✅ Server started with custom Fastify instance!')
console.log(`📝 API Documentation: http://localhost:${port}/docs`)
console.log(`🏥 Health check: http://localhost:${port}/health`)
console.log('\n💡 Try these commands:')
console.log(' # Health check (custom route)')
console.log(` curl http://localhost:${port}/health`)
console.log('\n # Status check (no rate limiting)')
console.log(` curl http://localhost:${port}/status`)
console.log('\n # List users')
console.log(` curl http://localhost:${port}/users?limit=2`)
console.log('\n # Create user (rate limited: 10 req/min)')
console.log(
` curl -X POST http://localhost:${port}/users -H "Content-Type: application/json" -d '{"name":"John Doe","email":"john@example.com"}'`,
)