Use entities defined in external package
See original GitHub issueIssue type:
[x] question
Database system/driver:
[x] postgres
TypeORM version:
[x] latest
Hi, I have an app where I’m creating connection in the following way:
import { entities } from "@mypackage/entities";
(async function() {
const connectionOptionsReader = new TypeORM.ConnectionOptionsReader();
const connectionOptions = (await connectionOptionsReader.all())[0];
connectionOptions.entities.push(...entities);
await TypeORM.createConnection(connectionOptions);
/* ... */
})();
As you can see, I’m loading connectionOptions from config file (that part works properly). And later I’m adding entities from the @mypackage/models
to the connectionOptions.entities
list. I’ve checked the connectionOptions and it looks good. However, when I try to load something from the database I get the Context creation failed: No repository for \"User\" was found. Looks like this entity is not registered in current \"default\" connection?
error.
Now, going to the package. It’s pretty straightforward.
import { Column, Entity, PrimaryGeneratedColumn } from "typeorm";
@Entity({ name: "users" })
class User {
@PrimaryGeneratedColumn({ type: "bigint" })
readonly id: number;
@Column({
name: "first_name",
type: "character varying",
length: 50
})
firstName: string;
@Column({
name: "last_name",
type: "character varying",
length: 50
})
lastName: string;
}
const entities = [User];
export { entities };
I’m building this package with TS. Everything is built properly. I’ve read in some issue regarding Nest that this kind of operation is possible. But I’m probably missing something. Could you help? I haven’t found anything in docs
Issue Analytics
- State:
- Created 4 years ago
- Comments:6 (1 by maintainers)
Hi @lukejagodzinski , Do you use nestjs or only node? I currently have an issue with importing external entities, I tried to create a package at @app/common with all my entities decorated with type-orm, then sym link this package to two other packages using lerna. The issue was that when I tried to use the repository in the other packages by importing the class from @app/common, I got the “No repository for <Entity name> was found.”. Would you mind sharing the architecture of your application please? Thanks a lot,
@tdnghia98 , hi man i was having same kind a problem , Here is my solution ! I tested as below : first way
Second way (suggested)
Thanks