I'm trying to figure out a concept in typescript that I can't find the wording for to google online
using express with typescript
login route
import express, { Request, Response } from "express";
import LoginController from "../controllers/login.controller";
const router = express.Router();
const loginController = new LoginController();
router.post("/", loginController.login);
router.post("/", (req: Request, res: Response) => loginController.login(req, res));
export default router;
as you can see, there are two routes for the same path - but this is just for my question: the first post to ("/") has "this" in the logincontroller class undefined the second one works perfectly
import Cache from "../services/Cache";
class LoginController {
cache: Cache = Cache.getInstance();
constructor() {
this.cache = Cache.getInstance();
}
public async login(req: Request, res: Response) {
if (req.body.username === "admin" && req.body.password === "Aa123123") {
console.log("trying to access cache'");
const access_token = await this.cache.get("access_token", () => {
return "a_A1S2D3";
});
console.log("got access token");
res.send({ status: true, data: access_token, msg: "Logged in successfully" });
} else {
res.send({ status: false, data: null, msg: "User not found" });
}
}
}
export default LoginController;
this is the function.
What I am trying to understand is why
router.post("/", loginController.login);
does not have a "this" instance and the second syntax does - cause the "this" should be bound by the class itself, shouldn't it?