【问题标题】:Connection “default” was not found with TypeORM when trying to request a repository尝试请求存储库时未使用 TypeORM 找到连接“默认”
【发布时间】:2020-11-25 20:58:09
【问题描述】:

我正在使用 Express+TypeORM 构建 API。这是我的 ormconfig.json:

{
  "type": "postgres",
  "host": "localhost",
  "port": "5432",
  "username": "mdsp9070",
  "password": "mdsp9070",
  "database": "mesha",
  "entities": ["./src/entities/*.ts"],
  "migrations": ["./src/shared/infra/typeorm/migrations/*.ts"],
  "cli": {
    "migrationsDir": "./src/shared/infra/typeorm/migrations"
  }
}

而我的实体定义为:

import {
  Entity,
  Column,
  PrimaryGeneratedColumn,
} from "typeorm";

@Entity("users")
export class User {
  @PrimaryGeneratedColumn("uuid")
  id: string;

  @Column()
  name: string;

  @Column()
  email: string;

  @Column()
  birthYear: string;

  @Column()
  phoneNumber: string;

  @Column()
  photo: string;
}

在我的 CreateUserUseCase 中,我将此存储库称为:

...
private usersRepository: IUsersRepository;
  // receives ormRepository, that's users repository
  constructor() {
    this.usersRepository = getCustomRepository(UsersRepository);
  }
...

但我收到此错误:[ERROR] 13:08:39 ConnectionNotFoundError: Connection "default" was not found.

不,在我调用服务器索引上的文件时,在 getCustomRepository 之后没有调用连接。

完整的 github 仓库:https://github.com/Mdsp9070/mesha

【问题讨论】:

    标签: node.js typescript express orm typeorm


    【解决方案1】:

    解释:在建立连接之前调用了快速路由!所以我选择使用动态导入。

    我的应用程序主条目已更改为 typeorm/index.ts 为:

    import { createConnection } from "typeorm";
    import { AppError } from "../../errors/AppError";
    
    // finds ormconfig.json file and creates a connection. (magic!),
    // it could be set up manually with parameters
    // however an external file is the best practise
    createConnection()
      .then(() => {
         console.log("Connected to the database")
         import("../../http/server.ts")
      })
      .catch(() => new AppError("Unable to connect to the database"));
    

    这种方式就像一个魅力!

    【讨论】:

      猜你喜欢
      • 2018-09-22
      • 1970-01-01
      • 2019-09-08
      • 2020-09-23
      • 1970-01-01
      • 2020-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多