Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using serializr with TypeORM #183

Open
krishnabrq opened this issue Dec 28, 2023 · 0 comments
Open

Using serializr with TypeORM #183

krishnabrq opened this issue Dec 28, 2023 · 0 comments

Comments

@krishnabrq
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant