I wish to get an asynchronous dependency at the top level, without having to use top level awaits.
Currently I am using a temporary hack by declaring getService()
, an asynchronous function, in the controller file. However, by doing so I have to call the getService()
function for every route that I declare in my controller file.
Here is my current code:
// something.controller.ts
const router = Router();
async function getService() { // temporary hack
return await container.getAsync<IService>(TYPES.Service)
}
router.get("/collection",
paginateCollectionSchema,
validateRequestSchema,
async (req, res) => {
const service = await getService(); // if I have 100 routes, I have do this 100 times
const paginationSettings = await service.getSome(req.query.limit, req.query.offset);
const pagination = paginate("/collection", paginationSettings);
return res.json(pagination)
},
);
...
export router;
What I hope to achieve is something like this:
// something.controller.ts
const router = Router();
// get service once without using top level await
router.get("/collection",
paginateCollectionSchema,
validateRequestSchema,
async (req, res) => {
// no need to get service
const paginationSettings = await service.getSome(req.query.limit, req.query.offset);
const pagination = paginate("/collection", paginationSettings);
return res.json(pagination)
},
);
...
export router;