Fastify Register Routes
fastify register routes (fastify-register-routes) Plugin to automatically load routes from a specified path and optionally limit loaded file names by a regular expression.
Install
npm i fastify-register-routes
Usage
Options
-
regex
: You regex to test file name the router Ex.: user-router.js if nothing is informed I'll use the regex standard/((Route)|(Routes)|(route)|(routes))\.js|.mjs$/
. -
showTable
: After loaded all routes, will showind one table with all routes registred's by default value is false. -
path
: Path is used to reference the directory for reading files, therefore, isrequired
. -
useService
: allowed injecting methods of services inside the fastifyRequest
object. Accepts as an argument a list of functions, exemple below. -
schema
: In your routes, you can define the schema, according to the documentation of fastify, this parameter is optional, you just need to informschema: you-schema
consult the documentation of fastify, see other examples here
const path = const Fastify = const registerRoutes = const fastify = // path with your's routes filesconst defaultPath = path fastify // case need confering routes registred's// fastify provide an log with the routes loaded// this function ready é executed after the all is completed loadingfastify fastify
Options for Routes
useWrap
: use a flag useWrap with value true, is an envelope of handler methods, i see below
moduleexports = path: '/some-route' handler:
Options for method's services Injected and Scheme at routes
// by default, is used ajv for validation schemes.const schema = querystring: name: type: 'string' excitement: type: 'integer' response: 200: type: 'object' properties: hello: type: 'string' const action01 = { // same code here return 'action01'} const action02 = { // your logic here! return 'action02'} const get = name: 'user-get' version: '1.0.0' path: '/get-route' // your scheme here, any questions, consult the documentation of fastify. schema: schema method: 'get' service: action01 action02 { const action = req$service return reply }
Other Examples using services injections.
// middleware.js file // don't you import much services methods within you logic, // you will only need inject on http-route, its file the routes. const createUser = { const userNews = req$service // Wow! it's simple!} // service.js// example of serviceconst createUser = User // route.js// example of uses const userRoute = name: 'user-create' version: '1.2.1' path: '/user-create' method: 'post' service: createUser handler: middlewarecreateUser
disclaimer
any error can be reported, as issue and I am accepting PR's :)