You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

创建REST API时,如何在路由中正确调用Interface类?

问题分析与解决方案

1. 先修复实现类的逻辑问题

你的AuthenticationServiceImpl里的signUp方法逻辑有误:Firebase Admin的createUser方法在用户已存在时会直接抛出异常,不会返回用户对象,所以你写的if (existingUser)判断永远不会触发。正确的写法是捕获Firebase的原生错误,按需转换:

import { AuthenticationService } from "../application/authentication_repository";
import * as admin from "firebase-admin";

export class AuthenticationServiceImpl implements AuthenticationService {
  async signUp(email: string, password: string): Promise<void> {
    const auth = admin.auth();
    try {
      await auth.createUser({
        email,
        password,
        emailVerified: false,
        disabled: false,
      });
    } catch (error: any) {
      // 匹配Firebase用户已存在的错误码
      if (error.code === "auth/email-already-exists") {
        throw new Error("User already exists");
      }
      // 其他错误直接抛出
      throw error;
    }
  }
}

2. 路由中正确调用接口

TypeScript的接口只是类型约束,不能直接实例化。你必须在路由中创建实现类的实例,再通过接口类型约束它(可选,但符合依赖倒置原则):

示例Express路由代码

import { Router } from "express";
import { AuthenticationService } from "../application/authentication_repository";
import { AuthenticationServiceImpl } from "../services/authentication_service_impl";

const router = Router();

// 实例化实现类,用接口做类型约束
const authService: AuthenticationService = new AuthenticationServiceImpl();

// 注册接口路由
router.post("/signup", async (req, res) => {
  try {
    const { email, password } = req.body;
    await authService.signUp(email, password);
    res.status(201).json({ message: "User created successfully" });
  } catch (error: any) {
    res.status(400).json({ error: error.message });
  }
});

export default router;

3. 额外排查点

如果仍报错,检查以下内容:

  • 确认Firebase Admin已在项目启动时完成初始化(调用admin.initializeApp())
  • 核对文件导入路径,确保AuthenticationService和AuthenticationServiceImpl的路径正确
  • 若使用Express,需配置express.json()中间件解析JSON请求体,否则无法获取req.body中的参数

内容的提问来源于stack exchange,提问作者Gbenga B Ayannuga

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 05:22:43