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

Having Trouble Setting Default Value in React Typescript MUI Autocomplete

I am encountering an issue with my React and Typescript code using MUI with the use of hook form. The problem arises when trying to set a default value for an Autocomplete field, resulting in the following error message: I am seeking assistance in resolvi ...

Is there a way to clear the selected date in a date picker while using MatDateRangeSelectionStrategy?

Recently, I was experimenting with the date picker feature of Angular Material and stumbled upon this particular example After implementing this example with my own logic, everything seemed to be working perfectly fine except for one issue. The dates were ...

Separating the time and date into distinct variables offers flexibility in how they

Struggling with formatting time in a web component using TypeScript and React. The code below is working: new Date(myDate) .toLocaleTimeString( 'en-US', { weekday: 'short', year: 'numeric', month: 'short', ...

Invoke a function and assign it to an export variable

I have a query regarding a file containing an export constant that is utilized to construct a navigation bar in CoreUI. However, I am exploring methods to generate dynamic JSON data within other Components or the same file and then inject it into the exp ...

Implement a function for templateURL in AngularJS using Typescript programming language

Here is my current setup: export class MyComponent implements ng.IComponentOptions { public static componentName: string = "myViewer"; public bindings: any; public controller: any; public controllerAs: any; public templateUrl: string; ...

Error: Unable to locate namespace 'google' in TypeScript

I am currently working on an angular-cli project. ~root~/src/typings.json { "globalDevDependencies": { "angular-protractor": "registry:dt/angular-protractor#1.5.0+20160425143459", "jasmine": "registry:dt/jasmine#2.2.0+20160621224255", "sele ...

How come the information I receive when I subscribe always seems to mysteriously disappear afterwards?

I've been working on a web project using Angular, and I've run into an issue with my code that's been causing problems for a while now. The problem lies in fetching data from a server that contains translations: getTranslations(): Observab ...

Can you explain the distinction between declaring a map in TypeScript using these two methods?

When working in TypeScript, there are two different ways to declare a map. The first way is like this: {[key:number]string} This shows an example of creating a map with keys as numbers and values as strings. However, you can also define a map like this: M ...

What is the best way to include a variable or literal as a value in styled components?

When it comes to managing various use cases, I always rely on props. However, I am currently facing a challenge in changing the border color of a styled input during its focus state. Is there a way to utilize props for this specific scenario? Despite my f ...

The object literal can only define properties that are already known, and 'data' is not found in the type 'PromiseLike<T>'

When making a request to a server with my method, the data returned can vary in shape based on the URL. Previously, I would cast the expected interface into the returned object like this: const data = Promise.resolve(makeSignedRequest(requestParamete ...

Setting up tsconfig.json to enable support for either string literals or string templates involves adjusting the compiler options

After utilizing swagger codgen with the typescript-aurelia template to create API code, I noticed that a significant amount of string literals were being used in the resulting code. Despite encountering errors when running the transpiler tsc from the comma ...

Unexpected expression after upgrading to TypeScript 3.7.2 was encountered, file expected.ts(1109)

After updating TypeScript from version 3.6.x to 3.7.2, I started using optional chaining in my code. However, I encountered a peculiar error. Error message: Expression expected.ts(1109) This error appeared in both my (vim, VSCode) IDE, even though the ...

Enhance the express request to include the user parameter for the passport

I am currently utilizing Passport for authentication in an Express application. This authenticates the user and sets it on the Express response. As I am using TypeScript, trying to set the request type to Request in the route definitions results in an erro ...

Accessing BIM Components: Identifying Global and Express IDs through Selection

As I delve into the task of handpicking specific elements from the intricate web of an IFC model, my approach involves utilizing a SimpleRayCaster to cast a ray onto the object with relative success. The challenge lies in identifying the exact entity inter ...

Typescript libraries built specifically for unique custom classes

I am currently exploring the most effective method for creating a class library in Typescript and deploying it to NPM along with a definitions file. The classes within the library serve as models that are utilized by multiple RESTful services. Some of the ...

Encountering a 404 error when importing http/server in deno

The file named index.ts is located below import { serve } from "https://deno.land/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b0c3c4d4f0809e8186869e80">[email protected]</a>/http/server.ts"; function ...

Create type declarations using the Typescript compiler by running the command:

After generating my definition file ".d.ts" using tsc --declaration or setting declaration as true in the tsconfig.json, I noticed that the generated files are missing declare module "mymodule" {... } This appears to be causing issues with "tslint" which ...

The property 'filter' is not recognized on the 'Object' type. An attempt to filter the response was made

Trying to fetch data from a JSON file that matches the player's name in the URL, such as localhost:4200/players/Febiven, should only retrieve information about Febiven. The code is written in Angular 6. The current code snippet is as follows: player ...

A step-by-step guide on leveraging swagger-autogen in TypeScript applications

Is it possible to integrate the swagger-autogen module into a Typescript project? I have attempted multiple methods, but have been unsuccessful. The error message "Failed" keeps appearing when using a swagger.js file: const swaggerAutogen = require("swagge ...

Saving JSON data in a variable or array post subscription: What's the preferred method?

I have been receiving JSON files in the following format: {streetAddress: "Kosterlijand 20", postalCode: "3980", city: "Bunnik", country: "Netherlands"} Although the length of these files varies, the structure always remains the same: {key: "string valu ...