Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(routes): expose findRoute and param validator #5230

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
23 changes: 23 additions & 0 deletions docs/Reference/Server.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ describes the properties available in that options object.
- [routing](#routing)
- [route](#route)
- [hasRoute](#hasroute)
- [findRoute](#findroute)
- [close](#close)
- [decorate\*](#decorate)
- [register](#register)
Expand Down Expand Up @@ -1148,6 +1149,28 @@ if (routeExists === false) {
}
```

#### findRoute
<a id="findRoute"></a>

Method to retrieve a route already registered to the internal router. It
expects an object as the payload. `url` and `method` are mandatory fields. It
is possible to also specify `constraints`.
The method returns a route object or `null` if the route cannot be found.

```js
const route = fastify.findRoute({
url: '/artists/:artistId',
method: 'GET',
constraints: { version: '1.0.0' } // optional
})

if (route !== null) {
// perform some route checks
console.log(route.params) // `{artistId: ':artistId'}`
}
```


#### close
<a id="close"></a>

Expand Down
3 changes: 3 additions & 0 deletions fastify.js
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,9 @@ function fastify (options) {
hasRoute: function _route (options) {
return router.hasRoute.call(this, { options })
},
findRoute: function _findRoute (options) {
return router.findRoute(options)
},
// expose logger instance
log: logger,
// type provider
Expand Down
9 changes: 7 additions & 2 deletions lib/route.js
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,8 @@ function buildRouting (options) {
printRoutes: router.prettyPrint.bind(router),
addConstraintStrategy,
hasConstraintStrategy,
isAsyncConstraint
isAsyncConstraint,
findRoute
}

function addConstraintStrategy (strategy) {
Expand Down Expand Up @@ -169,11 +170,15 @@ function buildRouting (options) {
}

function hasRoute ({ options }) {
return findRoute(options) !== null
}

function findRoute (options) {
return router.find(
options.method,
options.url || '',
options.constraints
) !== null
)
}

/**
Expand Down
118 changes: 118 additions & 0 deletions test/findRoute.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
'use strict'

const { test } = require('tap')
const Fastify = require('..')
const fastifyPlugin = require('fastify-plugin')

test('findRoute should return null when route cannot be found due to a different method', t => {
t.plan(1)
const fastify = Fastify()

fastify.get('/artists/:artistId', {
schema: {
params: { artistId: { type: 'integer' } }
},
handler: (req, reply) => reply.send(typeof req.params.artistId)
})

t.equal(fastify.findRoute({
method: 'POST',
url: '/artists/:artistId'
}), null)
})

test('findRoute should return an immutable route to avoid leaking and runtime route modifications', t => {
t.plan(1)
const fastify = Fastify()

fastify.get('/artists/:artistId', {
schema: {
params: { artistId: { type: 'integer' } }
},
handler: (req, reply) => reply.send(typeof req.params.artistId)
})

let route = fastify.findRoute({
method: 'GET',
url: '/artists/:artistId'
})

route.params = {
...route.params,
id: ':id'
}

route = fastify.findRoute({
method: 'GET',
url: '/artists/:artistId'
})
t.same(route.params, { artistId: ':artistId' })
})

test('findRoute should return null when route cannot be found due to a different path', t => {
t.plan(1)
const fastify = Fastify()

fastify.get('/artists/:artistId', {
schema: {
params: { artistId: { type: 'integer' } }
},
handler: (req, reply) => reply.send(typeof req.params.artistId)
})

t.equal(fastify.findRoute({
method: 'GET',
url: '/books/:bookId'
}), null)
})

test('findRoute should return the route when found', t => {
t.plan(2)
const fastify = Fastify()

const handler = (req, reply) => reply.send(typeof req.params.artistId)

fastify.get('/artists/:artistId', {
schema: {
params: { artistId: { type: 'integer' } }
},
handler
})

const route = fastify.findRoute({
method: 'GET',
url: '/artists/:artistId'
})

t.same(route.params, { artistId: ':artistId' })
t.same(route.store.schema, { params: { artistId: { type: 'integer' } } })
})

test('findRoute should work correctly when used within plugins', t => {
t.plan(1)
const fastify = Fastify()
const handler = (req, reply) => reply.send(typeof req.params.artistId)
fastify.get('/artists/:artistId', {
schema: {
params: { artistId: { type: 'integer' } }
},
handler
})

function validateRoutePlugin (instance, opts, done) {
const validateParams = function () {
return instance.findRoute({
method: 'GET',
url: '/artists/:artistId'
}) !== null
}
instance.decorate('validateRoutes', { validateParams })
done()
}

fastify.register(fastifyPlugin(validateRoutePlugin))

fastify.ready(() => {
t.equal(fastify.validateRoutes.validateParams(), true)
})
})
11 changes: 10 additions & 1 deletion test/types/route.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ import * as http from 'http'
import { expectAssignable, expectError, expectType } from 'tsd'
import fastify, { FastifyInstance, FastifyReply, FastifyRequest, RouteHandlerMethod } from '../../fastify'
import { RequestPayload } from '../../types/hooks'
import { HTTPMethods } from '../../types/utils'
import { HTTPMethods, RawServerBase, RawServerDefault } from '../../types/utils'
import { FindResult, HTTPVersion } from 'find-my-way'
import { FindMyWayFindResult, FindMyWayVersion } from '../../types/instance'

/*
* Testing Fastify HTTP Routes and Route Shorthands.
Expand Down Expand Up @@ -453,6 +455,13 @@ expectType<boolean>(fastify().hasRoute({
}
}))

expectType<FindMyWayFindResult<RawServerDefault>>(
fastify().findRoute({
url: '/',
method: 'get'
})
)

expectType<FastifyInstance>(fastify().route({
url: '/',
method: 'get',
Expand Down
9 changes: 8 additions & 1 deletion types/instance.d.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { FastifyError } from '@fastify/error'
import { ConstraintStrategy, HTTPVersion } from 'find-my-way'
import { ConstraintStrategy, FindResult, HTTPVersion } from 'find-my-way'
import * as http from 'http'
import { CallbackFunc as LightMyRequestCallback, Chain as LightMyRequestChain, InjectOptions, Response as LightMyRequestResponse } from 'light-my-request'
import { AddContentTypeParser, ConstructorAction, FastifyBodyParser, getDefaultJsonParser, hasContentTypeParser, ProtoAction, removeAllContentTypeParsers, removeContentTypeParser } from './content-type-parser'
Expand Down Expand Up @@ -86,6 +86,7 @@ export interface FastifyListenOptions {

type NotInInterface<Key, _Interface> = Key extends keyof _Interface ? never : Key
type FindMyWayVersion<RawServer extends RawServerBase> = RawServer extends http.Server ? HTTPVersion.V1 : HTTPVersion.V2
type FindMyWayFindResult<RawServer extends RawServerBase> = FindResult<FindMyWayVersion<RawServer>>

type GetterSetter<This, T> = T | {
getter: (this: This) => T,
Expand Down Expand Up @@ -219,6 +220,12 @@ export interface FastifyInstance<
SchemaCompiler extends FastifySchema = FastifySchema,
>(opts: Pick<RouteOptions<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider>, 'method' | 'url' | 'constraints'>): boolean;

findRoute<
RouteGeneric extends RouteGenericInterface = RouteGenericInterface,
ContextConfig = ContextConfigDefault,
SchemaCompiler extends FastifySchema = FastifySchema,
>(opts: Pick<RouteOptions<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider>, 'method' | 'url' | 'constraints'>): FindMyWayFindResult<RawServer>;

// addHook: overloads

// Lifecycle addHooks
Expand Down