When defining a GraphQL Object type in NestJS, an error was encountered: "The schema must have unique type names, but there are multiple types named 'Address'."

Utilizing Nestjs and GraphQL for backend development, encountered an error when defining a model class (code first): Schema must contain uniquely named types but contains multiple types named "Address". Below is the Reader model file example:

@ObjectType()
class Address {
  @Field()
  homeAddress: string;
  @Field()
  province: string;
  @Field()
  postcode: string;
}

@ObjectType()
class FavouriteBook {
  @Field()
  bookID: string;
  @Field()
  createDate: Date;
}

@ObjectType()
export class ReaderProfile {
  @Field()
  _id: string;
  @Field()
  firstName: string;
  @Field()
  lastName: string;
  @Field()
  gender: string;
  @Field()
  birthday: Date;
  @Field()
  address?: Address;
  @Field()
  postcode: string;
  @Field(type => Int)
  readTimes: number;
  @Field(type => Int)
  readDuration: number;
  @Field(type => Int)
  score: number;
  @Field()
  securityQuestion: string;
  @Field()
  securityAnswer: string;
}

@ObjectType()
export class ReaderReadHistory {
  @Field()
  _id: string;
  @Field()
  bookID: string;
  @Field(type => Int)
  currentPage: number;
  @Field()
  startTime: Date;
  @Field()
  lastReadTime: Date;
  @Field(type => Int)
  readTimes: number;
  @Field(type => Int)
  readDuration: number;
}

@ObjectType()
export class Reader {
  @Field()
  _id: string;
  @Field()
  username: string;
  @Field()
  password: string;
  @Field()
  email: string;
  @Field()
  registerDate: Date;
  @Field()
  isActive: boolean;
  @Field({ nullable: true })
  currentRefreshToken?: string;
  @Field(type => ReaderProfile)
  readerProfile: ReaderProfile;
  @Field(type => [FavouriteBook])
  favouriteBook: FavouriteBook[];
  @Field(type => [ReaderReadHistory])
  readHistory: ReaderReadHistory[];
}

This excerpt details the GraghQL configuration in the app module (code first)

GraphQLModule.forRoot({
      autoSchemaFile: join(process.cwd(), 'src/schema.gql'),
      cors: false,
      sortSchema: true,
      context: ({ req }) => ({ req }),
    }),

Seeking guidance on resolving this issue. Your help is greatly appreciated!

Answer №1

After much searching, I couldn't find a solution using the code first approach. So, I decided to switch to schema first coding, and it worked perfectly as expected. For anyone facing the same issue with the code first method, I recommend giving schema first a try. I also noticed that schema first has less boilerplate code compared to code first. Additionally, you can use a separate auto-generate function (see below) to generate all TypeScript interfaces in one file, which is extremely useful.

import { GraphQLDefinitionsFactory } from '@nestjs/graphql';
import { join } from 'path';

const definitionsFactory = new GraphQLDefinitionsFactory();
definitionsFactory.generate({
  typePaths: ['./src/**/*.graphql'],
  path: join(process.cwd(), 'src/graphql.ts'),
});

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

Exploring the power of Node JS with Promise.all and forEach within a nested array

When working on a Node app with typescript, I encountered the need to iterate through an array while calling an asynchronous function inside the loop to fetch information about related items for each item in the array. The function is called for each relat ...

When using Playwright, there may arise a requirement to reuse a specific UUID that has been defined in one test within another

I have two separate tests running in parallel, each creating a different company in my test environment. However, I need to access the uuid of both companies in later tests. I am looking for a way to store these uuids so they can be used across all subseq ...

Error in Directive: NgControl Provider Not Found

I encountered an issue with my Directive while attempting to inject 'NgControl' and received a 'No provider for NgControl' error. Here is the structure of my File Directory: app folder |--directives folder |--myDirec ...

Utilizing files that do not have the extension '.ts' or '.tsx' within the 'ts_library' as dependencies

My current challenge involves importing a JSON file from TypeScript while utilizing the resolveJsonModule flag in my tsconfig. The problem lies in how I can provide this JSON file to ts_library since it seems unable to locate the file. This issue extends t ...

What could be causing TypeScript to not locate my custom package?

