Introducing Socket Firewall: Free, Proactive Protection for Your Software Supply Chain.Learn More
Socket
Book a DemoInstallSign in
Socket

express-import-routes

Package Overview
Dependencies
Maintainers
1
Versions
16
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

express-import-routes

Auto import your routes like Nuxt.js

latest
Source
npmnpm
Version
0.0.4-b4
Version published
Maintainers
1
Created
Source

express-import-routes

This plugin will remove the way you think about importing routers for expressjs

0.0.2-b5 What news?

  • Better support middleware access.
  • Using the app-root-path package ensures the transparency of the paths.
  • Add a custom router and middleware registry.

View example

Usage

yarn add express-import-routes
const express = require("express")
const importRoutes = require("express-import-routes")

const app = express()

app.use(importRoutes())

app.listen(8080, err => {
  if ( err ) {
    console.error(err)
  } else {
    console.log("App it runing on port 8080.")
  }
})

And now in the routes directory let's create your routes. express-import-routes will import all of them for you

project
└───routes
│   │   index.js
│   │
│   └───user
│       │   _id
│           └─── index.js
│  
└───app.js
└───package.json
└───yarn.lock

equivalent to

const express = require("express")
const app = express()

app.route("/", require("./routes/index.js"))
app.route("/user/:id", require("./routes/_id/index.,js"))

app.listen(8080, err => {
  if ( err ) {
    console.error(err)
  } else {
    console.log("App it runing on port 8080.")
  }
})

The file naming rules for configuring routers are the same as nuxtjs. Please refer here Nuxt router system

Route file writing rules

The route file in /routes requires you to export some function to render the route

index.js

exports.get = (req, res) => {
  req.end(`Hello!. This is a route /`)
}

You can exports. [get | post | put | delete | options] according to the method you want to listen to

The above example is equivalent to

const router = require("express").Router()

router.route("/").get((req, res) => {
  req.end(`Hello!. This is a route /`)
})

module.exports = router

** If you use an additional plugin eg multer you only need to exports an array **

const upload = multer({ dest: 'uploads/' })

exports.post = [upload.single('avatar'), function (req, res) {
  // req.file is the `avatar` file
  // req.body will hold the text fields, if there were any
}]

Middleware

Add stronger support with middleware.

You can now export the middleware to tell the plugin that you want it to apply the middleware to this route.

exports.middleware = ["auth"]

exports.get = (req, res) => {
  req.end(`Welcome back ${req.user.name}!`)
}

middleware/auth.js

module.exports = (req, res, next) => {
  try {
    if ( req.headers.authorization ) {
      req.user = jwt.verify(req.headers.authorization, SERKET_KEY)
      next()
    } else {
      throw new Error("NO_TOKEN")
    }
  } catch(err) {
    console.log( err )
    next("route")
  }
}

Specify local middleware

You can now specify each middleware for each router.

const upload = multer({ dest: 'uploads/' })

exports.post = [upload.single('avatar'), function (req, res) {
  // req.file is the `avatar` file
  // req.body will hold the text fields, if there were any
}]

or

exports.middleware = {
  post: upload.single('avatar'),
}

exports.post = function (req, res) {
  // req.file is the `avatar` file
  // req.body will hold the text fields, if there were any
}

Register

I added 2 methods for you to register the plugin to know this is a custom method. it can also combine with other modules like multer.

app.js

const express = require("express")
const multer = require("multer")
const importRoutes = require("express-import-routes")
const { registerMiddleware } = importRoutes

const app = express()

const upload = multer({ dest: "uploads/" })

registerMiddleware("file-avatar", upload.single("avatar"))

app.use(importRoutes())

app.listen(8080, err => {
  if ( err ) {
    console.error(err)
  } else {
    console.log("App it runing on port 8080.")
  }
})

Typescript

import { exposeRouter } from "express-import-routes"

export default exposeRouter({
  middleware: {
    post: upload.single('avatar'),
  },
  post (req, res) {
    // req.file is the `avatar` file
    // req.body will hold the text fields, if there were any
  }
})

FAQs

Package last updated on 21 Oct 2021

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts