NESTJS Alert: Unable to identify a GraphQL output type for the specified entity. Ensure that your class has the correct decorator applied to it

I am currently in the process of developing a NestJS API utilizing GraphQL, PostgreSQL, and Docker. However, I encountered an error when attempting to build my API:

/app/node_modules/@nestjs/graphql/dist/schema-builder/factories/output-type.factory.js:19
stocks-api-api-1                

throw new cannot_determine_output_type_error_1.CannotDetermineOutputTypeError(hostType);

stocks-api-api-1 Error: Cannot determine a GraphQL output type for the "createStock". Make sure your class is decorated with an appropriate decorator.

Below is a snippet of the code causing the issue:

create-stock.dto:

import { Field, InputType, ObjectType } from "@nestjs/graphql";
import { IsNotEmpty } from "class-validator";

@InputType()
export class CreateStockDto {
    @IsNotEmpty()
    @Field()
    ticker: string;

    @IsNotEmpty()
    @Field()
    price : number;

    @IsNotEmpty()
    @Field()
    timestamp : Date;
}

stocks.entity.ts:

import { Field, ObjectType, ID } from "type-graphql";
import { Entity, PrimaryGeneratedColumn, Column, BaseEntity } from "typeorm";

@Entity()
@ObjectType()
export class Stock extends BaseEntity {
    @PrimaryGeneratedColumn()
    @Field(type => ID)
    id: string;

    @Column()
    @Field()
    ticker: string;

    @Column()
    @Field()
    price: number;

    @Column()
    @Field()
    timestamp: Date;
}

stocks.resolver.ts

import { Args, Mutation, Resolver, Query, ObjectType } from '@nestjs/graphql';
import { Stock } from '../entities/stocks.entity';
import { CreateStockDto } from '../dtos/create-stock.dto';
import { StocksService } from '../stocks.service';

@Resolver()
@ObjectType()
export class StocksResolver {

    constructor(private stocksService: StocksService) {}

    @Query(() => [Stock]) 
    async getStocks(): Promise<Stock[]> {
        return this.stocksService.getStocks();
    }

    @Mutation(() => Stock)
    async createStock(
        @Args('stock') createTaskDto: CreateStockDto
    ): Promise<Stock> {
        return this.stocksService.createStock(createTaskDto);
    }


}

stock.module.ts

import { Module } from '@nestjs/common';
import { StocksService } from './stocks.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import { StocksRepository } from './stocks.repository';
import { StocksResolver } from './resolvers/stocks.resolver';

@Module({
  imports: [TypeOrmModule.forFeature([StocksRepository])],
  providers: [StocksResolver,StocksService],
})
export class StocksModule {}
stocks.repository.ts:
import { Repository } from "typeorm";
import { Stock } from "./entities/stocks.entity";
import { CreateStockDto } from "./dtos/create-stock.dto";
import { Injectable, InternalServerErrorException } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";

@Injectable()
export class StocksRepository {
    constructor(
        @InjectRepository(Stock)
        private repository: Repository<Stock>,
    ) {}

    async getStocks(): Promise<Stock[]> {
        const query = this.repository.createQueryBuilder('stock');
        const stocks = await query.getMany();
        return stocks;
    }

    async createStock({ ticker, price, timestamp }: CreateStockDto): Promise<Stock> {
        const stock = this.repository.create({
            ticker,
            price,
            timestamp
        });

        try {
            await this.repository.save(stock);
            return stock;
        } catch (error) {
            throw new InternalServerErrorException();
        }
    }
}

stocks.service.ts:

import { Injectable } from '@nestjs/common';
import { StocksRepository } from './stocks.repository';
import { CreateStockDto } from './dtos/create-stock.dto';
import { Stock } from './entities/stocks.entity';
import { InjectRepository } from '@nestjs/typeorm';

@Injectable()
export class StocksService {
    constructor(
    @InjectRepository(StocksRepository)
    private stocksRepository: StocksRepository,
    ) {}

    async getStocks(): Promise<Stock[]> {
    return await this.stocksRepository.getStocks();
    }

    async createStock(createStockDto: CreateStockDto): Promise<Stock> {
    return await this.stocksRepository.createStock(createStockDto);
    }
}

I have been stuck on this issue for about four hours now and I still can't seem to figure it out. Everything seems properly decorated in the files provided. Can anyone point out what I might be missing here?

Answer №1

It appears that the issue could arise from a discrepancy in data types. It seems like your code is returning a Stock object, but perhaps it would be better to create a StockDtoOutput object instead. This way, you have more control over what is being returned. For example, if your database stores prices as numbers converted to Floats, but the resolver is expecting Integers while the entity is returning Floats, there may be confusion regarding the expected data type. Additionally, make sure to review your schema.gql file to confirm the types of fields being returned.

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

Manipulating the user interface in react-leaflet using the plus and minus control options

How can I eliminate the "+" and "-" symbols from my react-leaftlet map container? https://i.sstatic.net/3DDsV.png Below is my mapContainer code: <MapContainer center={[0.0, 0.0]} zoom={2} attributionControl={false} doubleClickZoom={fal ...

