I’m using the routing-controllers package with Express to load controllers dynamically from files in my project.
My app.ts :
import "reflect-metadata";
import express from 'express';
import dotenv from 'dotenv';
import { useExpressServer } from 'routing-controllers';
import { connectDB } from './config/db';
import requireAll from 'require-all';
import path from 'path';
import { fileURLToPath } from 'url';
dotenv.config();
// Create an instance of an Express app
const app = express();
// Get __filename
const __filename = fileURLToPath(import.meta.url);
// Get __dirname
const __dirname = path.dirname(__filename);
const controllers = Object.values(
requireAll({
dirname: path.join(__dirname, 'controllers'),
filter: /(.+.controller).(ts|js)$/, // Match both .ts and .js files
})
).map((controllerModule: any) =>
Object.values(controllerModule).map((controller: any) => controller.default || controller)
).flat();
useExpressServer(app, {
controllers,
});
// Connect to the database and start the server
const port = 3000;
connectDB().then(() => {
console.log("controllers", controllers);
app.listen(port, () => {
console.log("Successfully running on ", `${port}`);
});
});
When I log the controllers array, it outputs class references like:
[[class Demo1Controller], [class Demo2Controller]]
However, I want to extract just the class names like this:
[Demo1Controller, Demo2Controller]
How can I modify my code to get only the class names of the controllers instead of the entire class objects?
What I Tried:
I attempted using map() and flatMap() to extract the names from the class objects, but neither approach worked as expected.
My Environment :
Nodejs version 20.12.2 and npm version 9.9.4