express-filebased-routing
TypeScript icon, indicating that this package has built-in type declarations

0.1.22 • Public • Published

express-filebased-routing

Install

npm i express-filebased-routing

Usage

import express from 'express'
import { setupRouter, router } from 'express-filebased-routing'

async function main() {
  const app = express()

  // use as middleware
  // app.use(await router())

  // use as function
  await setupRouter(app)

  app.listen(3000)
}
main()

file-based route

// routes/index.js  --->  /
// routes/user/index.js  --->  /user
// routes/user/list.js  --->  /user/list
// routes/user.add.js  --->  /user/add
// Support Method: GET/POST/PUT/PATCH/DELETE/ALL

export const GET = (_req, res) => {
  res.send({
    msg: 'Express REST API is working'
  })
}

// export ALL or export default to use app.all()
const ALL = (req, res) => {
  res.send('match all method')
}
export { ALL }
export default ALL

dynamic route

// routes/user/[id].js  ---> /user/:id
// routes/user.edit.[id].js  ---> /user/edit/:id
export const GET = (req, res) => {
  const { id } = req.params
  res.send({
    msg: `get user #${id}`
  })
}

export const PUT = (req, res) => {
  const { id } = req.params
  res.send({
    msg: `put user #${id}`
  })
}

export const DELETE = (req, res) => {
  const { id } = req.params
  res.send({
    msg: `delete user #${id}`
  })
}

catch-all route

// routes/[...catchall].js  ---> /*
// routes/user/[...catch].js  --->  /user/*

export const GET = (req, res) => {
  res.send('404 Not Found!')
}

route middleware

export const GET = [authMiddleware, rightsMiddleware, findAll]

helper function

import { defineEventHandler } from 'express-filebased-routing'

export const GET = defineEventHandler((req, res) => {
  res.render('index', { title: 'Hello Express.js' })
})

export default defineEventHandler(
  () => {
    return '404 Not Found!'
  },
  { statusCode: 404 }
)

export default defineEventHandler({
  POST: [createUserDto, userService.create]
})

Package Sidebar

Install

npm i express-filebased-routing

Weekly Downloads

240

Version

0.1.22

License

ISC

Unpacked Size

43.1 kB

Total Files

32

Last publish

Collaborators

  • sunshj