I am quite new with typescript/express and I have a problem with importing a middleware.
Indeed, I have a module auth.ts
which will contain in a near future several middlewares. Here is its current implementation (with only one middleware for keeping simple).
import { Request, Response } from "express";
import jwt, { JwtPayload } from "jsonwebtoken";
export function getConnectedPerson(req: Request, res: Response, next) {
try {
const token = req.headers.authorization.split(' ')[1];
const { personId } = jwt.verify(token, process.env.TOKEN_SEED) as JwtPayload;
res.locals.personId = personId;
next();
} catch {
res.status(401).send("Invalid request");
}
}
and here is my controller implementation:
import { Request, Response, Router } from "express";
import { autoInjectable } from "tsyringe";
const authMiddleware = require("auth")
@autoInjectable()
export class ActivityController {
constructor() {
}
initRoutes(router: Router) {
router.get('/activities', [
authMiddleware.getConnectedPerson
],async (req: Request, res: Response) => {});
}
}
when starting my app, I get the following error:
Error: Route.get() requires a callback function but got a [object Object]
I am a bit lost with all the possible import/export/require variants. Would you know what is wrong with my implementation ?
CodePudding user response:
In auth.ts, export is going wrong i feel. Please do the following changes and try
import { Request, Response } from "express";
import jwt, { JwtPayload } from "jsonwebtoken";
function getConnectedPerson(req: Request, res: Response, next) {
try {
const token = req.headers.authorization.split(' ')[1];
const { personId } = jwt.verify(token, process.env.TOKEN_SEED) as JwtPayload;
res.locals.personId = personId;
next();
} catch {
res.status(401).send("Invalid request");
}
}
function getConnectedPerson_1(req: Request, res: Response, next) {
// some operation
console.log("second function export");
next();
}
exports.getConnectedPerson = getConnectedPerson;
exports.getConnectedPerson_1 = getConnectedPerson_1;
in controller :-
import { Request, Response, Router } from "express";
import { autoInjectable } from "tsyringe";
//const authMiddleware = require("auth")
const { getConnectedPerson, getConnectedPerson_1 } =require("./auth")
@autoInjectable()
export class ActivityController {
constructor() {
}
initRoutes(router: Router) {
router.get('/activities', [ getConnectedPerson, getConnectedPerson_1 ],async (req: Request, res: Response) => {});
}
}