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

Angular 6 and above: The use of ProvidedIn in a submodule is leading to a circular dependency issue

A resolve service is being implemented using the new providedIn attribute. This translations resolver is utilized in a protected module: import { Injectable } from '@angular/core'; import { Observable , pipe } from 'rxjs'; import { ...

What is the method for deducing the return type based on the parameter type in a generic function?

Check out this code snippet featuring conditional types: class X { public x: number; } class Y { public y: number; } type DataCategory = "x" | "y"; type TData<T extends DataCategory> = T extends "x" ? X : T extends "y" ? Y : ne ...

What techniques can be employed to dynamically modify Typescript's AST and run it while utilizing ts-node?

Below is my approach in executing a TypeScript file: npx ts-node ./tinker.ts In the file, I am reading and analyzing the Abstract Syntax Tree (AST) of another file named sample.ts, which contains the following line: console.log(123) The goal is to modify ...

The error message "TypeError: Unable to access the 'getFullWidth' property of an undefined value when using TSLint and TypeScript" was

I have been using Dan Wahlin's tutorials and online examples to set up Gulp and Typescript, but I am facing an issue with the tslint() function. The problem occurs in my code as follows: node_modules\tslint\lib\language\walker&bso ...

Commit to choosing an option from a dropdown menu using TypeScript

I just started learning about typescript and I have been trying to create a promise that will select options from a drop down based on text input. However, my current approach doesn't seem to be working as expected: case 'SelectFromList': ...

MongooseError: Timeout occurred after 10000ms while attempting to buffer the operation `users.findOne()` in a Next.js application

Encountering the "MongooseError: Operation users.findOne() Buffering Timed Out After 10000ms" error in my Next.js app while using Mongoose (^8.2.2) to connect to MongoDB. Using Next.js version 14+ Troubleshooting Steps: 1. Checked MongoDB connection str ...

Storing Buffer data in Postgres bytea using TypeORM is limited to only 10 bytes

I am encountering an issue while trying to store images in a postgres database, as only 10 bytes of data are being saved. Here is the sequence of events: Initially, I receive a base64 encoded string on my server. I then convert it into a Buffer, assign i ...

Potential Null Object in Typescript Mongoose: A Concern

Encountering an issue while attempting to locate my user model: Object is possibly 'null'. I would like to find a solution that does not involve suppressing TypeScript's strict rule. const { email, password } = req.body; const user = awai ...

By constantly subscribing to a Behavior Subject, updating the data, and then resetting the value, an endless loop is created

We have implemented a wizard functionality with lazy loading, consisting of a parent component and multiple child components. const routes: Routes = [ { path : '', component : WizardHomeComponent, canActivate: [HomeGuard], chil ...

Guide on retrieving an ArrayList() from intricate function in Angular

Simplicity is the key to my question. Let's take a look at this Angular method: getAllOrdersHeaders(){ this.getAllOrdersIds().subscribe(idList=>{ idList.forEach(id=>{ this.ordersCollection.doc(id).collection('metadata&apo ...

TypeScript implementation of internationalization message extraction in Create React App

I am facing challenges in getting i18n messages extracted, as defined by react-intl's defineMessages, to function correctly in a TypeScript-based CRA. Here are the methods I've attempted: Initial Approach I tried following this guide to make i ...

New Authentication: The sign-in feature will redirect to /api/auth/error

Currently implementing Google sign-in functionality on my Next.js 13 app using Next-auth. I have utilized the signIn() function as described in the documentation here. However, upon calling the signIn() function, I am unexpectedly redirected to http://loca ...

Error: The property you are trying to set is undefined and cannot

When I attempt to set a property 'error' that is undefined, I receive a TypeError. The problematic line of code looks like this: this.error = error.code; This issue arises in an Angular Reactive Form while making a call to a web service. Below i ...

What is the process for listening to custom events in Angular 4 components that have been loaded using routing?

In the app.component.html file <li routerLinkActive="active current"> <a [routerLink]="['/stats']"> Cluster stats </a> </li> When we route to the DisplayAllStatsComponent, how can we ...

Retrieve the observable value and store it in a variable within my Angular 13 component

Incorporating Angular 13, my service contains the following observable: private _user = new BehaviorSubject<ApplicationUser | null>(null); user$ = this._user.asObservable(); The ApplicationUser model is defined as: export interface ...

Can you guide me on implementing AWS SDK interfaces in TypeScript?

Attempting to create an SES TypeScript client using AWS definitions file downloaded from this link My approach so far: /// <reference path="../typings/aws-sdk.d.ts" /> var AWS = require('aws-sdk'); var ses:SES = new AWS.SES(); The error ...

Steps for eliminating a selection in the dropdown list:

I am dealing with a situation in which my select element gets new options added based on a specific input value. However, each time the value is changed, more options are appended to the select element instead of replacing the old ones. How can I remove th ...

Troubleshooting data binding problems when using an Array of Objects in MatTableDataSource within Angular

I am encountering an issue when trying to bind an array of objects data to a MatTableDataSource; the table displays empty results. I suspect there is a minor problem with data binding in my code snippet below. endPointsDataSource; endPointsLength; endP ...

What is the best approach to implementing React Hooks in Typescript when using Context?

I have implemented the following code snippet in my new React Native project to enable Dark Mode using TailwindCSS: import React, { createContext, useState, useContext } from 'react'; import { Appearance } from 'react-native'; import { ...

Angular is programmed to detect any alterations

Upon detecting changes, the NgOnChanges function triggers an infinite service call to update the table, a situation that currently perplexes me. Any assistance on this matter would be greatly appreciated. Many thanks. The TableMultiSortComponent functions ...