无法从控制器ExpressJS + Typescript返回next()

时间:2019-09-07 04:17:20

标签: typescript express

我正在尝试使用Typescript开发新的REST API。 我有一个看起来像这样的控制器。

export default class AuthController {
  static async getRegisterController(
    req: Request,
    res: Response,
    next: NextFunction,
  ): Promise<Response> {
    const vendorData: RegisterInput = {
      name: req.body.name,
      email: req.body.email,
      password: req.body.password,
      contactNo: req.body.contactNo,
      referralCode: req.body.referralCode,
    };

    const userWithEmail = await VendorData.getVendorWithEmail(vendorData.email);
    if (userWithEmail) {
      return next(new ConflictException('User with email already exists'));
    }

    const hashedPassword = await hashPassword(vendorData.password);
    vendorData.password = hashedPassword;

    const savedVendor = await VendorData.insertVendor(vendorData);
    const successResult = Result.success(savedVendor);
    return new ApiResponse(res, successResult).apiSuccess();
  }
}

但是,由于返回类型与控制器的返回类型冲突,因此我无法在此处返回next()函数。异步函数始终返回promise,但是next函数返回的类型为void。但是,我确实需要下一个函数将错误传播到全局错误处理中间件,以发送适当的响应。

编辑: 我只想在致电next(err);之后停止执行。 return;之后的next(err)无效,因为return;从异步函数返回Promise<undefined>,该函数在这里也不起作用。

1 个答案:

答案 0 :(得分:0)

我现在找到的解决方案是让您的控制器返回Promise<Response | undefined>。由于路由器不关心控制器的返回类型,所以这是可能的。