### Registering and Using @fastify/routes Plugin Source: https://github.com/fastify/fastify-routes/blob/main/README.md Demonstrates how to register the @fastify/routes plugin in a Fastify application and access the `fastify.routes` Map after registering a route. This example shows a basic GET route and logs the collected routes to the console. ```javascript const fastify = require("fastify")(); (async () => { await fastify.register(require("@fastify/routes")); fastify.get("/hello", {}, (request, reply) => { reply.send({ hello: "world" }); }); fastify.listen({ port: 3000 }, (err, address) => { if (err) { console.error(err); return; } console.log(fastify.routes); /* will output a Map with entries: { '/hello': [ { method: 'GET', url: '/hello', schema: Object, handler: , prefix: , logLevel: , bodyLimit: } ] } */ }); })(); ``` -------------------------------- ### Building a Route Documentation Endpoint with @fastify/routes Source: https://context7.com/fastify/fastify-routes/llms.txt Provides a practical example of creating an API endpoint that dynamically exposes all registered application routes. It iterates through the routes managed by @fastify/routes, extracting details like method, path, description, and schema information to serve as API documentation. ```javascript const fastify = require('fastify')(); const routes = require('@fastify/routes'); async function documentationExample() { await fastify.register(routes); // Application routes fastify.get('/users', { schema: { description: 'List all users', response: { 200: { type: 'array' } } } }, async () => []); fastify.post('/users', { schema: { description: 'Create a new user', body: { type: 'object', properties: { name: { type: 'string' } } } } }, async () => ({})); fastify.get('/users/:id', { schema: { description: 'Get user by ID' } }, async () => ({})); // Documentation endpoint fastify.get('/docs/routes', async (request, reply) => { const documentation = []; for (const [path, routeList] of fastify.routes.entries()) { if (path === '/docs/routes') continue; // Skip this endpoint routeList.forEach(route => { documentation.push({ method: route.method, path: route.url, description: route.schema?.description || 'No description', bodySchema: route.schema?.body || null, responseSchema: route.schema?.response || null }); }); } return { routes: documentation }; }); await fastify.listen({ port: 3000 }); console.log('Server running. Visit http://localhost:3000/docs/routes'); } documentationExample(); // GET /docs/routes returns: // { // "routes": [ // { "method": "GET", "path": "/users", "description": "List all users", ... }, // { "method": "POST", "path": "/users", "description": "Create a new user", ... }, // { "method": "GET", "path": "/users/:id", "description": "Get user by ID", ... } // ] // } ``` -------------------------------- ### Registering Routes with Multiple HTTP Methods in Fastify Source: https://context7.com/fastify/fastify-routes/llms.txt Demonstrates how to register a single route path to respond to multiple HTTP methods (e.g., GET and HEAD, PUT and PATCH) using the @fastify/routes plugin. It shows how the plugin stores these methods as an array in the route configuration and how to access them. ```javascript const fastify = require('fastify')({ exposeHeadRoutes: false }); const routes = require('@fastify/routes'); async function multiMethodExample() { await fastify.register(routes); // Register route with multiple methods fastify.route({ method: ['GET', 'HEAD'], path: '/health', handler: async () => ({ status: 'ok' }) }); fastify.route({ method: ['PUT', 'PATCH'], path: '/users/:id', handler: async (request) => ({ updated: request.params.id }) }); await fastify.ready(); const healthRoute = fastify.routes.get('/health')[0]; console.log('Health methods:', healthRoute.method); // ['GET', 'HEAD'] const userRoute = fastify.routes.get('/users/:id')[0]; console.log('User update methods:', userRoute.method); // ['PUT', 'PATCH'] } multiMethodExample(); ``` -------------------------------- ### Combining @fastify/routes with Fastify's onRoute Hook Source: https://context7.com/fastify/fastify-routes/llms.txt Illustrates how the @fastify/routes plugin captures route options before other onRoute hooks. This example shows how to add constraints (like host restrictions) to routes using an onRoute hook, and how these modifications are reflected in the stored route configurations. ```javascript const fastify = require('fastify')({ exposeHeadRoutes: false }); const routes = require('@fastify/routes'); async function hookExample() { await fastify.register(routes); // Add a hook that automatically adds constraints fastify.addHook('onRoute', (routeOptions) => { if (routeOptions.url.startsWith('/admin')) { routeOptions.constraints = { ...routeOptions.constraints, host: 'admin.example.com' }; } }); fastify.get('/admin/dashboard', async () => ({ page: 'dashboard' })); fastify.get('/public/home', async () => ({ page: 'home' })); await fastify.ready(); const adminRoute = fastify.routes.get('/admin/dashboard')[0]; console.log('Admin constraints:', adminRoute.constraints); // { host: 'admin.example.com' } const publicRoute = fastify.routes.get('/public/home')[0]; console.log('Public constraints:', publicRoute.constraints); // undefined } hookExample(); ``` -------------------------------- ### GET /docs/routes Source: https://context7.com/fastify/fastify-routes/llms.txt Exposes all registered application routes as a JSON documentation object, excluding the documentation endpoint itself. ```APIDOC ## GET /docs/routes ### Description Retrieves a list of all registered routes in the application, including their HTTP methods, URL paths, descriptions, and schema definitions. ### Method GET ### Endpoint /docs/routes ### Parameters None ### Request Example GET /docs/routes ### Response #### Success Response (200) - **routes** (array) - A list of route objects containing method, path, description, bodySchema, and responseSchema. #### Response Example { "routes": [ { "method": "GET", "path": "/users", "description": "List all users", "bodySchema": null, "responseSchema": { "200": { "type": "array" } } } ] } ``` -------------------------------- ### Handling Routes with Constraints Source: https://context7.com/fastify/fastify-routes/llms.txt Illustrates how to register multiple routes on the same path using different constraints, such as host or version, and how they are stored as separate entries. ```javascript const fastify = require('fastify')({ exposeHeadRoutes: false }); const routes = require('@fastify/routes'); async function constraintsExample() { await fastify.register(routes); fastify.route({ method: 'GET', path: '/api/data', handler: async () => ({ source: 'default' }) }); fastify.route({ method: 'GET', path: '/api/data', constraints: { host: 'api.example.com' }, handler: async () => ({ source: 'api.example.com' }) }); fastify.route({ method: 'GET', path: '/api/data', constraints: { version: '2.0.0' }, handler: async () => ({ source: 'v2' }) }); await fastify.ready(); const dataRoutes = fastify.routes.get('/api/data'); console.log('Routes for /api/data:', dataRoutes.length); dataRoutes.forEach((route, index) => { console.log(`Route ${index + 1}:`, { method: route.method, constraints: route.constraints || 'none' }); }); } constraintsExample(); ``` -------------------------------- ### Accessing Route Configuration Options Source: https://context7.com/fastify/fastify-routes/llms.txt Demonstrates how to register the routes plugin and retrieve configuration details like schema, body limits, and log levels from a specific route. ```javascript const fastify = require('fastify')(); const routes = require('@fastify/routes'); async function routeOptionsExample() { await fastify.register(routes); const responseSchema = { response: { 200: { type: 'object', properties: { id: { type: 'integer' }, name: { type: 'string' } } } } }; fastify.get('/users/:id', { schema: responseSchema, bodyLimit: 1048576, logLevel: 'info' }, async (request, reply) => { return { id: request.params.id, name: 'John' }; }); await fastify.ready(); const routeConfig = fastify.routes.get('/users/:id')[0]; console.log('Method:', routeConfig.method); console.log('URL:', routeConfig.url); console.log('Body Limit:', routeConfig.bodyLimit); console.log('Log Level:', routeConfig.logLevel); console.log('Schema:', JSON.stringify(routeConfig.schema, null, 2)); console.log('Handler:', typeof routeConfig.handler); } routeOptionsExample(); ``` -------------------------------- ### Managing Prefixed Routes in Plugins Source: https://context7.com/fastify/fastify-routes/llms.txt Shows how to register routes within plugins using prefixes and how the route configuration tracks the full URL and the specific prefix applied. ```javascript const fastify = require('fastify')({ exposeHeadRoutes: false }); const routes = require('@fastify/routes'); async function prefixExample() { await fastify.register(routes); const apiV1 = function(instance, opts, next) { instance.get('/users', async () => ({ version: 'v1', users: [] })); instance.get('/products', async () => ({ version: 'v1', products: [] })); next(); }; const apiV2 = function(instance, opts, next) { instance.get('/users', async () => ({ version: 'v2', users: [] })); next(); }; fastify.register(apiV1, { prefix: '/api/v1' }); fastify.register(apiV2, { prefix: '/api/v2' }); await fastify.ready(); const v1Users = fastify.routes.get('/api/v1/users')[0]; console.log('URL:', v1Users.url); console.log('Prefix:', v1Users.prefix); const v2Users = fastify.routes.get('/api/v2/users')[0]; console.log('URL:', v2Users.url); console.log('Prefix:', v2Users.prefix); console.log('All paths:', [...fastify.routes.keys()]); } prefixExample(); ``` -------------------------------- ### Registering the Fastify Routes Plugin Source: https://context7.com/fastify/fastify-routes/llms.txt Demonstrates how to register the @fastify/routes plugin. It is critical to register and await the plugin before defining any application routes to ensure they are captured correctly. ```javascript const fastify = require('fastify')(); const routes = require('@fastify/routes'); async function start() { await fastify.register(routes); fastify.get('/hello', async (request, reply) => { return { hello: 'world' }; }); fastify.post('/users', async (request, reply) => { return { created: true }; }); await fastify.ready(); console.log(fastify.routes); } start(); ``` -------------------------------- ### Fastify Routes Data Structure Source: https://github.com/fastify/fastify-routes/blob/main/README.md Illustrates the data structure of the `fastify.routes` Map, showing how paths map to arrays of route configurations. Each route configuration includes details like method, URL, schema, handler, and other options. ```javascript { '/hello': [ { method: 'GET', url: '/hello', schema: { ... }, handler: Function, prefix: String, logLevel: String, bodyLimit: Number, constraints: undefined, }, { method: 'POST', url: '/hello', schema: { ... }, handler: Function, prefix: String, logLevel: String, bodyLimit: Number, constraints: { ... }, } ] } ``` -------------------------------- ### Iterating Over All Registered Routes Source: https://context7.com/fastify/fastify-routes/llms.txt Explains how to traverse the entire route Map to perform bulk analysis or logging. It demonstrates iterating over keys, entries, and calculating the total count of registered routes. ```javascript const fastify = require('fastify')(); const routes = require('@fastify/routes'); async function listAllRoutes() { await fastify.register(routes); fastify.get('/users', async () => ({})); fastify.get('/users/:id', async () => ({})); fastify.post('/users', async () => ({})); fastify.get('/products', async () => ({})); await fastify.ready(); for (const [path, routeList] of fastify.routes.entries()) { routeList.forEach(route => { console.log(`${route.method.toString().padEnd(6)} ${path}`); }); } let totalRoutes = 0; fastify.routes.forEach(routes => { totalRoutes += routes.length; }); console.log(`Total routes: ${totalRoutes}`); } listAllRoutes(); ``` -------------------------------- ### Accessing Route Configurations by Path Source: https://context7.com/fastify/fastify-routes/llms.txt Shows how to retrieve an array of route objects for a specific URL path using the fastify.routes.get() method. This is useful for inspecting multiple methods or constraints associated with a single path. ```javascript const fastify = require('fastify')(); const routes = require('@fastify/routes'); async function example() { await fastify.register(routes); fastify.get('/api/items', async () => ({ items: [] })); fastify.post('/api/items', async () => ({ created: true })); fastify.delete('/api/items/:id', async () => ({ deleted: true })); await fastify.ready(); const itemRoutes = fastify.routes.get('/api/items'); itemRoutes.forEach(route => { console.log(`${route.method} ${route.url}`); }); const deleteRoute = fastify.routes.get('/api/items/:id'); console.log(deleteRoute[0].method); } example(); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.