Skip to content

[Startup MVP recipes #13] Quick glance: Inheritance of TypeOrm’s Entity and GraphQL’s Object

This is a quick tutorial and code pointer sharing of how to create a reusable base entity that contains common columns. There are more advanced topics on this e.g. https://jczhang.com/2022/07/29/startup-mvp-recipes-6-graphql-resolver-inheritance-and-a-crud-base-resolver-with-generics/ , etc.

The Base Entity

import {
  BaseEntity,
  Column,
  CreateDateColumn,
  DeleteDateColumn,
  PrimaryGeneratedColumn,
  UpdateDateColumn,
} from 'typeorm';

@ObjectType({ isAbstract: true })
export abstract class CustomBaseEntity extends BaseEntity {
  @Field(() => ID, { description: 'Auto-increment int ID' })
  @PrimaryGeneratedColumn()
  id!: number;

  @CreateDateColumn({
    type: 'timestamptz',
    update: false,
  })
  createdAt!: Date;

  @UpdateDateColumn({
    type: 'timestamptz',
  })
  updatedAt!: Date;
}

The abstract modifier is used to mark it as an abstract class and avoid direct instantiation and usage. @Entity() is omitted to avoid create this entity in actual table. @ObjectType({ isAbstract: true }) is used to avoid creating GraphQL ObjectType for it.

Inherited Class

An example of inheriting from CustomBaseEntity

import { Field, ObjectType } from '@nestjs/graphql';
import { IsEmail } from 'class-validator';
import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';

@ObjectType()
@Entity()
export default class User extends CustomBaseEntity {
  @Column({ unique: true })
  @Field(() => String, { description: `User's email address` })
  @IsEmail()
  email: string;
}

Now the User Entity will be equipped with classic common fields like id, createdAt, updatedAt automatically!

Leave a Reply

Your email address will not be published.