Skip to content

Instantly share code, notes, and snippets.

@f-huang
Last active November 24, 2020 20:54
Show Gist options
  • Save f-huang/76a2cc209f94ce6fa86c075a8b103d64 to your computer and use it in GitHub Desktop.
Save f-huang/76a2cc209f94ce6fa86c075a8b103d64 to your computer and use it in GitHub Desktop.
Example of entity typing
const invoiceRepository = queryRunner.manager.getRepository("invoice");
// or
const invoiceRepository = connection.getRepository<Invoice>("invoice");
import { Entity, PrimaryGeneratedColumn, ManyToOne, Column } from "typeorm";
import { Base } from "./base.entity.ts"
import { User } from "./user.entity.ts"
@Entity()
export class Invoice extends Base {
@ManyToOne((_type) => User)
importedBy!: User | undefined;
@Column({ nullable: false })
importedById!: User["id"];
}
// in module.ts
import { Module } from "@nestjs/common";
import { TypeOrmModule } from "@nestjs/typeorm";
import { InvoiceRepository } from "./invoice.repository.ts";
@Module({
imports: [TypeOrmModule.forFeature(InvoiceRepository)]
})
export class InvoiceModule {}
// in service.ts
import { Injectable } from "@nestjs/common";
import { InvoiceRepository } from "./invoice.repository.ts";
@Injectable()
export class InvoiceService {
constructor(private readonly invoiceRepository: InvoiceRepository) {}
}
import { Module } from "@nestjs/common";
import { TypeOrmModule } from "@nestjs/typeorm";
import { Invoice } from "./invoice.entity.ts";
@Module({
imports: [TypeOrmModule.forFeature(Invoice)]
})
export class InvoiceModule {}
import { Injectable } from "@nestjs/common";
import { InjectRepository, Repository, TypeOrmModule } from "@nestjs/typeorm";
import { Invoice } from "./invoice.entity.ts";
@Injectable()
export class InvoiceService {
constructor(@InjectRepository(Invoice) private readonly invoiceRepository: Repository<Invoice>) {}
}
import { Entity, PrimaryGeneratedColumn, ManyToOne, Column } from "typeorm";
import { Base } from "./base.entity.ts"
import { User } from "./user.entity.ts"
@Entity()
export class Invoice extends Base {
@ManyToOne((_type) => User)
importedBy!: User | undefined;
@Column({ nullable: false })
importedById!: User["id"];
}
interface UserWithImportedBy extends User {
importedBy: NonNullable<User["importedBy"]>;
}
const isUserWithImportedBy = (user: User): user is UserWithImportedBy => {
return user.importedBy != null;
}
//When querying in repository
public async findWithImportedBy(userId: User["id"]): Promise<UserWithImportedBy> {
const user = await this.findOneOrFail({
where: { id: userId },
relations: ["importedBy"],
});
if (!isUserWithImportedBy(user)) {
throw new TypeError(`Could not load relation importedBy for user ${userId}`);
}
return user;
}
import { BaseEntity, Entity, PrimaryGeneratedColumn } from "typeorm";
@Entity()
export class User extends BaseEntity {
@PrimaryGeneratedColumn("uuid")
id!: string & { __brand: "userId" };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment