Plugin to handle routes in fastify automatically based on directory structure.
đ GitHub Repository
đ° Full Documentation
đ Install
npm install --save fastify-autoroutes
đ Usage
Register plugin
const fastify = require('fastify')
const server = fastify()
server.register(require('fastify-autoroutes'), {
dir: './<autoroutes-directory>', // relative to your cwd
})
Create file in autoroutes directory
//file: `<autoroutes-directory>/some/route.js`
//url: `http://your-host/some/route`
export default (fastifyInstance) => ({
get: {
handler: async (request, reply) => 'Hello, Route'
},
})
Using typescript support for module
//file: `<autoroutes-directory>/some/route.ts`
//url: `http://your-host/some/route`
import { FastifyInstance } from 'fastify'
import { Resource } from 'fastify-autoroutes'
export default (fastify: FastifyInstance) => <Resource> {
get: {
handler: async (request: FastifyRequest, reply: FastifyReply) => 'Hello, Route!'
}
}
Accepts params in autoroutes
âšī¸ file/directory name must follow syntax
:paramName
or{paramName}
//file: `<autoroutes-directory>/users/{userId}/photos.js`
//mapped to: `<your host>/users/:userId/photos`
export default (fastifyInstance) => ({
get: {
handler: (request, reply) => {
reply.send(`photos of user ${request.params.userId}`)
}
},
})
âļī¸ Route module definition
Method specification for attributes is available here: Method specification
âšī¸ attributes
url
andmethod
are dynamically provided
Allowed attributes mapped to Http methods in module:
- delete
- get
- head
- patch
- post
- put
- options
âļī¸ Skipping files
to skip file in routes directory, prepend the .
or _
charater to filename
examples:
routes
âââ .ignored-directory
âââ _ignored-directory
âââ .ignored-js-file.js
âââ _ignored-js-file.js
âââ .ignored-ts-file.ts
âââ _ignored-ts-file.ts
âââ ignored-js-test.test.js
âââ ignored-ts-test.test.ts
â ī¸ also any
*.test.js
and*.test.ts
are skipped!
this is useful if you want to have a lib file containts functions that don't have to be a route, so just create the file with _
prepending character
đ License
Licensed under MIT
Top comments (2)
Very useful. I have a question, If I am using Javascript without last features, it's possible to use
export default
instead ofmodule.exports
?'export default' is part of the ES6 module system, so to use it you need a javascript runtime that support it, or you can transpile from highter version to lower using babel.
Anyway the library support both.
Thanks for the question i hope i answered it in a clear way :)