I would like pass a class to an express router, and modify my class to each request.
server.ts
import routes from './routes';
import Client from './client';
class Server {
constructor () {
this.app = express()
this.client = new Client();
this.init()
}
init() {
this.app.use(routes(this))
}
}
routes.ts
import {Router} from 'express';
export default (api) => {
const router = Router();
router.get('/', (req, res) => {
api.client.size+=1;
console.log(api.client.size);
});
return router;
}
It's similar to this problem : Pass variable to express router
But this code doesn't work.
Somebody has an idea ?
Thank you
Finally, here is the answer to my question :
server.js
class Server {
constructor () {
this.app = express();
this.app.locals.clients = new Clients();
}
}
route.ts
import {Router} from 'express';
const router = Router();
router.get('/', (req, res) => {
res.app.locals.client.size += 1;
res.send(`bla bla bla`);
});
export default router;