尝试请求存储库时,TypeORM 未找到连接“默认”

aug*_*ral 5 orm node.js express typescript typeorm

我正在使用 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"
  }
}
Run Code Online (Sandbox Code Playgroud)

我的实体定义为:

{
  "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"
  }
}
Run Code Online (Sandbox Code Playgroud)

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

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;
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

aug*_*ral 3

说明:在建立连接之前,已调用快速路线!所以我选择使用动态导入。

我的应用程序主条目更改为 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"));
Run Code Online (Sandbox Code Playgroud)

这种方式就像一个魅力!