strong-tie/inbound-calls
0
1import { FastifyError } from '@fastify/error'2import { ConstraintStrategy, FindResult, HTTPVersion } from 'find-my-way'3import * as http from 'node:http'4import { InjectOptions, CallbackFunc as LightMyRequestCallback, Chain as LightMyRequestChain, Response as LightMyRequestResponse } from 'light-my-request'5import { AddressInfo } from 'node: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 { RouteGenericInterface, RouteHandlerMethod, RouteOptions, RouteShorthandMethod } from './route'13import {14 FastifySchema,15 FastifySchemaCompiler,16 FastifySchemaControllerOptions,17 FastifySerializerCompiler,18 SchemaErrorFormatter19} from './schema'20import {21 FastifyTypeProvider,22 FastifyTypeProviderDefault,23 SafePromiseLike24} from './type-provider'25import { ContextConfigDefault, HTTPMethods, RawReplyDefaultExpression, RawRequestDefaultExpression, RawServerBase, RawServerDefault } from './utils'26 27export interface PrintRoutesOptions {28 method?: HTTPMethods;29 includeMeta?: boolean | (string | symbol)[]30 commonPrefix?: boolean31 includeHooks?: boolean32}33 34type AsyncFunction = (...args: any) => Promise<any>35 36export interface FastifyListenOptions {37 /**38 * Default to `0` (picks the first available open port).39 */40 port?: number;41 /**42 * Default to `localhost`.43 */44 host?: string;45 /**46 * Will be ignored if `port` is specified.47 * @see [Identifying paths for IPC connections](https://nodejs.org/api/net.html#identifying-paths-for-ipc-connections).48 */49 path?: string;50 /**51 * Specify the maximum length of the queue of pending connections.52 * The actual length will be determined by the OS through sysctl settings such as `tcp_max_syn_backlog` and `somaxconn` on Linux.53 * Default to `511`.54 */55 backlog?: number;56 /**57 * Default to `false`.58 */59 exclusive?: boolean;60 /**61 * For IPC servers makes the pipe readable for all users.62 * Default to `false`.63 */64 readableAll?: boolean;65 /**66 * For IPC servers makes the pipe writable for all users.67 * Default to `false`.68 */69 writableAll?: boolean;70 /**71 * 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.72 * Default to `false`.73 */74 ipv6Only?: boolean;75 /**76 * An AbortSignal that may be used to close a listening server.77 * @since This option is available only in Node.js v15.6.0 and greater78 */79 signal?: AbortSignal;80 81 /**82 * Function that resolves text to log after server has been successfully started83 * @param address84 */85 listenTextResolver?: (address: string) => string;86}87 88type NotInInterface<Key, _Interface> = Key extends keyof _Interface ? never : Key89type FindMyWayVersion<RawServer extends RawServerBase> = RawServer extends http.Server ? HTTPVersion.V1 : HTTPVersion.V290type FindMyWayFindResult<RawServer extends RawServerBase> = FindResult<FindMyWayVersion<RawServer>>91 92type GetterSetter<This, T> = T | {93 getter: (this: This) => T,94 setter?: (this: This, value: T) => void95}96 97type DecorationMethod<This, Return = This> = {98 <99 // Need to disable "no-use-before-define" to maintain backwards compatibility, as else decorate<Foo> would suddenly mean something new100 101 T extends (P extends keyof This ? This[P] : unknown),102 P extends string | symbol = string | symbol103 >(property: P,104 value: GetterSetter<This, T extends (...args: any[]) => any105 ? (this: This, ...args: Parameters<T>) => ReturnType<T>106 : T107 >,108 dependencies?: string[]109 ): Return;110 111 (property: string | symbol): Return;112 113 (property: string | symbol, value: null | undefined, dependencies: string[]): Return;114}115 116/**117 * Fastify server instance. Returned by the core `fastify()` method.118 */119export interface FastifyInstance<120 RawServer extends RawServerBase = RawServerDefault,121 RawRequest extends RawRequestDefaultExpression<RawServer> = RawRequestDefaultExpression<RawServer>,122 RawReply extends RawReplyDefaultExpression<RawServer> = RawReplyDefaultExpression<RawServer>,123 Logger extends FastifyBaseLogger = FastifyBaseLogger,124 TypeProvider extends FastifyTypeProvider = FastifyTypeProviderDefault125> {126 server: RawServer;127 pluginName: string;128 prefix: string;129 version: string;130 log: Logger;131 listeningOrigin: string;132 addresses(): AddressInfo[]133 withTypeProvider<Provider extends FastifyTypeProvider>(): FastifyInstance<RawServer, RawRequest, RawReply, Logger, Provider>;134 135 addSchema(schema: unknown): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;136 getSchema(schemaId: string): unknown;137 getSchemas(): Record<string, unknown>;138 139 after(): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider> & SafePromiseLike<undefined>;140 after(afterListener: (err: Error | null) => void): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;141 142 close(): Promise<undefined>;143 close(closeListener: () => void): undefined;144 145 /** Alias for {@linkcode FastifyInstance.close()} */146 147 // @ts-ignore - type only available for @types/node >=17 or typescript >= 5.2148 [Symbol.asyncDispose](): Promise<undefined>;149 150 // 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 to151 decorate: DecorationMethod<FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>>;152 decorateRequest: DecorationMethod<FastifyRequest, FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>>;153 decorateReply: DecorationMethod<FastifyReply, FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>>;154 155 hasDecorator(decorator: string | symbol): boolean;156 hasRequestDecorator(decorator: string | symbol): boolean;157 hasReplyDecorator(decorator: string | symbol): boolean;158 hasPlugin(name: string): boolean;159 160 addConstraintStrategy(strategy: ConstraintStrategy<FindMyWayVersion<RawServer>, unknown>): void;161 hasConstraintStrategy(strategyName: string): boolean;162 163 inject(opts: InjectOptions | string, cb: LightMyRequestCallback): void;164 inject(opts: InjectOptions | string): Promise<LightMyRequestResponse>;165 inject(): LightMyRequestChain;166 167 listen(opts: FastifyListenOptions, callback: (err: Error | null, address: string) => void): void;168 listen(opts?: FastifyListenOptions): Promise<string>;169 listen(callback: (err: Error | null, address: string) => void): void;170 171 ready(): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider> & SafePromiseLike<undefined>;172 ready(readyListener: (err: Error | null) => void | Promise<void>): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;173 174 register: FastifyRegister<FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider> & SafePromiseLike<undefined>>;175 176 routing(req: RawRequest, res: RawReply): void;177 178 route<179 RouteGeneric extends RouteGenericInterface = RouteGenericInterface,180 ContextConfig = ContextConfigDefault,181 const SchemaCompiler extends FastifySchema = FastifySchema182 >(opts: RouteOptions<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger>): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;183 184 delete: RouteShorthandMethod<RawServer, RawRequest, RawReply, TypeProvider, Logger>;185 get: RouteShorthandMethod<RawServer, RawRequest, RawReply, TypeProvider, Logger>;186 head: RouteShorthandMethod<RawServer, RawRequest, RawReply, TypeProvider, Logger>;187 patch: RouteShorthandMethod<RawServer, RawRequest, RawReply, TypeProvider, Logger>;188 post: RouteShorthandMethod<RawServer, RawRequest, RawReply, TypeProvider, Logger>;189 put: RouteShorthandMethod<RawServer, RawRequest, RawReply, TypeProvider, Logger>;190 options: RouteShorthandMethod<RawServer, RawRequest, RawReply, TypeProvider, Logger>;191 propfind: RouteShorthandMethod<RawServer, RawRequest, RawReply, TypeProvider, Logger>;192 proppatch: RouteShorthandMethod<RawServer, RawRequest, RawReply, TypeProvider, Logger>;193 mkcalendar: RouteShorthandMethod<RawServer, RawRequest, RawReply, TypeProvider, Logger>;194 mkcol: RouteShorthandMethod<RawServer, RawRequest, RawReply, TypeProvider, Logger>;195 copy: RouteShorthandMethod<RawServer, RawRequest, RawReply, TypeProvider, Logger>;196 move: RouteShorthandMethod<RawServer, RawRequest, RawReply, TypeProvider, Logger>;197 lock: RouteShorthandMethod<RawServer, RawRequest, RawReply, TypeProvider, Logger>;198 unlock: RouteShorthandMethod<RawServer, RawRequest, RawReply, TypeProvider, Logger>;199 trace: RouteShorthandMethod<RawServer, RawRequest, RawReply, TypeProvider, Logger>;200 report: RouteShorthandMethod<RawServer, RawRequest, RawReply, TypeProvider, Logger>;201 search: RouteShorthandMethod<RawServer, RawRequest, RawReply, TypeProvider, Logger>;202 all: RouteShorthandMethod<RawServer, RawRequest, RawReply, TypeProvider, Logger>;203 204 hasRoute<205 RouteGeneric extends RouteGenericInterface = RouteGenericInterface,206 ContextConfig = ContextConfigDefault,207 SchemaCompiler extends FastifySchema = FastifySchema208 >(opts: Pick<RouteOptions<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider>, 'method' | 'url' | 'constraints'>): boolean;209 210 findRoute<211 RouteGeneric extends RouteGenericInterface = RouteGenericInterface,212 ContextConfig = ContextConfigDefault,213 SchemaCompiler extends FastifySchema = FastifySchema214 >(opts: Pick<RouteOptions<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider>, 'method' | 'url' | 'constraints'>): Omit<FindMyWayFindResult<RawServer>, 'store'>;215 216 // addHook: overloads217 218 // Lifecycle addHooks219 220 /**221 * `onRequest` is the first hook to be executed in the request lifecycle. There was no previous hook, the next hook will be `preParsing`.222 * Notice: in the `onRequest` hook, request.body will always be null, because the body parsing happens before the `preHandler` hook.223 */224 addHook<225 RouteGeneric extends RouteGenericInterface = RouteGenericInterface,226 ContextConfig = ContextConfigDefault,227 SchemaCompiler extends FastifySchema = FastifySchema,228 Logger extends FastifyBaseLogger = FastifyBaseLogger,229 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>230 >(231 name: 'onRequest',232 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,233 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;234 235 /**236 * `preParsing` is the second hook to be executed in the request lifecycle. The previous hook was `onRequest`, the next hook will be `preValidation`.237 * Notice: in the `preParsing` hook, request.body will always be null, because the body parsing happens before the `preHandler` hook.238 */239 addHook<240 RouteGeneric extends RouteGenericInterface = RouteGenericInterface,241 ContextConfig = ContextConfigDefault,242 SchemaCompiler extends FastifySchema = FastifySchema,243 Logger extends FastifyBaseLogger = FastifyBaseLogger,244 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>245 >(246 name: 'preParsing',247 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,248 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;249 250 /**251 * `preValidation` is the third hook to be executed in the request lifecycle. The previous hook was `preParsing`, the next hook will be `preHandler`.252 */253 addHook<254 RouteGeneric extends RouteGenericInterface = RouteGenericInterface,255 ContextConfig = ContextConfigDefault,256 SchemaCompiler extends FastifySchema = FastifySchema,257 Logger extends FastifyBaseLogger = FastifyBaseLogger,258 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>259 >(260 name: 'preValidation',261 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,262 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;263 264 /**265 * `preHandler` is the fourth hook to be executed in the request lifecycle. The previous hook was `preValidation`, the next hook will be `preSerialization`.266 */267 addHook<268 RouteGeneric extends RouteGenericInterface = RouteGenericInterface,269 ContextConfig = ContextConfigDefault,270 SchemaCompiler extends FastifySchema = FastifySchema,271 Logger extends FastifyBaseLogger = FastifyBaseLogger,272 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>273 >(274 name: 'preHandler',275 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,276 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;277 278 /**279 * `preSerialization` is the fifth hook to be executed in the request lifecycle. The previous hook was `preHandler`, the next hook will be `onSend`.280 * Note: the hook is NOT called if the payload is a string, a Buffer, a stream or null.281 */282 addHook<283 PreSerializationPayload = unknown,284 RouteGeneric extends RouteGenericInterface = RouteGenericInterface,285 ContextConfig = ContextConfigDefault,286 SchemaCompiler extends FastifySchema = FastifySchema,287 Logger extends FastifyBaseLogger = FastifyBaseLogger,288 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>289 >(290 name: 'preSerialization',291 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,292 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;293 294 /**295 * 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`.296 * Note: If you change the payload, you may only change it to a string, a Buffer, a stream, or null.297 */298 addHook<299 OnSendPayload = unknown,300 RouteGeneric extends RouteGenericInterface = RouteGenericInterface,301 ContextConfig = ContextConfigDefault,302 SchemaCompiler extends FastifySchema = FastifySchema,303 Logger extends FastifyBaseLogger = FastifyBaseLogger,304 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>305 >(306 name: 'onSend',307 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,308 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;309 310 /**311 * `onResponse` is the seventh and last hook in the request hook lifecycle. The previous hook was `onSend`, there is no next hook.312 * 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.313 */314 addHook<315 RouteGeneric extends RouteGenericInterface = RouteGenericInterface,316 ContextConfig = ContextConfigDefault,317 SchemaCompiler extends FastifySchema = FastifySchema,318 Logger extends FastifyBaseLogger = FastifyBaseLogger,319 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>320 >(321 name: 'onResponse',322 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,323 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;324 325 /**326 * `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)327 * 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.328 */329 addHook<330 RouteGeneric extends RouteGenericInterface = RouteGenericInterface,331 ContextConfig = ContextConfigDefault,332 SchemaCompiler extends FastifySchema = FastifySchema,333 Logger extends FastifyBaseLogger = FastifyBaseLogger,334 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>335 >(336 name: 'onTimeout',337 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,338 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;339 340 /**341 * `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`).342 * 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.343 * Notice: client abort detection is not completely reliable. See: https://github.com/fastify/fastify/blob/main/docs/Guides/Detecting-When-Clients-Abort.md344 */345 addHook<346 RouteGeneric extends RouteGenericInterface = RouteGenericInterface,347 ContextConfig = ContextConfigDefault,348 SchemaCompiler extends FastifySchema = FastifySchema,349 Logger extends FastifyBaseLogger = FastifyBaseLogger,350 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>351 >(352 name: 'onRequestAbort',353 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,354 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;355 356 /**357 * This hook is useful if you need to do some custom error logging or add some specific header in case of error.358 * It is not intended for changing the error, and calling reply.send will throw an exception.359 * 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).360 * Notice: unlike the other hooks, pass an error to the done function is not supported.361 */362 addHook<363 RouteGeneric extends RouteGenericInterface = RouteGenericInterface,364 ContextConfig = ContextConfigDefault,365 SchemaCompiler extends FastifySchema = FastifySchema,366 Logger extends FastifyBaseLogger = FastifyBaseLogger,367 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>368 >(369 name: 'onError',370 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,371 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;372 373 // Application addHooks374 375 /**376 * 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 callback377 */378 addHook<379 RouteGeneric extends RouteGenericInterface = RouteGenericInterface,380 ContextConfig = ContextConfigDefault,381 SchemaCompiler extends FastifySchema = FastifySchema,382 Logger extends FastifyBaseLogger = FastifyBaseLogger383 >(384 name: 'onRoute',385 hook: onRouteHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger>386 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;387 388 /**389 * Triggered when a new plugin is registered and a new encapsulation context is created. The hook will be executed before the registered code.390 * 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.391 * Note: This hook will not be called if a plugin is wrapped inside fastify-plugin.392 */393 addHook(394 name: 'onRegister',395 hook: onRegisterHookHandler<RawServer, RawRequest, RawReply, Logger, TypeProvider>396 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;397 398 /**399 * 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.400 */401 addHook<402 Fn extends onReadyHookHandler | onReadyAsyncHookHandler = onReadyHookHandler403 >(404 name: 'onReady',405 hook: Fn extends unknown ? Fn extends AsyncFunction ? onReadyAsyncHookHandler : onReadyHookHandler : Fn,406 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;407 408 /**409 * 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.410 */411 addHook<412 Fn extends onListenHookHandler<RawServer, RawRequest, RawReply, Logger, TypeProvider> | onListenAsyncHookHandler<RawServer, RawRequest, RawReply, Logger, TypeProvider> = onListenHookHandler<RawServer, RawRequest, RawReply, Logger, TypeProvider>413 >(414 name: 'onListen',415 hook: Fn extends unknown ? Fn extends AsyncFunction ? onListenAsyncHookHandler : onListenHookHandler : Fn,416 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;417 418 /**419 * 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.420 */421 addHook<422 Fn extends onCloseHookHandler | onCloseAsyncHookHandler = onCloseHookHandler423 >(424 name: 'onClose',425 hook: Fn extends unknown ? Fn extends AsyncFunction ? onCloseAsyncHookHandler : onCloseHookHandler : Fn,426 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;427 428 /**429 * 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.430 */431 addHook<432 Fn extends preCloseHookHandler | preCloseAsyncHookHandler = preCloseHookHandler433 >(434 name: 'preClose',435 hook: Fn extends unknown ? Fn extends AsyncFunction ? preCloseAsyncHookHandler : preCloseHookHandler : Fn,436 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;437 438 addHook<439 K extends ApplicationHook | LifecycleHook,440 Fn extends (...args: any) => Promise<any> | any441 > (442 name: K,443 hook: Fn extends unknown ? Fn extends AsyncFunction ? HookAsyncLookup<K> : HookLookup<K> : Fn444 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;445 446 /**447 * Set the 404 handler448 */449 setNotFoundHandler<RouteGeneric extends RouteGenericInterface = RouteGenericInterface, ContextConfig extends ContextConfigDefault = ContextConfigDefault, TypeProvider extends FastifyTypeProvider = FastifyTypeProviderDefault, SchemaCompiler extends FastifySchema = FastifySchema> (450 handler: RouteHandlerMethod<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger>451 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;452 453 setNotFoundHandler<RouteGeneric extends RouteGenericInterface = RouteGenericInterface, ContextConfig extends ContextConfigDefault = ContextConfigDefault, TypeProvider extends FastifyTypeProvider = FastifyTypeProviderDefault, SchemaCompiler extends FastifySchema = FastifySchema> (454 opts: {455 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>[];456 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>[];457 },458 handler: RouteHandlerMethod<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger>459 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>460 461 /**462 * Fastify default error handler463 */464 errorHandler: (error: FastifyError, request: FastifyRequest, reply: FastifyReply) => void;465 466 /**467 * Set a function that will be called whenever an error happens468 */469 setErrorHandler<TError extends Error = FastifyError, RouteGeneric extends RouteGenericInterface = RouteGenericInterface, SchemaCompiler extends FastifySchema = FastifySchema, TypeProvider extends FastifyTypeProvider = FastifyTypeProviderDefault>(470 handler: (this: FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>, error: TError, request: FastifyRequest<RouteGeneric, RawServer, RawRequest, SchemaCompiler, TypeProvider>, reply: FastifyReply<RouteGeneric, RawServer, RawRequest, RawReply, ContextConfigDefault, SchemaCompiler, TypeProvider>) => any | Promise<any>471 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;472 473 /**474 * Set a function that will generate a request-ids475 */476 setGenReqId(fn: (req: RawRequestDefaultExpression<RawServer>) => string): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;477 478 /**479 * Hook function that is called when creating a child logger instance for each request480 * which allows for modifying or adding child logger bindings and logger options, or481 * returning a completely custom child logger implementation.482 */483 childLoggerFactory: FastifyChildLoggerFactory<RawServer, RawRequest, RawReply, Logger, TypeProvider>;484 485 /**486 * Hook function that is called when creating a child logger instance for each request487 * which allows for modifying or adding child logger bindings and logger options, or488 * returning a completely custom child logger implementation.489 *490 * Child logger bindings have a performance advantage over per-log bindings, because491 * they are pre-serialised by Pino when the child logger is created.492 *493 * For example:494 * ```495 * function childLoggerFactory(logger, bindings, opts, rawReq) {496 * // Calculate additional bindings from the request497 * bindings.traceContext = rawReq.headers['x-cloud-trace-context']498 * return logger.child(bindings, opts);499 * }500 * ```501 */502 setChildLoggerFactory(factory: FastifyChildLoggerFactory<RawServer, RawRequest, RawReply, Logger, TypeProvider>): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;503 504 /**505 * Fastify schema validator for all routes.506 */507 validatorCompiler: FastifySchemaCompiler<any> | undefined;508 509 /**510 * Set the schema validator for all routes.511 */512 setValidatorCompiler<T = FastifySchema>(schemaCompiler: FastifySchemaCompiler<T>): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;513 514 /**515 * Fastify schema serializer for all routes.516 */517 serializerCompiler: FastifySerializerCompiler<any> | undefined;518 519 /**520 * Set the schema serializer for all routes.521 */522 setSerializerCompiler<T = FastifySchema>(schemaCompiler: FastifySerializerCompiler<T>): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;523 524 /**525 * Set the schema controller for all routes.526 */527 setSchemaController(schemaControllerOpts: FastifySchemaControllerOptions): FastifyInstance<RawServer, RawRequest, RawReply, Logger>;528 529 /**530 * Set the reply serializer for all routes.531 */532 setReplySerializer(replySerializer: (payload: unknown, statusCode: number) => string): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;533 534 /*535 * Set the schema error formatter for all routes.536 */537 setSchemaErrorFormatter(errorFormatter: SchemaErrorFormatter): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;538 /**539 * Add a content type parser540 */541 addContentTypeParser: AddContentTypeParser<RawServer, RawRequest, RouteGenericInterface, FastifySchema, TypeProvider>;542 hasContentTypeParser: hasContentTypeParser;543 /**544 * Remove an existing content type parser545 */546 removeContentTypeParser: removeContentTypeParser547 /**548 * Remove all content type parsers, including the default ones549 */550 removeAllContentTypeParsers: removeAllContentTypeParsers551 /**552 * Add a non-standard HTTP method553 *554 * Methods defined by default include `GET`, `HEAD`, `TRACE`, `DELETE`,555 * `OPTIONS`, `PATCH`, `PUT` and `POST`556 */557 addHttpMethod(method: string, methodOptions?: { hasBody: boolean }): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;558 /**559 * Fastify default JSON parser560 */561 getDefaultJsonParser: getDefaultJsonParser;562 /**563 * Fastify default plain text parser564 */565 defaultTextParser: FastifyBodyParser<string>;566 567 /**568 * Prints the representation of the internal radix tree used by the router569 */570 printRoutes(opts?: PrintRoutesOptions): string;571 572 /**573 * Prints the representation of the plugin tree used by avvio, the plugin registration system574 */575 printPlugins(): string;576 577 /**578 * Frozen read-only object registering the initial options passed down by the user to the fastify instance579 */580 initialConfig: Readonly<{581 connectionTimeout?: number,582 keepAliveTimeout?: number,583 forceCloseConnections?: boolean,584 bodyLimit?: number,585 caseSensitive?: boolean,586 allowUnsafeRegex?: boolean,587 http2?: boolean,588 https?: boolean | Readonly<{ allowHTTP1: boolean }>,589 ignoreTrailingSlash?: boolean,590 ignoreDuplicateSlashes?: boolean,591 disableRequestLogging?: boolean,592 maxParamLength?: number,593 onProtoPoisoning?: ProtoAction,594 onConstructorPoisoning?: ConstructorAction,595 pluginTimeout?: number,596 requestIdHeader?: string | false,597 requestIdLogLabel?: string,598 http2SessionTimeout?: number,599 useSemicolonDelimiter?: boolean,600 }>601}602 