简体   繁体   中英

Connection “default” was not found with TypeORM when trying to request a repository

I'm building an API with Express+TypeORM. This is my 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"
  }
}

And my entity is defined as:

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;
}

On my CreateUserUseCase, I call this repository like:

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

but I'm getting this error: [ERROR] 13:08:39 ConnectionNotFoundError: Connection "default" was not found.

No, connection is not being called after getCustomRepository as I call the file on the index of my server.

full github repo: https://github.com/Mdsp9070/mesha

Explanation: Express routes eas been called before connection being established. So I chose to use dynamic imports.

My application main entry was changed to typeorm/index.ts as:

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"));

That way worked like a charm!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM