NodeJS Express OOP + Typescript问题:用户服务中的类型错误?

mfpqipee  于 2023-10-17  发布在  Node.js
关注(0)|答案(1)|浏览(82)

我目前正在开发一个完整的身份验证应用程序与MERN堆栈,所有在 typescript 。但我遇到了一些问题(类型错误)与我的userController文件。
这是我的路由文件:

import { validate } from "../middlewares/validateMiddleware";
import { createUserSchema } from "../schemas/user.schema";
import { UserController } from "../controllers/user.controller";

function routes(app: Express) {
  app.get("/", (req: Request, res: Response) => {
    res.json({ message: "Hello World" });
  });

  // Local User Authentication and Authorization
  const user = new UserController()
  app.post("/auth/local/signup", validate(createUserSchema), user.createNewUser)
}

export { routes };

用户控制器档桉

import { Request, Response } from "express";
import { UserService } from "../services/user.service";
import { createUserInput } from "../schemas/user.schema";
import { CREATED, FORBIDDEN } from "http-status";
import log from "../utils/logger";
import { JwtStrategy } from "../auth/jwt";
export class UserController {
  private userService: UserService;
  private jwtStrategy: JwtStrategy;

  constructor() {
    this.userService = new UserService();
    this.jwtStrategy = new JwtStrategy();
  }

  public async createNewUser(
    req: Request<{}, {}, createUserInput["body"]>,
    res: Response
  ) {
    try {
      const user = await this.userService.createNewUser(req.body);
      return res.status(CREATED).json(user);
    } catch (error) {
      log.error(error);
      return res.status(FORBIDDEN).send(error);
    }
  }

  public async authenticateUser() {}
}

用户服务文件:

import { User, UserInput } from "../models/user.models";
export class UserService {
  private model: typeof User;

  constructor() {
    this.model = User;
  }

  public async createNewUser(dto: UserInput) {
    try {
      return await this.model.create(dto);
    } catch (error: any) {
      throw new Error(error);
    }
  }
}

但我总是得到错误:TypeError:无法读取未定义的属性(阅读“userService”)
有什么问题吗?

"type": "TypeError",
      "message": "Cannot read properties of undefined (reading 'userService')",
"stack":
          TypeError: Cannot read properties of undefined (reading 'userService')
              at /Desktop/Practices/Ts/Mern-Auth/src/controllers/user.controller.ts:21:31
}

任何帮助将不胜感激,我是相对新的使用快递。

ttvkxqim

ttvkxqim1#

您丢失了this上下文
你有几个选择
箭头函数

app.post("/auth/local/signup", validate(createUserSchema), (...args) => user.createNewUser(...args))

结合

app.post("/auth/local/signup", validate(createUserSchema), user.createNewUser.bind(user))

在构造函数中绑定

constructor() {
  this.userService = new UserService();
  this.jwtStrategy = new JwtStrategy();
  this.createNewUser = createNewUser;
}

相关问题