Skip to content

Using serializr with TypeORM #183

Open
@krishnabrq

Description

@krishnabrq

I am working on a Express.js backend and using TypeORM for DB operations. As in TypeORM we Entity classes for DB tables, I used the same classes for (de)serialization purpose too. I am using serializr for this. For example:

import { Column, Entity, ManyToOne, OneToMany, PrimaryGeneratedColumn } from "typeorm";

// The User class is a TypeORM entity as well as be used for (de)serialization
@Entity({ name: "users" })
class User {
  @serializable
  @PrimaryGeneratedColumn()
  id: number;

  @serializable
  @Column({ nullable: false })
  name: string;
}

But the issue occurs when I have something like following:

@Entity({ name: "posts" })
class Post {
  @serializable
  @PrimaryGeneratedColumn()
  id: number;

  @serializable
  @Column({ nullable: false })
  desc: string;

  @serializable(list(object(Comment)))
  @OneToMany(() => Comment, (c) => c.post, {
    nullable: true,
  })
  comments: Comment[];
}

@Entity({ name: "comments" })
class Comment {
  @serializable
  @PrimaryGeneratedColumn()
  id: number;

  @serializable
  @Column({ nullable: false })
  desc: string;

  @serializable(object(Post))
  @ManyToOne(() => Post, (p) => p.comments, {
    nullable: false,
  })
  post: Post;
}

This creates a circular dependency and getting the following error from serializr:

Error: [serializr] No modelSchema provided. If you are importing it from another file be aware of circular dependencies.

I found about identifier() and reference() in serializr documentation and tried is as following:

@Entity({ name: "posts" })
class Post {
  @serializable
  @PrimaryGeneratedColumn()
  id: number;

  @serializable
  @Column({ nullable: false })
  desc: string;

  @serializable(list(reference(Comment)))
  @OneToMany(() => Comment, (c) => c.post, {
    nullable: true,
  })
  comments: Comment[];
}

@Entity({ name: "comments" })
class Comment {
  @serializable(identifier())
  @PrimaryGeneratedColumn()
  id: number;

  @serializable
  @Column({ nullable: false })
  desc: string;

  @ManyToOne(() => Post, (p) => p.comments, {
    nullable: false,
  })
  post: Post;
}

But still getting the same error. Please suggest me any fix for this.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions