Introduction
I got an express server
export const Search = {
start: () => {
useContainer(Container);
const app = express();
app.use(function (req, res, next) {
req.setTimeout(0); // no timeout for all requests, your server will be DoS'd
next();
});
app.use(express.urlencoded({ extended: true }));
// Configure controllers
useExpressServer(app, {
routePrefix: '/api',
controllers: [
SearchController,
],
});
app.get('*', (req, res, next) => {
if (req.path.startsWith('/api')) {
next();
} else {
res.end();
}
});
const server = app.listen(process.env.PORT || 3000, () => {
// eslint-disable-next-line no-console
Logger.info(`⚡️[server]: Server is running at https://localhost:${process.env.PORT || 3000}`);
});
server.setTimeout(0);
},
};
SearchController
in turn uses type di to instantiate a Service class in it's constructor like so
@JsonController('/search')
@Service()
export class SearchController {
constructor(
private graph: SearchService,
) {
...
}
and when we get a post search request, we process it inside the search service like so:
@Post('') async search(@Body() query:searchQuery, @Res() response: any) { query = toLowerCase(query); const results = await this.graph.search(query); return response.send(results); }
Problem
Inside the search service, the search method does this
async search(query: searchQuery) {
this.queryPersonId = query.personId;
the problem here is that this.queryPersonId shares this parameter from across different requests! So what's happening here is that we're not instantiating a separate Search Service per request! How do we do that with type di?