UNPKG

14.4 kBTypeScriptView Raw
1import { Chain as LightMyRequestChain, InjectOptions, Response as LightMyRequestResponse, CallbackFunc as LightMyRequestCallback } from 'light-my-request'
2import { RouteOptions, RouteShorthandMethod, RouteGenericInterface } from './route'
3import { FastifySchemaCompiler, FastifySchemaValidationError } from './schema'
4import { RawServerBase, RawRequestDefaultExpression, RawServerDefault, RawReplyDefaultExpression, ContextConfigDefault } from './utils'
5import { FastifyLoggerInstance } from './logger'
6import { FastifyRegister } from './register'
7import { onRequestHookHandler, preParsingHookHandler, onSendHookHandler, preValidationHookHandler, preHandlerHookHandler, preSerializationHookHandler, onResponseHookHandler, onErrorHookHandler, onRouteHookHandler, onRegisterHookHandler, onCloseHookHandler, onReadyHookHandler, onTimeoutHookHandler } from './hooks'
8import { FastifyRequest } from './request'
9import { FastifyReply } from './reply'
10import { FastifyError } from 'fastify-error'
11import { AddContentTypeParser, hasContentTypeParser } from './content-type-parser'
12
13/**
14 * Fastify server instance. Returned by the core `fastify()` method.
15 */
16export interface FastifyInstance<
17 RawServer extends RawServerBase = RawServerDefault,
18 RawRequest extends RawRequestDefaultExpression<RawServer> = RawRequestDefaultExpression<RawServer>,
19 RawReply extends RawReplyDefaultExpression<RawServer> = RawReplyDefaultExpression<RawServer>,
20 Logger = FastifyLoggerInstance
21> {
22 server: RawServer;
23 prefix: string;
24 version: string | undefined;
25 log: Logger;
26
27 addSchema(schema: unknown): FastifyInstance<RawServer, RawRequest, RawReply, Logger>;
28 getSchema(schemaId: string): unknown;
29 getSchemas(): Record<string, unknown>;
30
31 after(): FastifyInstance<RawServer, RawRequest, RawReply, Logger> & PromiseLike<undefined>;
32 after(afterListener: (err: Error) => void): FastifyInstance<RawServer, RawRequest, RawReply, Logger>;
33
34 close(): FastifyInstance<RawServer, RawRequest, RawReply, Logger> & PromiseLike<undefined>;
35 close(closeListener: () => void): FastifyInstance<RawServer, RawRequest, RawReply, Logger>;
36
37 // should be able to define something useful with the decorator getter/setter pattern using Generics to enfore the users function returns what they expect it to
38 decorate(property: string | symbol, value: any, dependencies?: string[]): FastifyInstance<RawServer, RawRequest, RawReply, Logger>;
39 decorateRequest(property: string | symbol, value: any, dependencies?: string[]): FastifyInstance<RawServer, RawRequest, RawReply, Logger>;
40 decorateReply(property: string | symbol, value: any, dependencies?: string[]): FastifyInstance<RawServer, RawRequest, RawReply, Logger>;
41
42 hasDecorator(decorator: string | symbol): boolean;
43 hasRequestDecorator(decorator: string | symbol): boolean;
44 hasReplyDecorator(decorator: string | symbol): boolean;
45
46 inject(opts: InjectOptions | string, cb: LightMyRequestCallback): void;
47 inject(opts: InjectOptions | string): Promise<LightMyRequestResponse>;
48 inject(): LightMyRequestChain;
49
50 listen(port: number | string, address: string, backlog: number, callback: (err: Error, address: string) => void): void;
51 listen(port: number | string, address: string, callback: (err: Error, address: string) => void): void;
52 listen(port: number | string, callback: (err: Error, address: string) => void): void;
53 listen(port: number | string, address?: string, backlog?: number): Promise<string>;
54 listen(opts: { port: number; host?: string; backlog?: number }, callback: (err: Error, address: string) => void): void;
55 listen(opts: { port: number; host?: string; backlog?: number }): Promise<string>;
56
57 ready(): FastifyInstance<RawServer, RawRequest, RawReply> & PromiseLike<undefined>;
58 ready(readyListener: (err: Error) => void): FastifyInstance<RawServer, RawRequest, RawReply, Logger>;
59
60 register: FastifyRegister<FastifyInstance<RawServer, RawRequest, RawReply, Logger> & PromiseLike<undefined>>;
61
62 /**
63 * This method will throw a `FST_ERR_MISSING_MIDDLEWARE` error unless support
64 * for Express-style middlewares is first enabled. Visit
65 * https://fastify.io/docs/latest/Middleware/ for more info.
66 */
67 use(...args: unknown[]): unknown;
68
69 route<
70 RouteGeneric extends RouteGenericInterface = RouteGenericInterface,
71 ContextConfig = ContextConfigDefault
72 >(opts: RouteOptions<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig>): FastifyInstance<RawServer, RawRequest, RawReply, Logger>;
73
74 get: RouteShorthandMethod<RawServer, RawRequest, RawReply>;
75 head: RouteShorthandMethod<RawServer, RawRequest, RawReply>;
76 post: RouteShorthandMethod<RawServer, RawRequest, RawReply>;
77 put: RouteShorthandMethod<RawServer, RawRequest, RawReply>;
78 delete: RouteShorthandMethod<RawServer, RawRequest, RawReply>;
79 options: RouteShorthandMethod<RawServer, RawRequest, RawReply>;
80 patch: RouteShorthandMethod<RawServer, RawRequest, RawReply>;
81 all: RouteShorthandMethod<RawServer, RawRequest, RawReply>;
82
83 // addHook: overloads
84
85 // Lifecycle addHooks
86
87 /**
88 * `onRequest` is the first hook to be executed in the request lifecycle. There was no previous hook, the next hook will be `preParsing`.
89 * Notice: in the `onRequest` hook, request.body will always be null, because the body parsing happens before the `preHandler` hook.
90 */
91 addHook<
92 RouteGeneric extends RouteGenericInterface = RouteGenericInterface,
93 ContextConfig = ContextConfigDefault
94 >(
95 name: 'onRequest',
96 hook: onRequestHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig>
97 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger>;
98
99 /**
100 * `preParsing` is the second hook to be executed in the request lifecycle. The previous hook was `onRequest`, the next hook will be `preValidation`.
101 * Notice: in the `preParsing` hook, request.body will always be null, because the body parsing happens before the `preHandler` hook.
102 */
103 addHook<
104 RouteGeneric extends RouteGenericInterface = RouteGenericInterface,
105 ContextConfig = ContextConfigDefault
106 >(
107 name: 'preParsing',
108 hook: preParsingHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig>
109 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger>;
110
111 /**
112 * `preValidation` is the third hook to be executed in the request lifecycle. The previous hook was `preParsing`, the next hook will be `preHandler`.
113 */
114 addHook<
115 RouteGeneric extends RouteGenericInterface = RouteGenericInterface,
116 ContextConfig = ContextConfigDefault
117 >(
118 name: 'preValidation',
119 hook: preValidationHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig>
120 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger>;
121
122 /**
123 * `preHandler` is the fourth hook to be executed in the request lifecycle. The previous hook was `preValidation`, the next hook will be `preSerialization`.
124 */
125 addHook<
126 RouteGeneric extends RouteGenericInterface = RouteGenericInterface,
127 ContextConfig = ContextConfigDefault
128 >(
129 name: 'preHandler',
130 hook: preHandlerHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig>
131 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger>;
132
133 /**
134 * `preSerialization` is the fifth hook to be executed in the request lifecycle. The previous hook was `preHandler`, the next hook will be `onSend`.
135 * Note: the hook is NOT called if the payload is a string, a Buffer, a stream or null.
136 */
137 addHook<
138 PreSerializationPayload = unknown,
139 RouteGeneric extends RouteGenericInterface = RouteGenericInterface,
140 ContextConfig = ContextConfigDefault
141 >(
142 name: 'preSerialization',
143 hook: preSerializationHookHandler<PreSerializationPayload, RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig>
144 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger>;
145
146 /**
147 * 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`.
148 * Note: If you change the payload, you may only change it to a string, a Buffer, a stream, or null.
149 */
150 addHook<
151 OnSendPayload = unknown,
152 RouteGeneric extends RouteGenericInterface = RouteGenericInterface,
153 ContextConfig = ContextConfigDefault
154 >(
155 name: 'onSend',
156 hook: onSendHookHandler<OnSendPayload, RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig>
157 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger>;
158
159 /**
160 * `onResponse` is the seventh and last hook in the request hook lifecycle. The previous hook was `onSend`, there is no next hook.
161 * 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.
162 */
163 addHook<
164 RouteGeneric extends RouteGenericInterface = RouteGenericInterface,
165 ContextConfig = ContextConfigDefault
166 >(
167 name: 'onResponse',
168 hook: onResponseHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig>
169 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger>;
170
171 /**
172 * `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)
173 * 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.
174 */
175 addHook<
176 RouteGeneric extends RouteGenericInterface = RouteGenericInterface,
177 ContextConfig = ContextConfigDefault
178 >(
179 name: 'onTimeout',
180 hook: onTimeoutHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig>
181 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger>;
182
183 /**
184 * This hook is useful if you need to do some custom error logging or add some specific header in case of error.
185 * It is not intended for changing the error, and calling reply.send will throw an exception.
186 * 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).
187 * Notice: unlike the other hooks, pass an error to the done function is not supported.
188 */
189 addHook<
190 RouteGeneric extends RouteGenericInterface = RouteGenericInterface,
191 ContextConfig = ContextConfigDefault
192 >(
193 name: 'onError',
194 hook: onErrorHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig>
195 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger>;
196
197 // Application addHooks
198
199 /**
200 * 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
201 */
202 addHook<
203 RouteGeneric extends RouteGenericInterface = RouteGenericInterface,
204 ContextConfig = ContextConfigDefault
205 >(
206 name: 'onRoute',
207 hook: onRouteHookHandler<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig>
208 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger>;
209
210 /**
211 * Triggered when a new plugin is registered and a new encapsulation context is created. The hook will be executed before the registered code.
212 * 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.
213 * Note: This hook will not be called if a plugin is wrapped inside fastify-plugin.
214 */
215 addHook(
216 name: 'onRegister',
217 hook: onRegisterHookHandler<RawServer, RawRequest, RawReply, Logger>
218 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger>;
219
220 /**
221 * 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.
222 */
223 addHook(
224 name: 'onReady',
225 hook: onReadyHookHandler<RawServer, Logger>
226 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger>;
227
228 /**
229 * 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.
230 */
231 addHook(
232 name: 'onClose',
233 hook: onCloseHookHandler<RawServer, RawRequest, RawReply, Logger>
234 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger>;
235
236 /**
237 * Set the 404 handler
238 */
239 setNotFoundHandler<RouteGeneric extends RouteGenericInterface = RouteGenericInterface>(
240 handler: (request: FastifyRequest<RouteGeneric, RawServer, RawRequest>, reply: FastifyReply<RawServer, RawRequest, RawReply, RouteGeneric>) => void
241 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger>;
242
243 /**
244 * Set a function that will be called whenever an error happens
245 */
246 setErrorHandler<TError extends Error = FastifyError, RouteGeneric extends RouteGenericInterface = RouteGenericInterface>(
247 handler: (this: FastifyInstance<RawServer, RawRequest, RawReply, Logger>, error: TError, request: FastifyRequest<RouteGeneric, RawServer, RawRequest>, reply: FastifyReply<RawServer, RawRequest, RawReply, RouteGeneric>) => void
248 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger>;
249
250 /**
251 * Set the schema validator for all routes.
252 */
253 setValidatorCompiler(schemaCompiler: FastifySchemaCompiler): FastifyInstance<RawServer, RawRequest, RawReply, Logger>;
254
255 /**
256 * Set the schema serializer for all routes.
257 */
258 setSerializerCompiler(schemaCompiler: FastifySchemaCompiler): FastifyInstance<RawServer, RawRequest, RawReply, Logger>;
259
260 /**
261 * Set the reply serializer for all routes.
262 */
263 setReplySerializer(replySerializer: (payload: unknown, statusCode: number) => string): FastifyInstance<RawServer, RawRequest, RawReply, Logger>;
264
265 /*
266 * Set the schema error formatter for all routes.
267 */
268 setSchemaErrorFormatter(errorFormatter: (errors: FastifySchemaValidationError[], dataVar: string) => Error): FastifyInstance<RawServer, RawRequest, RawReply, Logger>;
269 /**
270 * Add a content type parser
271 */
272 addContentTypeParser: AddContentTypeParser<RawServer, RawRequest>;
273 hasContentTypeParser: hasContentTypeParser;
274
275 /**
276 * Prints the representation of the internal radix tree used by the router
277 */
278 printRoutes(): string;
279}