UNPKG

36.8 kBTypeScriptView Raw
1import { FastifyError } from '@fastify/error'
2import { ConstraintStrategy, FindResult, HTTPVersion } from 'find-my-way'
3import * as http from 'http'
4import { InjectOptions, CallbackFunc as LightMyRequestCallback, Chain as LightMyRequestChain, Response as LightMyRequestResponse } from 'light-my-request'
5import { AddressInfo } from 'net'
6import { AddContentTypeParser, ConstructorAction, FastifyBodyParser, ProtoAction, getDefaultJsonParser, hasContentTypeParser, removeAllContentTypeParsers, removeContentTypeParser } from './content-type-parser'
7import { ApplicationHook, HookAsyncLookup, HookLookup, LifecycleHook, onCloseAsyncHookHandler, onCloseHookHandler, onErrorAsyncHookHandler, onErrorHookHandler, onListenAsyncHookHandler, onListenHookHandler, onReadyAsyncHookHandler, onReadyHookHandler, onRegisterHookHandler, onRequestAbortAsyncHookHandler, onRequestAbortHookHandler, onRequestAsyncHookHandler, onRequestHookHandler, onResponseAsyncHookHandler, onResponseHookHandler, onRouteHookHandler, onSendAsyncHookHandler, onSendHookHandler, onTimeoutAsyncHookHandler, onTimeoutHookHandler, preCloseAsyncHookHandler, preCloseHookHandler, preHandlerAsyncHookHandler, preHandlerHookHandler, preParsingAsyncHookHandler, preParsingHookHandler, preSerializationAsyncHookHandler, preSerializationHookHandler, preValidationAsyncHookHandler, preValidationHookHandler } from './hooks'
8import { FastifyBaseLogger, FastifyChildLoggerFactory } from './logger'
9import { FastifyRegister } from './register'
10import { FastifyReply } from './reply'
11import { FastifyRequest } from './request'
12import { DefaultRoute, RouteGenericInterface, RouteHandlerMethod, RouteOptions, RouteShorthandMethod } from './route'
13import {
14 FastifySchema,
15 FastifySchemaCompiler,
16 FastifySchemaControllerOptions,
17 FastifySerializerCompiler,
18 SchemaErrorFormatter
19} from './schema'
20import {
21 FastifyTypeProvider,
22 FastifyTypeProviderDefault
23} from './type-provider'
24import { ContextConfigDefault, HTTPMethods, RawReplyDefaultExpression, RawRequestDefaultExpression, RawServerBase, RawServerDefault } from './utils'
25
26export interface PrintRoutesOptions {
27 method?: HTTPMethods;
28 includeMeta?: boolean | (string | symbol)[]
29 commonPrefix?: boolean
30 includeHooks?: boolean
31}
32
33type AsyncFunction = (...args: any) => Promise<any>;
34
35export interface FastifyListenOptions {
36 /**
37 * Default to `0` (picks the first available open port).
38 */
39 port?: number;
40 /**
41 * Default to `localhost`.
42 */
43 host?: string;
44 /**
45 * Will be ignored if `port` is specified.
46 * @see [Identifying paths for IPC connections](https://nodejs.org/api/net.html#identifying-paths-for-ipc-connections).
47 */
48 path?: string;
49 /**
50 * Specify the maximum length of the queue of pending connections.
51 * The actual length will be determined by the OS through sysctl settings such as `tcp_max_syn_backlog` and `somaxconn` on Linux.
52 * Default to `511`.
53 */
54 backlog?: number;
55 /**
56 * Default to `false`.
57 */
58 exclusive?: boolean;
59 /**
60 * For IPC servers makes the pipe readable for all users.
61 * Default to `false`.
62 */
63 readableAll?: boolean;
64 /**
65 * For IPC servers makes the pipe writable for all users.
66 * Default to `false`.
67 */
68 writableAll?: boolean;
69 /**
70 * For TCP servers, setting `ipv6Only` to `true` will disable dual-stack support, i.e., binding to host `::` won't make `0.0.0.0` be bound.
71 * Default to `false`.
72 */
73 ipv6Only?: boolean;
74 /**
75 * An AbortSignal that may be used to close a listening server.
76 * @since This option is available only in Node.js v15.6.0 and greater
77 */
78 signal?: AbortSignal;
79
80 /**
81 * Function that resolves text to log after server has been successfully started
82 * @param address
83 */
84 listenTextResolver?: (address: string) => string;
85}
86
87type NotInInterface<Key, _Interface> = Key extends keyof _Interface ? never : Key
88type FindMyWayVersion<RawServer extends RawServerBase> = RawServer extends http.Server ? HTTPVersion.V1 : HTTPVersion.V2
89type FindMyWayFindResult<RawServer extends RawServerBase> = FindResult<FindMyWayVersion<RawServer>>
90
91type GetterSetter<This, T> = T | {
92 getter: (this: This) => T,
93 setter?: (this: This, value: T) => void
94}
95
96type DecorationMethod<This, Return = This> = {
97 <
98 // Need to disable "no-use-before-define" to maintain backwards compatibility, as else decorate<Foo> would suddenly mean something new
99 // eslint-disable-next-line no-use-before-define
100 T extends (P extends keyof This ? This[P] : unknown),
101 P extends string | symbol = string | symbol
102 >(property: P,
103 value: GetterSetter<This, T extends (...args: any[]) => any
104 ? (this: This, ...args: Parameters<T>) => ReturnType<T>
105 : T
106 >,
107 dependencies?: string[]
108 ): Return;
109
110 (property: string | symbol): Return;
111
112 (property: string | symbol, value: null): Return;
113
114 (property: string | symbol, value: null|undefined, dependencies: string[]): Return;
115}
116
117/**
118 * Fastify server instance. Returned by the core `fastify()` method.
119 */
120export interface FastifyInstance<
121 RawServer extends RawServerBase = RawServerDefault,
122 RawRequest extends RawRequestDefaultExpression<RawServer> = RawRequestDefaultExpression<RawServer>,
123 RawReply extends RawReplyDefaultExpression<RawServer> = RawReplyDefaultExpression<RawServer>,
124 Logger extends FastifyBaseLogger = FastifyBaseLogger,
125 TypeProvider extends FastifyTypeProvider = FastifyTypeProviderDefault,
126> {
127 server: RawServer;
128 pluginName: string;
129 prefix: string;
130 version: string;
131 log: Logger;
132 listeningOrigin: string;
133 addresses(): AddressInfo[]
134 withTypeProvider<Provider extends FastifyTypeProvider>(): FastifyInstance<RawServer, RawRequest, RawReply, Logger, Provider>;
135
136 addSchema(schema: unknown): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;
137 getSchema(schemaId: string): unknown;
138 getSchemas(): Record<string, unknown>;
139
140 after(): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider> & PromiseLike<undefined>;
141 after(afterListener: (err: Error | null) => void): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;
142
143 close(): Promise<undefined>;
144 close(closeListener: () => void): undefined;
145
146 /** Alias for {@linkcode FastifyInstance.close()} */
147 // eslint-disable-next-line @typescript-eslint/ban-ts-comment
148 // @ts-ignore - type only available for @types/node >=17 or typescript >= 5.2
149 [Symbol.asyncDispose](): Promise<undefined>;
150
151 // should be able to define something useful with the decorator getter/setter pattern using Generics to enforce the users function returns what they expect it to
152 decorate: DecorationMethod<FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>>;
153 decorateRequest: DecorationMethod<FastifyRequest, FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>>;
154 decorateReply: DecorationMethod<FastifyReply, FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>>;
155
156 hasDecorator(decorator: string | symbol): boolean;
157 hasRequestDecorator(decorator: string | symbol): boolean;
158 hasReplyDecorator(decorator: string | symbol): boolean;
159 hasPlugin(name: string): boolean;
160
161 addConstraintStrategy(strategy: ConstraintStrategy<FindMyWayVersion<RawServer>, unknown>): void;
162 hasConstraintStrategy(strategyName: string): boolean;
163
164 inject(opts: InjectOptions | string, cb: LightMyRequestCallback): void;
165 inject(opts: InjectOptions | string): Promise<LightMyRequestResponse>;
166 inject(): LightMyRequestChain;
167
168 listen(opts: FastifyListenOptions, callback: (err: Error | null, address: string) => void): void;
169 listen(opts?: FastifyListenOptions): Promise<string>;
170 listen(callback: (err: Error | null, address: string) => void): void;
171
172 /**
173 * @deprecated Variadic listen method is deprecated. Please use `.listen(optionsObject, callback)` instead. The variadic signature will be removed in `fastify@5`
174 * @see https://github.com/fastify/fastify/pull/3712
175 */
176 listen(port: number | string, address: string, backlog: number, callback: (err: Error|null, address: string) => void): void;
177 /**
178 * @deprecated Variadic listen method is deprecated. Please use `.listen(optionsObject, callback)` instead. The variadic signature will be removed in `fastify@5`
179 * @see https://github.com/fastify/fastify/pull/3712
180 */
181 listen(port: number | string, address: string, callback: (err: Error|null, address: string) => void): void;
182 /**
183 * @deprecated Variadic listen method is deprecated. Please use `.listen(optionsObject, callback)` instead. The variadic signature will be removed in `fastify@5`
184 * @see https://github.com/fastify/fastify/pull/3712
185 */
186 listen(port: number | string, callback: (err: Error|null, address: string) => void): void;
187 /**
188 * @deprecated Variadic listen method is deprecated. Please use `.listen(optionsObject)` instead. The variadic signature will be removed in `fastify@5`
189 * @see https://github.com/fastify/fastify/pull/3712
190 */
191 listen(port: number | string, address?: string, backlog?: number): Promise<string>;
192
193 ready(): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider> & PromiseLike<undefined>;
194 ready(readyListener: (err: Error | null) => void): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;
195
196 register: FastifyRegister<FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider> & PromiseLike<undefined>>;
197
198 routing(req: RawRequest, res: RawReply): void;
199 getDefaultRoute(): DefaultRoute<RawRequest, RawReply>;
200 setDefaultRoute(defaultRoute: DefaultRoute<RawRequest, RawReply>): void;
201
202 route<
203 RouteGeneric extends RouteGenericInterface = RouteGenericInterface,
204 ContextConfig = ContextConfigDefault,
205 const SchemaCompiler extends FastifySchema = FastifySchema,
206 >(opts: RouteOptions<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger>): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;
207
208 get: RouteShorthandMethod<RawServer, RawRequest, RawReply, TypeProvider, Logger>;
209 head: RouteShorthandMethod<RawServer, RawRequest, RawReply, TypeProvider, Logger>;
210 post: RouteShorthandMethod<RawServer, RawRequest, RawReply, TypeProvider, Logger>;
211 put: RouteShorthandMethod<RawServer, RawRequest, RawReply, TypeProvider, Logger>;
212 delete: RouteShorthandMethod<RawServer, RawRequest, RawReply, TypeProvider, Logger>;
213 options: RouteShorthandMethod<RawServer, RawRequest, RawReply, TypeProvider, Logger>;
214 patch: RouteShorthandMethod<RawServer, RawRequest, RawReply, TypeProvider, Logger>;
215 all: RouteShorthandMethod<RawServer, RawRequest, RawReply, TypeProvider, Logger>;
216
217 hasRoute<
218 RouteGeneric extends RouteGenericInterface = RouteGenericInterface,
219 ContextConfig = ContextConfigDefault,
220 SchemaCompiler extends FastifySchema = FastifySchema,
221 >(opts: Pick<RouteOptions<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider>, 'method' | 'url' | 'constraints'>): boolean;
222
223 findRoute<
224 RouteGeneric extends RouteGenericInterface = RouteGenericInterface,
225 ContextConfig = ContextConfigDefault,
226 SchemaCompiler extends FastifySchema = FastifySchema,
227 >(opts: Pick<RouteOptions<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider>, 'method' | 'url' | 'constraints'>): Omit<FindMyWayFindResult<RawServer>, 'store'>;
228
229 // addHook: overloads
230
231 // Lifecycle addHooks
232
233 /**
234 * `onRequest` is the first hook to be executed in the request lifecycle. There was no previous hook, the next hook will be `preParsing`.
235 * Notice: in the `onRequest` hook, request.body will always be null, because the body parsing happens before the `preHandler` hook.
236 */
237 addHook<
238 RouteGeneric extends RouteGenericInterface = RouteGenericInterface,
239 ContextConfig = ContextConfigDefault,
240 SchemaCompiler extends FastifySchema = FastifySchema,
241 Logger extends FastifyBaseLogger = FastifyBaseLogger,
242 Fn extends onRequestHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger> | onRequestAsyncHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger> = onRequestHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger>
243 >(
244 name: 'onRequest',
245 hook: Fn extends unknown ? Fn extends AsyncFunction ? onRequestAsyncHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger> : onRequestHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger> : Fn,
246 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;
247
248 /**
249 * `preParsing` is the second hook to be executed in the request lifecycle. The previous hook was `onRequest`, the next hook will be `preValidation`.
250 * Notice: in the `preParsing` hook, request.body will always be null, because the body parsing happens before the `preHandler` hook.
251 */
252 addHook<
253 RouteGeneric extends RouteGenericInterface = RouteGenericInterface,
254 ContextConfig = ContextConfigDefault,
255 SchemaCompiler extends FastifySchema = FastifySchema,
256 Logger extends FastifyBaseLogger = FastifyBaseLogger,
257 Fn extends preParsingHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger> | preParsingAsyncHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger> = preParsingHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger>
258 >(
259 name: 'preParsing',
260 hook: Fn extends unknown ? Fn extends AsyncFunction ? preParsingAsyncHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger> : preParsingHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger> : Fn,
261 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;
262
263 /**
264 * `preValidation` is the third hook to be executed in the request lifecycle. The previous hook was `preParsing`, the next hook will be `preHandler`.
265 */
266 addHook<
267 RouteGeneric extends RouteGenericInterface = RouteGenericInterface,
268 ContextConfig = ContextConfigDefault,
269 SchemaCompiler extends FastifySchema = FastifySchema,
270 Logger extends FastifyBaseLogger = FastifyBaseLogger,
271 Fn extends preValidationHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger> | preValidationAsyncHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger> = preValidationHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger>
272 >(
273 name: 'preValidation',
274 hook: Fn extends unknown ? Fn extends AsyncFunction ? preValidationAsyncHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger> : preValidationHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger> : Fn,
275 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;
276
277 /**
278 * `preHandler` is the fourth hook to be executed in the request lifecycle. The previous hook was `preValidation`, the next hook will be `preSerialization`.
279 */
280 addHook<
281 RouteGeneric extends RouteGenericInterface = RouteGenericInterface,
282 ContextConfig = ContextConfigDefault,
283 SchemaCompiler extends FastifySchema = FastifySchema,
284 Logger extends FastifyBaseLogger = FastifyBaseLogger,
285 Fn extends preHandlerHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger> | preHandlerAsyncHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger> = preHandlerHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger>
286 >(
287 name: 'preHandler',
288 hook: Fn extends unknown ? Fn extends AsyncFunction ? preHandlerAsyncHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger> : preHandlerHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger> : Fn,
289 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;
290
291 /**
292 * `preSerialization` is the fifth hook to be executed in the request lifecycle. The previous hook was `preHandler`, the next hook will be `onSend`.
293 * Note: the hook is NOT called if the payload is a string, a Buffer, a stream or null.
294 */
295 addHook<
296 PreSerializationPayload = unknown,
297 RouteGeneric extends RouteGenericInterface = RouteGenericInterface,
298 ContextConfig = ContextConfigDefault,
299 SchemaCompiler extends FastifySchema = FastifySchema,
300 Logger extends FastifyBaseLogger = FastifyBaseLogger,
301 Fn extends preSerializationHookHandler<PreSerializationPayload, RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger> | preSerializationAsyncHookHandler<PreSerializationPayload, RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger> = preSerializationHookHandler<PreSerializationPayload, RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger>
302 >(
303 name: 'preSerialization',
304 hook: Fn extends unknown ? Fn extends AsyncFunction ? preSerializationAsyncHookHandler<PreSerializationPayload, RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger> : preSerializationHookHandler<PreSerializationPayload, RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger> : Fn,
305 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;
306
307 /**
308 * You can change the payload with the `onSend` hook. It is the sixth hook to be executed in the request lifecycle. The previous hook was `preSerialization`, the next hook will be `onResponse`.
309 * Note: If you change the payload, you may only change it to a string, a Buffer, a stream, or null.
310 */
311 addHook<
312 OnSendPayload = unknown,
313 RouteGeneric extends RouteGenericInterface = RouteGenericInterface,
314 ContextConfig = ContextConfigDefault,
315 SchemaCompiler extends FastifySchema = FastifySchema,
316 Logger extends FastifyBaseLogger = FastifyBaseLogger,
317 Fn extends onSendHookHandler<OnSendPayload, RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger> | onSendAsyncHookHandler<OnSendPayload, RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger> = onSendHookHandler<OnSendPayload, RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger>
318 >(
319 name: 'onSend',
320 hook: Fn extends unknown ? Fn extends AsyncFunction ? onSendAsyncHookHandler<OnSendPayload, RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger> : onSendHookHandler<OnSendPayload, RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger> : Fn,
321 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;
322
323 /**
324 * `onResponse` is the seventh and last hook in the request hook lifecycle. The previous hook was `onSend`, there is no next hook.
325 * The onResponse hook is executed when a response has been sent, so you will not be able to send more data to the client. It can however be useful for sending data to external services, for example to gather statistics.
326 */
327 addHook<
328 RouteGeneric extends RouteGenericInterface = RouteGenericInterface,
329 ContextConfig = ContextConfigDefault,
330 SchemaCompiler extends FastifySchema = FastifySchema,
331 Logger extends FastifyBaseLogger = FastifyBaseLogger,
332 Fn extends onResponseHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger> | onResponseAsyncHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger> = onResponseHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger>
333 >(
334 name: 'onResponse',
335 hook: Fn extends unknown ? Fn extends AsyncFunction ? onResponseAsyncHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger> : onResponseHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger> : Fn,
336 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;
337
338 /**
339 * `onTimeout` is useful if you need to monitor the request timed out in your service. (if the `connectionTimeout` property is set on the fastify instance)
340 * The onTimeout hook is executed when a request is timed out and the http socket has been hanged up. Therefore you will not be able to send data to the client.
341 */
342 addHook<
343 RouteGeneric extends RouteGenericInterface = RouteGenericInterface,
344 ContextConfig = ContextConfigDefault,
345 SchemaCompiler extends FastifySchema = FastifySchema,
346 Logger extends FastifyBaseLogger = FastifyBaseLogger,
347 Fn extends onTimeoutHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger> | onTimeoutAsyncHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger> = onTimeoutHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger>
348 >(
349 name: 'onTimeout',
350 hook: Fn extends unknown ? Fn extends AsyncFunction ? onTimeoutAsyncHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger> : onTimeoutHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger> : Fn,
351 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;
352
353 /**
354 * `onRequestAbort` is useful if you need to monitor the if the client aborts the request (if the `request.raw.aborted` property is set to `true`).
355 * The `onRequestAbort` hook is executed when a client closes the connection before the entire request has been received. Therefore, you will not be able to send data to the client.
356 * Notice: client abort detection is not completely reliable. See: https://github.com/fastify/fastify/blob/main/docs/Guides/Detecting-When-Clients-Abort.md
357 */
358 addHook<
359 RouteGeneric extends RouteGenericInterface = RouteGenericInterface,
360 ContextConfig = ContextConfigDefault,
361 SchemaCompiler extends FastifySchema = FastifySchema,
362 Logger extends FastifyBaseLogger = FastifyBaseLogger,
363 Fn extends onRequestAbortHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger> | onRequestAbortAsyncHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger> = onRequestAbortHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger>
364 >(
365 name: 'onRequestAbort',
366 hook: Fn extends unknown ? Fn extends AsyncFunction ? onRequestAbortAsyncHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger> : onRequestAbortHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger> : Fn,
367 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;
368
369 /**
370 * This hook is useful if you need to do some custom error logging or add some specific header in case of error.
371 * It is not intended for changing the error, and calling reply.send will throw an exception.
372 * This hook will be executed only after the customErrorHandler has been executed, and only if the customErrorHandler sends an error back to the user (Note that the default customErrorHandler always sends the error back to the user).
373 * Notice: unlike the other hooks, pass an error to the done function is not supported.
374 */
375 addHook<
376 RouteGeneric extends RouteGenericInterface = RouteGenericInterface,
377 ContextConfig = ContextConfigDefault,
378 SchemaCompiler extends FastifySchema = FastifySchema,
379 Logger extends FastifyBaseLogger = FastifyBaseLogger,
380 Fn extends onErrorHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, FastifyError, SchemaCompiler, TypeProvider, Logger> | onErrorAsyncHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, FastifyError, SchemaCompiler, TypeProvider, Logger> = onErrorHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, FastifyError, SchemaCompiler, TypeProvider, Logger>
381 >(
382 name: 'onError',
383 hook: Fn extends unknown ? Fn extends AsyncFunction ? onErrorAsyncHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, FastifyError, SchemaCompiler, TypeProvider, Logger> : onErrorHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, FastifyError, SchemaCompiler, TypeProvider, Logger> : Fn,
384 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;
385
386 // Application addHooks
387
388 /**
389 * Triggered when a new route is registered. Listeners are passed a routeOptions object as the sole parameter. The interface is synchronous, and, as such, the listener does not get passed a callback
390 */
391 addHook<
392 RouteGeneric extends RouteGenericInterface = RouteGenericInterface,
393 ContextConfig = ContextConfigDefault,
394 SchemaCompiler extends FastifySchema = FastifySchema,
395 Logger extends FastifyBaseLogger = FastifyBaseLogger
396 >(
397 name: 'onRoute',
398 hook: onRouteHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger>
399 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;
400
401 /**
402 * Triggered when a new plugin is registered and a new encapsulation context is created. The hook will be executed before the registered code.
403 * This hook can be useful if you are developing a plugin that needs to know when a plugin context is formed, and you want to operate in that specific context.
404 * Note: This hook will not be called if a plugin is wrapped inside fastify-plugin.
405 */
406 addHook(
407 name: 'onRegister',
408 hook: onRegisterHookHandler<RawServer, RawRequest, RawReply, Logger, TypeProvider>
409 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;
410
411 /**
412 * Triggered when fastify.listen() or fastify.ready() is invoked to start the server. It is useful when plugins need a "ready" event, for example to load data before the server start listening for requests.
413 */
414 addHook<
415 Fn extends onReadyHookHandler | onReadyAsyncHookHandler = onReadyHookHandler
416 >(
417 name: 'onReady',
418 hook: Fn extends unknown ? Fn extends AsyncFunction ? onReadyAsyncHookHandler : onReadyHookHandler : Fn,
419 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;
420
421 /**
422 * Triggered when fastify.listen() is invoked to start the server. It is useful when plugins need a "onListen" event, for example to run logics after the server start listening for requests.
423 */
424 addHook<
425 Fn extends onListenHookHandler<RawServer, RawRequest, RawReply, Logger, TypeProvider> | onListenAsyncHookHandler<RawServer, RawRequest, RawReply, Logger, TypeProvider> = onListenHookHandler<RawServer, RawRequest, RawReply, Logger, TypeProvider>
426 >(
427 name: 'onListen',
428 hook: Fn extends unknown ? Fn extends AsyncFunction ? onListenAsyncHookHandler : onListenHookHandler : Fn,
429 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;
430
431 /**
432 * Triggered when fastify.close() is invoked to stop the server. It is useful when plugins need a "shutdown" event, for example to close an open connection to a database.
433 */
434 addHook<
435 Fn extends onCloseHookHandler | onCloseAsyncHookHandler = onCloseHookHandler
436 >(
437 name: 'onClose',
438 hook: Fn extends unknown ? Fn extends AsyncFunction ? onCloseAsyncHookHandler : onCloseHookHandler : Fn,
439 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;
440
441 /**
442 * Triggered when fastify.close() is invoked to stop the server. It is useful when plugins need to cancel some state to allow the server to close successfully.
443 */
444 addHook<
445 Fn extends preCloseHookHandler | preCloseAsyncHookHandler = preCloseHookHandler
446 >(
447 name: 'preClose',
448 hook: Fn extends unknown ? Fn extends AsyncFunction ? preCloseAsyncHookHandler : preCloseHookHandler : Fn,
449 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;
450
451 addHook<
452 K extends ApplicationHook | LifecycleHook,
453 Fn extends (...args: any) => Promise<any> | any
454 > (
455 name: K,
456 hook: Fn extends unknown ? Fn extends AsyncFunction ? HookAsyncLookup<K> : HookLookup<K> : Fn
457 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;
458
459 /**
460 * Set the 404 handler
461 */
462 setNotFoundHandler<RouteGeneric extends RouteGenericInterface = RouteGenericInterface, ContextConfig extends ContextConfigDefault = ContextConfigDefault, TypeProvider extends FastifyTypeProvider = FastifyTypeProviderDefault, SchemaCompiler extends FastifySchema = FastifySchema> (
463 handler: RouteHandlerMethod<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger>
464 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;
465
466 setNotFoundHandler<RouteGeneric extends RouteGenericInterface = RouteGenericInterface, ContextConfig extends ContextConfigDefault = ContextConfigDefault, TypeProvider extends FastifyTypeProvider = FastifyTypeProviderDefault, SchemaCompiler extends FastifySchema = FastifySchema> (
467 opts: {
468 preValidation?: preValidationHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider> | preValidationAsyncHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider> | preValidationHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider>[] | preValidationAsyncHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider>[];
469 preHandler?: preHandlerHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider> | preHandlerAsyncHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider> | preHandlerHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider>[] | preHandlerAsyncHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider>[];
470 },
471 handler: RouteHandlerMethod<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger>
472 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>
473
474 /**
475 * Fastify default error handler
476 */
477 errorHandler: (error: FastifyError, request: FastifyRequest, reply: FastifyReply) => void;
478
479 /**
480 * Set a function that will be called whenever an error happens
481 */
482 setErrorHandler<TError extends Error = FastifyError, RouteGeneric extends RouteGenericInterface = RouteGenericInterface, SchemaCompiler extends FastifySchema = FastifySchema, TypeProvider extends FastifyTypeProvider = FastifyTypeProviderDefault>(
483 handler: (this: FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>, error: TError, request: FastifyRequest<RouteGeneric, RawServer, RawRequest, SchemaCompiler, TypeProvider>, reply: FastifyReply<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfigDefault, SchemaCompiler, TypeProvider>) => any | Promise<any>
484 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;
485
486 /**
487 * Set a function that will generate a request-ids
488 */
489 setGenReqId(fn: (req: RawRequestDefaultExpression<RawServer>) => string): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;
490
491 /**
492 * Hook function that is called when creating a child logger instance for each request
493 * which allows for modifying or adding child logger bindings and logger options, or
494 * returning a completely custom child logger implementation.
495 */
496 childLoggerFactory: FastifyChildLoggerFactory<RawServer, RawRequest, RawReply, Logger, TypeProvider>;
497
498 /**
499 * Hook function that is called when creating a child logger instance for each request
500 * which allows for modifying or adding child logger bindings and logger options, or
501 * returning a completely custom child logger implementation.
502 *
503 * Child logger bindings have a performance advantage over per-log bindings, because
504 * they are pre-serialised by Pino when the child logger is created.
505 *
506 * For example:
507 * ```
508 * function childLoggerFactory(logger, bindings, opts, rawReq) {
509 * // Calculate additional bindings from the request
510 * bindings.traceContext = rawReq.headers['x-cloud-trace-context']
511 * return logger.child(bindings, opts);
512 * }
513 * ```
514 */
515 setChildLoggerFactory(factory: FastifyChildLoggerFactory<RawServer, RawRequest, RawReply, Logger, TypeProvider>): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;
516
517 /**
518 * Fastify schema validator for all routes.
519 */
520 validatorCompiler: FastifySchemaCompiler<any> | undefined;
521
522 /**
523 * Set the schema validator for all routes.
524 */
525 setValidatorCompiler<T = FastifySchema>(schemaCompiler: FastifySchemaCompiler<T>): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;
526
527 /**
528 * Fastify schema serializer for all routes.
529 */
530 serializerCompiler: FastifySerializerCompiler<any> | undefined;
531
532 /**
533 * Set the schema serializer for all routes.
534 */
535 setSerializerCompiler<T = FastifySchema>(schemaCompiler: FastifySerializerCompiler<T>): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;
536
537 /**
538 * Set the schema controller for all routes.
539 */
540 setSchemaController(schemaControllerOpts: FastifySchemaControllerOptions): FastifyInstance<RawServer, RawRequest, RawReply, Logger>;
541
542 /**
543 * Set the reply serializer for all routes.
544 */
545 setReplySerializer(replySerializer: (payload: unknown, statusCode: number) => string): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;
546
547 /*
548 * Set the schema error formatter for all routes.
549 */
550 setSchemaErrorFormatter(errorFormatter: SchemaErrorFormatter): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;
551 /**
552 * Add a content type parser
553 */
554 addContentTypeParser: AddContentTypeParser<RawServer, RawRequest, RouteGenericInterface, FastifySchema, TypeProvider>;
555 hasContentTypeParser: hasContentTypeParser;
556 /**
557 * Remove an existing content type parser
558 */
559 removeContentTypeParser: removeContentTypeParser
560 /**
561 * Remove all content type parsers, including the default ones
562 */
563 removeAllContentTypeParsers: removeAllContentTypeParsers
564 /**
565 * Fastify default JSON parser
566 */
567 getDefaultJsonParser: getDefaultJsonParser;
568 /**
569 * Fastify default plain text parser
570 */
571 defaultTextParser: FastifyBodyParser<string>;
572
573 /**
574 * Prints the representation of the internal radix tree used by the router
575 */
576 printRoutes(opts?: PrintRoutesOptions): string;
577
578 /**
579 * Prints the representation of the plugin tree used by avvio, the plugin registration system
580 */
581 printPlugins(): string;
582
583 /**
584 * Frozen read-only object registering the initial options passed down by the user to the fastify instance
585 */
586 initialConfig: Readonly<{
587 connectionTimeout?: number,
588 keepAliveTimeout?: number,
589 forceCloseConnections?: boolean,
590 bodyLimit?: number,
591 caseSensitive?: boolean,
592 allowUnsafeRegex?: boolean,
593 http2?: boolean,
594 https?: boolean | Readonly<{ allowHTTP1: boolean }>,
595 ignoreTrailingSlash?: boolean,
596 ignoreDuplicateSlashes?: boolean,
597 disableRequestLogging?: boolean,
598 maxParamLength?: number,
599 onProtoPoisoning?: ProtoAction,
600 onConstructorPoisoning?: ConstructorAction,
601 pluginTimeout?: number,
602 requestIdHeader?: string | false,
603 requestIdLogLabel?: string,
604 http2SessionTimeout?: number,
605 useSemicolonDelimiter?: boolean,
606 }>
607}