简体   繁体   中英

How to write Dynamic routes for express server ( nodejs)

I have written crud routes

`

const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const db = require('./user_crud_queries')
const port = 3000
app.use(bodyParser.json())
app.use(
    bodyParser.urlencoded({
        extended: true,
    })
)
app.get('/', (request, response) => {
    response.json({
        info: 'Node.js, Express, and Postgres API'
    })
})
app.get('/users', db.getUsers)
app.get('/users/:id', db.getUserById)
app.post('/users', db.createUser)
app.put('/users/:id', db.updateUser)
app.delete('/users/:id', db.deleteUser)
app.listen(port, () => {
    console.log(`App running on port ${port}.`)
})

`

if i have 100 tables do i have to include 100 files? Can it be imported dynamically based on call?

I did create generic crud but i dont want to give that to client because they expect it to be detailed. So 100 tables means 100 separate file for each table. if sever include all 100 tables, will the memory is enough?

So what you can instead do is create a file called users.routes.js/ts and include all of it like this:

import { Router } from "express";

router
.route("/users")
.get(db.getUsers)
.post(db.createUser)

router
.route("/users/:id")
.get('/users/:id', db.getUserById)
.delete('/users/:id', db.deleteUser)




export default router;

and then in the app.js/ts you can user it like this:

import userRouter from "./routes/user.routes";

app.use("/api", userRouter);

So now you can use the following endpoint:

/api/users or /api.users/:id

But yes, if there are 100 tables you will have to use 100 different files for all the CRUD operation that is there, only this will make the code readability easy. Also, you can use different microservice for the same job and reduce the tables for a single server to handle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM