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. , etc.

The Base Entity

import {
} from 'typeorm';

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

    type: 'timestamptz',
    update: false,
  createdAt!: Date;

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

export default class User extends CustomBaseEntity {
  @Column({ unique: true })
  @Field(() => String, { description: `User's email address` })
  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. Required fields are marked *