Issue with GraphQL and TypeORM – Fetching Products with Images

Issue with GraphQL and TypeORM – Fetching Products with Images


0

I’m working on a GraphQL API using TypeORM as the ORM to interact with my PostgreSQL database. I’m currently facing an issue when trying to fetch products along with their associated images using GraphQL queries.

I have two tables: products and images. Each product can have multiple images associated with it. The images table has a foreign key product_id that relates to the id column of the products table.

Here’s my simplified GraphQL and TypeORM setup:

  1. Product Entity:
@Entity()
export class Product extends BaseEntity {
  @PrimaryGeneratedColumn()
  id!: number;

  // Other columns...

  @OneToMany(() => ProductImage, (image) => image.product)
  images: ProductImage[];
}
  1. ProductImage Entity:
@Entity()
export class ProductImage extends BaseEntity {
  @PrimaryGeneratedColumn()
  id!: number;

  @Column()
  url!: string;

  @Column()
  productId!: number;
  @ManyToOne(() => Product, (product) => product.images)
  product: Product;
}
  1. GraphQL Query:
extendType({
  type: 'Product',
  definition(t) {
    t.field('images', {
      type: 'ProductImage',
      list: true,
      resolve(parent, _args, _context, _info): Promise<ProductImage[] | null> {
        // Issue: The images are not being fetched correctly for the product.
        return ProductImage.find({ where: { productId: parent.id } });
      },
    });
  },
});

My problem is that when I try to fetch products along with their images using the GraphQL query, I’m not getting the expected results. The images field is returning null, and I’m not sure what’s causing this issue.

Am I missing something in my GraphQL query or TypeORM setup? Is there a better way to fetch products and their associated images using GraphQL and TypeORM?

Any help or guidance on this issue would be greatly appreciated. Thank you!

Share
Improve this question


Load 6 more related questions


Show fewer related questions

0

Reset to default



Leave a Reply

Your email address will not be published. Required fields are marked *