0.2.1 • Published 9 months ago

express-folder-router v0.2.1

Weekly downloads
-
License
MIT
Repository
github
Last release
9 months ago

express-folder-routing

This is a minimalist package for express to add folder based routing in it.

Installation

npm install express-folder-router

usage

import express from "express"
import {configureFolderRouter} from "express-folder-router"

const app = express()

// the second parameter is optional
configureFolderRouter(app, {
  routeDir: "routes", // specify the root route directory. default is "routes" directory . nested directory like src/routes can be used.
  extraMethods:["WS"], // specify if you have any extra methods . WS for express-ws.
});

app.listen(3000, () => {
  console.log("listening to port 3000");
});

your index files in the specified routeDir will be Api endpoint.

create an api endpoint

// src/routes/hello/index.js 
// endpoint: localhost:3000/hello

export function GET(req,res){
  res.send("this is a get request")
}

export function DELETE(req,res){
  res.send("this is a delete request")
}

export function POST(req,res){
  res.send("this is a post request")
}

alternatively export a default function that will receive all requests except the ones that you export as a named function.

// src/routes/hello/index.js 
// endpoint: localhost:3000/hello

export function GET(req,res){
  res.send("this is a get request")
}

export default function(req,res){
  res.send("this is a catch all request methods except the GET method")
}

Use middleware

export const GET = [authMiddleware,(req,res)=>{
  res.send("get hello")
}]

function authMiddleware(req,res,next){
    if(\*check authentication*\){
        next()
    }else{
        res.status(401).json({message:"unauthenticated"})
    }
}

make a dynamic route by simply naming the folder as ":dynamicName" . then access the dynamicName param as req.params.dynamicName;

make a catch-all route by simply naming the folder as * ;

0.2.1

9 months ago

0.2.0

9 months ago

0.1.9

9 months ago

0.1.8

10 months ago

0.1.7

10 months ago

0.1.4

10 months ago

0.1.6

10 months ago

0.1.5

10 months ago

0.1.3

12 months ago

0.1.2

12 months ago

0.1.1

12 months ago

0.1.0

12 months ago

0.0.9

12 months ago

0.0.8

12 months ago

0.0.7

12 months ago

0.0.6

12 months ago

0.0.5

12 months ago

0.0.4

12 months ago

0.0.3

12 months ago

0.0.2

12 months ago

0.0.1

12 months ago