express-auto-import-routes

Auto import your express routes.

Usage no npm install needed!

<script type="module">
  import expressAutoImportRoutes from 'https://cdn.skypack.dev/express-auto-import-routes';
</script>

README

express-auto-import-routes

Automatically import routers and create the correct endpoints using the structure of folders. Dynamic values use a underscore in the folder or filename: /_value changes it to /:value. Files take precedence over folders when doing router.use() which means a folder with the name _id will be used after a file with the name stuff.ts inside the same folder. This makes the endpoint /endpoint/stuff match before /endpoint/:id in the express router pipe. Non dynamic routes also take precedence over dynamic ones, /folder/_dynamic-value would be used after /folder/nondynamic-value.

Usage

app.js

const { router } = require('express-auto-import-routes')

const routesFolder = path.join(__dirname, 'routes')

app.use(router(routesFolder))

endpoint.js

const express = require('express')

const router = express.Router({ mergeParams: true })

router.get('', (req, res) => {
  res.send('hello world!')
})

// Important that it is exported as an object with the router as a key
module.exports = { router }

// Typescript 
export { router }

or you only write the handlers (get, put, post, patch, delete)

// Important to export handlers
module.exports.handlers = {
  get (req, res) {
    res.send('hello world!')
  }
}

// Typescript
export const handlers = {
  get (req, res) {
    res.send('hello world')
  }
}

Using middleware

Consider the following folder structure:

routes
├── index.ts
└── posts
    ├── _id
    │   ├── comments.ts
    │   └── index.ts
    ├── hot.ts
    └── index.ts

Lets say you want a middleware on the routes /posts/:id and /posts/:id/comments so everything inside the /posts/:id endpoint. You simply need to use this middleware inside the file /posts/_id/index.ts.

const express = require('express')

const router = express.Router({ mergeParams: true })

router.use('', (req, res, next) => {
  console.log('this is middleware for endpoints underneath and including `/posts/:id`')
  next()
})

router.get('', (req, res) => {
  res.send('hello world!')
})

If you at the same time would want middlewares only for the endpoint /posts/:id you could do this:

router.all('', (req, res, next) => {
  console.log('this middleware will only run on the `/posts/:id` endpoint!')
  next()
})

The following folder structure would create these endpoints

/
/posts
/posts/hot
/posts/:id
/posts/:id/comments

/users/:id
/users/:id/amount-posts
/users/:id/comments
/users/:id/info
/users/:id/posts

routes
├── index.ts
├── posts
│   ├── _id
│   │   ├── comments.ts
│   │   └── index.ts
│   ├── hot.ts
│   └── index.ts
└── users
    └── _id
        ├── amount-posts.ts
        ├── comments.ts
        ├── index.ts
        ├── info.ts
        └── posts.ts