How can I turn off strict null checks in TypeScript when using ESLint?

ESLint keeps flagging my object as potentially null despite having an if statement to check for it. const user: User | null = getUser() if (user) { // if (user !== null) doesn't work either await user.updateProfile({ di ...

The file isn't located in 'rootDir', even though all the details seem to be accurate

I'm currently troubleshooting an issue with one package in my nx monorepo that is causing the error code "TS6059". Interestingly, all other packages are functioning correctly in previous builds. After reviewing my index.ts files, it appears that all ...

Utilizing web components in React by solely relying on a CDN for integration

I have a client who has provided us with a vast library of UI elements that they want incorporated into our project. These elements are stored in javascript and css files on a CDN, and unfortunately I do not have access to the source code. All I have at my ...

Achieving Bi-Directional Data Binding with Vue.js using the vue-property-decorator Library

Currently, I am working with Vue.js and TypeScript while also utilizing the vue-property-decorator. My goal is to establish two-way data binding between a parent and child component. Below is an example of what I have in mind: Parent Component <templa ...

Advantages of using ConfigService instead of dotenv

What are the benefits and drawbacks of utilizing @NestJS/Config compared to using dotenv for retrieving environment variables? Although I can create a class to manage all envvars in both scenarios, is it necessary? I am aware that @NestJS/Config relies on ...

Discover how to validate a property within an array of objects and add the accurate values to a fresh array using TypeScript

I have a list of objects and I want to create a new array that contains only the objects with the 'read' property set to true. I've tried a couple of different methods, but I keep getting an error: Uncaught TypeError: Cannot read properties ...

Creating an iterable type in TypeScript with key-value pairs - a beginner's guide

I am trying to define a type in TypeScript that represents an object with dynamically generated keys. How can I achieve this? { dog: true, cat: true, x: true } Currently, I am using the 'any' type but I would like to define a proper t ...

When working with create-react-app and TypeScript, you may encounter an error stating: "JSX expressions in 'file_name.tsx' must

After setting up a React project with TypeScript using the CLI command create-react-app client --typescript, I encountered a compilation error when running npm start: ./src/App.js Line 26:13: 'React' must be in scope when using JSX react/r ...

ng-click-outside event triggers when clicking outside, including within child elements

I am looking to trigger a specific action when I click outside of the container. To achieve this, I have utilized the ng-click-outside directive which works well in most cases. However, there is one scenario where an issue arises. Inside the container, the ...

Troubleshooting Image Upload Problem with Angular, Node.js, Express, and Multer

While trying to implement the functionality of uploading an image, I have been referencing various guides like how to upload image file and display using express nodejs and NodeJS Multer is not working. However, I am facing issues with getting the image to ...

The Observable becomes null upon invocation of the unsubscribe function

Seeking assistance in creating an observable that retrieves data in a specific format. getRootGroupNodes(): Observable<Group[]> { return Observable.create(function(observer) { var groups = [ { groupName: "Group1" }, ...

What is the best way to extract value from subscribing?

I attempted to accomplish this task, however, I am encountering issues. Any assistance you can provide would be greatly appreciated! Thank you! export class OuterClass { let isUrlValid = (url:string) => { let validity:boolean ...

Tips for ensuring that the DOM is fully rendered before executing any code

Before proceeding to the next functions, it is necessary to wait for the DOM to finish rendering. The flow or lifecycle of this process is outlined below: Adding an item to the Array: this.someFormArray.push((this.createForm({ name: 'Name& ...

Load Angular template dynamically within the Component decorator

I am interested in dynamically loading an angular template, and this is what I have so far: import { getHTMLTemplate } from './util'; const dynamicTemplate = getHTMLTemplate(); @Component({ selector: 'app-button', // templat ...

Execute TSC on the Hosted Build Agent

Currently, I am diving into TypeScript and have managed to create a basic app that I would like to deploy using VSTS on Azure App Service. My straightforward build definition involves the following steps: Utilize "Node Tool Installer (preview)" to set up ...

Extending the type of parameters in TypeScript

I am trying to call a function from my UI library with a parameter type that extends the original (Suggestion) type by adding more properties. I found a resource that suggests it is possible here: https://github.com/Microsoft/TypeScript/issues/2225 (in the ...

Following a series of Observables in Angular 2+ in a sequential order

Apologies if this question has been answered elsewhere, I attempted to search for it but I'm not exactly sure what I should be looking for. Imagine I have this complex object: userRequest: { id: number, subject: string, ... orderIds: ...

I'm trying to determine in Stencil JS if a button has been clicked in a separate component within a different class. Can anyone assist

I've created a component named button.tsx, which contains a function that performs specific tasks when the button is clicked. The function this.saveSearch triggers the saveSearch() function. button.tsx {((this.test1) || this.selectedExistingId) && ...

Unable to implement a function from a controller class

I'm currently attempting to organize my Express.js code, but I've hit a snag when trying to utilize a class method from the controller. Here's an example of what my code looks like: product.service.ts export class ProductService { constr ...