0

I have currently a post microservice, I would like to create a generic review microservice to plug it on every microservice who needs it later (ike products).

To do that, I tried something like this

Reviews microservice

Review entity

import { Directive, Field, GraphQLISODateTime, Int, ObjectType } from '@nestjs/graphql';

@ObjectType()
@Directive('@key(fields: "parentId")')
@Directive('@key(fields: "parentType")')
export class Review {
  @Field((type) => Int)
  id: number;

  @Field((type) => String)
  parentType: string;

  @Field((type) => Int)
  parentId: number;
}

Posts microservice

Post entity

import { Directive, Field, ID, Int, ObjectType } from '@nestjs/graphql';
import { Review } from 'src/review/review.entity';
import { User } from '../user/user.entity';

@ObjectType()
@Directive('@key(fields: "id")')
export class Post {
  @Field((type) => ID)
  id: number;

  @Field()
  title: string;

  @Field((type) => [Review])
  reviews: Review[];
}

Review entity in post microservice which extends Review entity from the review microservice

import { Directive, ObjectType, Field, Int } from '@nestjs/graphql';
import { Post } from '../post/post.entity';

@ObjectType()
@Directive('@key(fields: "parentId")')
@Directive('@key(fields: "parentType")')
export class Review {
  @Field((type) => Int)
  parentId: number;

  @Field((type) => String)
  parentType: string;

  @Field((type) => [Post])
  posts?: Post[];
}

In the post resolver, I put

import { Parent, ResolveField, Resolver } from '@nestjs/graphql';
import { Post } from './post.entity';
import { Review } from 'src/review/review.entity';

@Resolver((of) => Post)
export class PostResolver {

  @ResolveField('reviews', () => [Review])
  reviews(@Parent() post: Post) {
    return { __typename: 'Review', parentType: 'POST', parentId: post.id };
  }
  
}

to resolve the reviews.

And in the review microservice resolver:

import { Resolver, ResolveReference } from '@nestjs/graphql';
import { Review } from './review.entity';
import { ReviewService } from './review.service';

@Resolver((of) => Review)
export class ReviewResolver {
  constructor(private reviewsService: ReviewService) { }

  @ResolveReference()
  async resolveReference(reference: { __typename: string; parentId: number, parentType: string }) {
    return await this.reviewsService.findByParent(reference.parentId, reference.parentType)
  }

}

My problem is cause by a one to many relation ship.

The Posts->reviews resolver should return an array like [{ reviewId: ... }, { reviewId: ...}] but I want to send the parentType and the parentId to resolve this and I don't know how to do it.

Pompedup
  • 566
  • 2
  • 8

0 Answers0