In my current project, I am developing a microservice application. One of the services is a Node.js service designed as the 'data service', utilizing nestjs
, typeorm
, and type-graphql
models. The data service integrates the https://github.com/nestjs/graphql module to facilitate a graphql interface along with a playground.
Another service in the setup acts as a 'websocket service' where clients can subscribe for updates.
The communication between the 'data service' and 'websocket service' occurs via HTTP requests using the axios
library. These requests are then transmitted over websockets to the subscribed clients. However, there's an issue with how typeorm
models are handled during this process. When the typeorm
models are sent through axios, they are passed through JSON.stringify
. Unfortunately, this transformation includes certain fields that should be excluded and misses essential graphql schema metadata.
To address this problem, I aim to convert the models into a graphql payload similar to what the graphql playground generates. It appears that this graphql transformation happens within the nest/graphql
module, which serves as an abstraction layer for the underlying apollo/server
module.
Due to the complexity of the system, extracting isolated code examples may be challenging. Feel free to ask for any clarifications. As an illustration, consider the 'data service' example below involving a Profile
entity comprising profile.entity.ts
, profile.service.ts
, and profile.resolver.ts
.
The structure of the Profile
entity is as follows:
import { Field, Int, ObjectType } from 'type-graphql'
import { Column, Entity, ManyToOne, OneToMany } from 'typeorm'
import { BaseEntity } from '../common/base/base.entity'
@ObjectType()
@Entity()
export class Profile extends BaseEntity {
@Field()
@Column({ unique: true })
public username: string
@Field()
@Column()
public name: string
@Field({ nullable: true })
@Column({ nullable: true })
public birthday?: Date
// Relations
@Column()
public accountId: string
@ManyToOne(type => Account, account => account.profiles, { eager: true })
public account: Account
}
When referencing the Profile
entity, it is fetched and transmitted to the socket service as shown below:
const profileReference = await this.profileService.fetchById(profileId)
await this.socketService.sendHomeEvent(profileReference)
At this stage, we aim to serialize the profileReference
into a graphql response payload. Currently, the result of JSON.stringify
on profileReference
includes undesired fields like the Account
field, which ought to be omitted.