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
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 }