Express: How to pass app-instance to routes from a different file?

后端 未结 8 1051
误落风尘
误落风尘 2020-11-29 16:34

I want to split up my routes into different files, where one file contains all routes and the other one the corresponding actions. I currently have a solution to achieve thi

8条回答
  •  温柔的废话
    2020-11-29 17:13

    If you want to pass an app-instance to others in Node-Typescript :

    Option 1: With the help of import (when importing)

    //routes.ts
    import { Application } from "express";
    import { categoryRoute } from './routes/admin/category.route'
    import { courseRoute } from './routes/admin/course.route';
    
    const routing = (app: Application) => {
        app.use('/api/admin/category', categoryRoute)
        app.use('/api/admin/course', courseRoute)
    }
    export { routing }
    

    Then import it and pass app:

    import express, { Application } from 'express';
    
    const app: Application = express();
    import('./routes').then(m => m.routing(app))
    

    Option 2: With the help of class

    // index.ts
    import express, { Application } from 'express';
    import { Routes } from './routes';
    
    
    const app: Application = express();
    const rotues = new Routes(app)
    ...
    

    Here we will access the app in the constructor of Routes Class

    // routes.ts
    import { Application } from 'express'
    import { categoryRoute } from '../routes/admin/category.route'
    import { courseRoute } from '../routes/admin/course.route';
    
    class Routes {
        constructor(private app: Application) {
            this.apply();
        }
    
        private apply(): void {
           this.app.use('/api/admin/category', categoryRoute)
           this.app.use('/api/admin/course', courseRoute)
        }
    }
    
    export { Routes }
    

提交回复
热议问题