尝试请求存储库时,未找到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"
}
}

我的实体定义为:

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

说明:在建立连接之前就调用了Express路由!所以我选择使用动态导入。

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

这种方式很有魅力!

相关内容

  • 没有找到相关文章

最新更新