I'm looking to resolve an asynchronous dependency at the top level without relying on top-level awaits.
Currently, I've implemented a temporary solution by defining an asynchronous function getService()
in the controller file. However, this approach requires me to call the getService()
function for each route declared in the controller file.
This is my current code:
// something.controller.ts
const router = Router();
async function getService() { // temporary solution
return await container.getAsync<IService>(TYPES.Service))
}
router.get("/collection",
paginateCollectionSchema,
validateRequestSchema,
async (req, res) => {
const service = await getService(); // this needs to be done for each route
const paginationSettings = await service.getSome(req.query.limit, req.query.offset);
const pagination = paginate("/collection", paginationSettings);
return res.json(pagination)
},
);
...
export router;
What I would like to achieve is something like this:
// something.controller.ts
const router = Router();
// obtain service once without using top-level await
router.get("/collection",
paginateCollectionSchema,
validateRequestSchema,
async (req, res) => {
// no need to obtain service
const paginationSettings = await service.getSome(req.query.limit, req.query.offset);
const pagination = paginate("/collection", paginationSettings);
return res.json(pagination)
},
);
...
export router;