尝试请求存储库时,未使用TypeORM找到连接“Default” [英] Connection “default” was not found with TypeORM when trying to request a repository

查看:25
本文介绍了尝试请求存储库时,未使用TypeORM找到连接“Default”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Express+TypeORM构建一个API。这是我的ormfig.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

推荐答案

说明:快速路由在建立连接之前已被调用!因此,我选择使用动态导入。

我的应用程序主条目更改为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"));

这样做真是妙极了!

这篇关于尝试请求存储库时,未使用TypeORM找到连接“Default”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