I decided to create a fork of an existing package and released it with a new, distinct name: https://www.npmjs.com/package/feed-media-fork After tagging a new version, setting up a release on GitHub, and running yarn add feed-media-fork or the equivalent ...

Has anyone tried integrating Reveal JS with Angular 8?

Encountering a problem with the integration of Reveal JS in an Angular component. Despite being initialized after DOM processing, it is not displaying anything. What is the appropriate time to initialize the reveal library? Is there a way to incorporate ...

Ionic app experiencing a CORS dilemma post-build

Using Ionic 3, I have written a provider code to fetch data from an API endpoint hosted on an HTTPS server. For example, my endpoint is located at . Below is the code for my provider: // Provider Class Function load(){ if(this.data){ return Pro ...

WebStorm is not implementing the exclude option as specified in the tsconfig.json file

Is there a way to exclude a directory from TypeScript compilation in WebStorm? Despite specifying the exclusion in the tsconfig.json file, it seems that WebStorm doesn't respect the setting and compiles everything in the root directory. However, runn ...

The React type '{ hasInputs: boolean; bg: string; }' cannot be assigned to the type 'IntrinsicAttributes & boolean'

I recently started learning react and encountered an error while passing a boolean value as a prop to a component. The complete error message is: Type '{ hasInputs: boolean; bg: string; }' is not assignable to type 'IntrinsicAttributes & ...

Module not found when attempting to import a newly created TypeScript module

A fresh Typescript project called puppeteer-jquery has just been released on the NPM registry. The code is functioning perfectly well. However, when attempting to integrate it into another project: npm install puppeteer-jquery and trying to import it lik ...

Hovering over the Chart.js tooltip does not display the labels as expected

How can I show the numberValue value as a label on hover over the bar chart? Despite trying various methods, nothing seems to appear when hovering over the bars. Below is the code snippet: getBarChart() { this.http.get(API).subscribe({ next: (d ...

Using ngModel to retrieve and display only the month, year, and date

Currently, I am working with an interface named Person which includes fields such as name, last name, birthday, and others. However, I am facing a confusion when it comes to the person's birthday format, as it contains some additional letters at the e ...

Issue: The UserComponent is attempting to set the property 'id' of an undefined object, resulting in an error

An error has occurred indicating that the property 'id' cannot be set as it is undefined in the UserComponent file of user.component.ts. Here is the TypeScript code: import { Component, OnInit } from "@angular/core"; import { ActivatedRoute, Rou ...

What is the best way to first identify and listen for changes in a form

In Angular, there are reactive forms that allow you to track changes in both the complete form and specific fields: this.filterForm.valueChanges.subscribe(() => { }); this.filterForm.controls["name"].valueChanges.subscribe(selectedValue => { }); ...

ESLint warning: Potentially risky assignment of an undetermined data type and hazardous invocation of an undetermined data type value

Review this test code: import { isHtmlLinkDescriptor } from '@remix-run/react/links' import invariant from 'tiny-invariant' import { links } from '~/root' it('should return a rel=stylesheet', () => { const resp ...

The Date object in Typescript is represented as a string

My typescript interface includes a variable called start, which is typed as Date | null. This data is retrieved from a dotnet API that returns a DateTime object. The issue arises when the start variable is passed through a function in Date-fns, causing a R ...

Creating a report file based on Typescript type checking results

Is there a way or third-party library that can help generate a report file (such as .html, .csv, etc.) after running TypeScript typechecking with tsc? I need to create a report on typechecking in my Next.js Project, capturing all the output from tsc --noE ...

Issues with the functionality of Angular 5 EventEmitter

I have been trying to call a function from the Parent Component in the Child Component, and here is how I implemented it: project-form.component.ts @Component({ selector: 'app-project-form', templateUrl: './project-form.component.html& ...

Modify information in formArray

Let's take a look at this setup I have: Model: export class MapDetailModel{ id: number; lat: number; lon: number; alt: number; long: number; angle: number; distance?: number; pendenza?: number; } Html: <div clas ...

Exploring the possibilities of ZMQ_XPUB_MANUAL in action with zeromq.js

I'm currently in the process of setting up a pub/sub broker using ZeroMQ, and I want to ensure that clients are only able to subscribe to authorized prefixes. While researching this topic, I came across a helpful tutorial that discusses achieving a si ...