genbs / fastify-autoroutes

Map directory structure to routes url

Home Page:https://giovannicardamone.github.io/fastify-autoroutes

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

fastify-autoroutes

Logo

JavaScript   TypeScript

GitHub forks GitHub stars GitHub issues All Contributors GitHub license

CI Test codecov

NPM version NPM downloads Known Vulnerabilities

⭐ Thanks everyone who want to star the project, it means a lot!

Automatic add routes based on file system hierarchy.

Full Documentation

🚀 Install

npm install --save fastify-autoroutes

📘 Usage

const fastify = require('fastify')
const server = fastify()

server.register(require('fastify-autoroutes'), {
  dir: './<autoroutes-directory>', // relative to your cwd
})
//file: `<autoroutes-directory>/some/route/index.js`
//mapped to: `<your host>/some/route`

export default (fastifyInstance) => ({
  get: {
    // any of routes option allowed by fastify: https://www.fastify.io/docs/latest/Routes/#routes-option
    // except for `url` and `method`

    handler: (request, reply) => {
      reply.send('hello index route')
    }
  },
  // other available methods are following: ['delete', 'get', 'head', 'patch', 'post', 'put', 'options']
})

ℹ️ use syntax :paramName or {paramName} in file name to specify url parameters

//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}`)
    }
  },
})

▶️ Accepted methods in module

  • delete
  • get
  • head
  • patch
  • post
  • put
  • options

▶️ Url parameters using path name

to use url parameters in your route use {parmName} in your file or directory, it will be automatically changed to fastify parameter

▶️ Skip files in autoroutes directory

to skip file in routes directory, prepend the . or _ charater to filename

examples:

  • .skipped_directory
  • _also_skipped_directory
  • .skipped_file.js
  • .skipped_file.ts
  • _also_skipped_file.js
  • _also_skipped_file.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

🔃 Changes

Check CHANGELOG

📄 License

Licensed under MIT

✨ Contributors

Thanks goes to these wonderful people (emoji key):

If you want to contribute remember to comment on an issue or pull request with:

@all-contributors please add @jakebolam for infrastructure, tests and code


Giovanni Cardamone

💻 📖 💡 🚧

This project follows the all-contributors specification. Contributions of any kind welcome!

About

Map directory structure to routes url

https://giovannicardamone.github.io/fastify-autoroutes

License:MIT License


Languages

Language:JavaScript 65.2%Language:TypeScript 34.8%