What is the process of converting a `typeorm` model into a GraphQL payload?

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.

Answer №1

If you have a GraphQL schema at your disposal, you have the ability to run any query on the server side. The library type-graphql provides a method called buildSchema that allows you to create your schema using resolver classes. More details can be found here.

import { buildSchema } from 'type-graphql'
import { graphql } from 'graphql'

const schema = await buildSchema({
  resolvers: [ProfileResolver],
})
const query = `
  # enter your query here
`
const root = {}
const context = {...}
const variables = {...}
const { data, errors } = await graphql(schema, query, root, context, variables)

Regrettably, it seems that nest.js does not expose the schema it generates internally, so you would need to handle that process manually.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Attempting to assign headers after they have already been sent to the client, causing a conflict in NEST

After connecting Redis to my session store, I am encountering an error after the first request, causing subsequent requests to fail. Error: Cannot set headers after they are sent to the client at new NodeError (node:internal/errors:371:5) at Serv ...

What is the reason for not hashing the password in this system?

My password hashing code using Argon2 is shown below: import { ForbiddenException, Injectable } from '@nestjs/common'; import { PrismaService } from 'src/prisma/prisma.service'; import { AuthDto } from './dto'; import * as arg ...

Why is the dateclick event in PrimeNG's FullCalendar not being emitted when clicking on a date? What is the best way to handle click events on specific dates within the calendar?

I am new to using Angular and PrimeNG, and I am facing challenges while trying to implement the FullCalendar component. The specific component I am referring to can be found here: The issue arises when I attempt to trigger an event when a user clicks on a ...

Why does the page not work when I enter a certain URL with an ID parameter, and instead displays the error message "Uncaught ReferenceError: System is not defined"?

This is my "app.routing.ts": import {provideRouter, RouterConfig} from "@angular/router"; import {DashboardComponent} from "./dashboard.component"; import {HeroesComponent} from "./heroes.component"; import {HeroDetailsComponent} from "./hero-details.com ...

Accessing information necessitates two separate subscriptions

I am posting this inquiry in order to enhance my understanding. Below is an excerpt from my service: export class HomeService { private generalstatistics = new ReplaySubject<object>(); constructor( private http: HttpClient ) { this ...

Retrieving the final element from a TypeScript JSON array

I am trying to retrieve the value of the "id" property from the last element in an array of JSON objects. While I can easily find each element by id, I specifically need to extract the value of the last "id" in the array of JSON objects. In the example p ...

Encountering difficulties in loading environment variables while starting the server using typescript in combination with node.js

My node.js server project, created using typescript, has the following structure: |--node_modules |--server .env |-- build |-- src |-- database |-- controllers |-- models |-- routes |-- utils |-- app. ...

Discover the process of translating words within app.routing.module.ts in Angular

Having some trouble with my Angular routing module and ngx-translate languages. I'm trying to retrieve words from the languages in this module, but the code I've attempted isn't working: import { NgModule } from '@angular/core'; im ...

Ways to retrieve a Class Level Variable within the onCellValueChanged function in agGrid

Exploring Angular with Typescript for the first time. I'm trying to access Class Level Variables within the onCellValueChanged event of agGrid, but encountering the following error: Cannot read property 'updateDict' of undefined Here&apo ...

Tips for injecting scripts into the head tag after an Angular component has been loaded

Currently, I am facing an issue with a script tag containing a Skype web control CDN. The script has been placed in the head section of my index.html file, but it is being called before the component that needs it has finished loading. Does anyone have a ...

React/Typescript: The object might be null

I am currently converting a React component to TypeScript. The component is making an API call, and although I believe my interfaces are correctly set up, I seem to be passing the types incorrectly. How can I resolve the two errors in the Parent componen ...

What could be causing my React Redux state to not trigger a re-render?

Having trouble with my redux state not triggering a re-render when using a selector. I'm new to react-redux and typescript, and despite following advice online about returning a new object from the reducer, my object is still not re-rendering even tho ...

Is it possible for me to incorporate a portion of the interface?

Is it possible to partially implement an interface? export interface AuthorizeUser { RQBody: { login: string; password: string; }; RSBody: { authorizationResult: AuthorizationResult; }; }; class AuthorizeUserRQBody implements Authorize ...

The various types of Angular 2 FormBuilders

As I delved into learning Angular 2, I initially came across ngModel, and later discovered FormGroup/FormBuilder which seemed more suitable for handling complex forms. However, one downside that caught my attention was that by using FormBuilder, we sacrifi ...

Creating a dynamic array in an Angular 2 service for real-time changes monitoring by a component

I am facing an issue where my NotificationsBellComponent is not receiving changes to the array in the service even though the _LocalStorageService is returning data correctly. Q) How can I ensure that my component receives updates when the service collect ...

Exploring the use of Jest for testing delete actions with Redux

I've been working on testing my React + Redux application, specifically trying to figure out how to test my reducer that removes an object from the global state with a click. Here's the code for my reducer: const PeopleReducer = (state:any = init ...

Guide on passing a customized component to the title property in Material-UI tooltip

I want to customize a Tooltip component by passing a custom component like the image shown in the link. https://i.stack.imgur.com/QkKcx.png Initially, I used Popover once, but now I prefer Tooltip because of its arrow feature. Currently, I am using Reac ...

Creating TypeScript atom packages

Has anyone successfully implemented this before? I couldn't locate any assistance for it. If someone could provide references to documentation or existing code, that would be great. I know that Atom runs on Node and that there is a TypeScript compil ...

How do React Native proxies differ from vanilla React proxies in their functionality?

Trying to retrieve data from an API running locally on port 5000 of my device, I recalled setting the proxy in package.json when working on React web applications: "proxy": "https://localhost:5000" Attempting to fetch information f ...

Receiving distinct data from server with Ionic 2 promises

Utilizing ionic 2 RC0 with promises to retrieve data from the server, I am facing an issue where I consistently receive the same data in every request due to the nature of promises. Hence, my question is: How can I tackle this problem and ensure differen ...