MCPcopy Create free account
hub / github.com/fastify/fastify / route

Function route

lib/route.js:204–454  ·  view source on GitHub ↗

* Route management * @param {{ options: import('../fastify').RouteOptions, isFastify: boolean }}

({ options, isFastify })

Source from the content-addressed store, hash-verified

202 * @param {{ options: import('../fastify').RouteOptions, isFastify: boolean }}
203 */
204 function route ({ options, isFastify }) {
205 throwIfAlreadyStarted('Cannot add route!')
206
207 // Since we are mutating/assigning only top level props, it is fine to have a shallow copy using the spread operator
208 const opts = { ...options }
209
210 const path = opts.url || opts.path || ''
211
212 if (!opts.handler) {
213 throw new FST_ERR_ROUTE_MISSING_HANDLER(opts.method, path)
214 }
215
216 if (opts.errorHandler !== undefined && typeof opts.errorHandler !== 'function') {
217 throw new FST_ERR_ROUTE_HANDLER_NOT_FN(opts.method, path)
218 }
219
220 validateBodyLimitOption(opts.bodyLimit)
221 validateHandlerTimeoutOption(opts.handlerTimeout)
222
223 const shouldExposeHead = opts.exposeHeadRoute ?? globalExposeHeadRoutes
224
225 let isGetRoute = false
226 let isHeadRoute = false
227
228 if (Array.isArray(opts.method)) {
229 for (let i = 0; i < opts.method.length; ++i) {
230 opts.method[i] = normalizeAndValidateMethod.call(this, opts.method[i])
231 validateSchemaBodyOption.call(this, opts.method[i], path, opts.schema)
232
233 isGetRoute = opts.method.includes('GET')
234 isHeadRoute = opts.method.includes('HEAD')
235 }
236 } else {
237 opts.method = normalizeAndValidateMethod.call(this, opts.method)
238 validateSchemaBodyOption.call(this, opts.method, path, opts.schema)
239
240 isGetRoute = opts.method === 'GET'
241 isHeadRoute = opts.method === 'HEAD'
242 }
243
244 // we need to clone a set of initial options for HEAD route
245 const headOpts = shouldExposeHead && isGetRoute ? { ...options } : null
246
247 const prefix = this[kRoutePrefix]
248
249 if (path === '/' && prefix.length > 0 && opts.method !== 'HEAD') {
250 switch (opts.prefixTrailingSlash) {
251 case 'slash':
252 addNewRoute.call(this, { path, isFastify })
253 break
254 case 'no-slash':
255 addNewRoute.call(this, { path: '', isFastify })
256 break
257 case 'both':
258 default:
259 addNewRoute.call(this, { path: '', isFastify })
260 // If ignoreTrailingSlash is set to true we need to add only the '' route to prevent adding an incomplete one.
261 if (ignoreTrailingSlash !== true && (ignoreDuplicateSlashes !== true || !prefix.endsWith('/'))) {

Callers

nothing calls this directly

Calls 3

throwIfAlreadyStartedFunction · 0.85
validateBodyLimitOptionFunction · 0.85

Tested by

no test coverage detected