The Nestje subscription is encountering a NULL value and displaying an error message stating: "Non-nullable field Subscription cannot be returned as null."

I attempted to implement a Subscription in my nestjs project with GraphQL, but encountered the following error message:

Cannot return null for non-nullable field Subscription

Below is the code snippet:

  //* ~~~~~~~~~~~~~~~~~~~ Subscription ~~~~~~~~~~~~~~~~~~~ */
  @Mutation((returns) => Boolean)
  testSubscription() {
    pubsub.publish('somethingOnTrack', {
      somethingOnTrack: 'something',
    });
    return true;
  }
  @Subscription((returns) => String)
  orderSubscription() {
    return pubsub.asyncIterator('somethingOnTrack');
  }
Simply create a subscription and test it.

This is how I set up the GraphQLModule in app.module within nestjs:

GraphQLModule.forRoot<ApolloDriverConfig>({
  driver: ApolloDriver,
  autoSchemaFile: true,
  subscriptions: {
    'graphql-ws': true,
    'subscriptions-transport-ws': true,
  },
}),

I tried utilizing graphql-ws & subscriptions-transport-ws

Next, I tested it in the graphql:

subscription {
  orderSubscription
}

mutation {
  testSubscription
}

The Mutation returned the expected result:

{
  "data": {
    "testSubscription": true
  }
}

However, the Subscription triggered an error:

{
  "errors": [
    {
      "message": "Cannot return null for non-nullable field Subscription.orderSubscription.",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "orderSubscription"
      ]
    }
  ],
  "data": null
}

It appears that the subscription is unable to receive the payload from the pubsub.publish function. Why am I encountering this issue?

Answer №1

Since this is a code-first approach, simply returning the type String in Subscription may not make much sense. As a solution, let's introduce an output type dto:

import { Field, ObjectType } from '@nestjs/graphql';

@ObjectType()
export class SubscriptionOutput {
  @Field((type) => String)
  somethingOnTrack: string;
}

In addition, we should include {resolve: ...} in the Subscription as well. Is this the correct syntax to use? Let's modify the test Subscription accordingly:

  //* ~~~~~~~~~~~~~~~~~~~ Subscription ~~~~~~~~~~~~~~~~~~~ */
  @Mutation((returns) => Boolean)
  testSubscription() {
    this.pubsub.publish('somethingOnTrack', { somethingOnTrack: 'something' });
    return true;
  }
  @Subscription((returns) => SubscriptionOutput, {
    resolve: (payload) => payload,
  })
  orderSubscription() {
    return this.pubsub.asyncIterator('somethingOnTrack');
  }

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

Struggle with typescript integration with emotion and styled components

Issue Description: I encountered an issue while working with typescript and emotion/styled libraries. When attempting to specify the type of the parent component that wraps a styled component, I faced difficulties. The scenario involves a parent componen ...

React experimental is encountering an issue with missing property "" $fragmentRefs"" when relaying fragments

Details Recently, I decided to explore React experimental features with concurrent mode and relay. Even though I have never used relay before, I managed to make progress but ran into some issues. Initially, using the useLazyLoadQuery hook without any frag ...

How can I utilize identical cucumber steps for both mobile and web tests while evaluating the same functionality?

In order to test our website and React Native mobile app, we have developed a hybrid framework using webdriver.io and cucumber.io. We currently maintain separate feature files for the same functionality on both the web and mobile platforms. For example, i ...

What are the best ways to maximize a web worker's ability to handle multiple tasks at once

I'm currently working on implementing a Web-Worker to handle its state while also managing multiple asynchronous requests. worker.ts file let a =0; //state of the worker let worker=self as unknown as Worker; worker.onmessage =(e)=>{ console ...

What is the best way to add all IDs to an array, except for the very first one

Is there a way to push all response IDs into the idList array, excluding the first ID? Currently, the code below pushes all IDs to the list. How can it be modified to exclude the first ID? const getAllId = async () => { let res = await axios({ m ...

Unable to locate module: Issue: Unable to locate '@angular/cdk/tree' or '@angular/material/tree'

Currently utilizing Angular 5 and attempting to create a tree view that resembles a table layout. https://stackblitz.com/edit/angular-hhkrr1?file=main.ts Encountering errors while trying to import: import {NestedTreeControl} from '@angular/cdk/tree ...

Implementing a back button in an RTL layout with Ionic 2

Just starting an Ionic 2 app in Arabic language requires a RTL layout. I decided to go with the side menu template. Adding the following line for configuring the app to RTL perfectly changed everything's direction, except for the back button which st ...

What is the method to assert that two arguments are equal within a function?

When working with TypeScript, you can pass a value to a function and have that function assert the value is true for type narrowing. For example: function assertTrue(v: unknown, message: string): asserts v { if (!v) { throw new MySpecialError(message ...

``If you're looking to integrate a 360-degree product viewer into your Angular application, here is a

I am in need of showcasing a 360 Product viewer consisting of an array of 36 car images in base64 format. Despite attempting to utilize the angular-three-sixty Package by @mediaman, I was only met with an empty canvas. Does anyone have experience in implem ...

Encountering issues with dependencies while updating React results in deployment failure for the React app

Ever since upgrading React to version 18, I've been encountering deployment issues. Despite following the documentation and scouring forums for solutions, I keep running into roadblocks with no success. The errors displayed are as follows: $ npm i np ...

How can a class be imported into a Firebase Cloud function in order to reduce cold start time?

When optimizing cold start time for Firebase Cloud functions, it is recommended in this Firebase Tutorial to import modules only where necessary. But can you also import a class with its own dependencies inside a function? In my scenario, I need to use Bc ...

Tips for ensuring the correct function type in TypeScript

TypeScript Version 3.5.1 Playground I've encountered an issue with TypeScript where the compiler fails to flag missing arguments in function declarations. Here's a basic illustration of the problem. interface IArgs { foo: number; } type MyF ...

What are the conditions for Jasmine's .toHaveBeenCalledWith to match the parameters?

I'm working on an Angular service along with its Jasmine test. The test is calling f1() and spying on f2(). The function f2 takes a variable v2 and updates it by setting field 'a' to 3. I expected the function f2 to be called with v2 (as def ...

Strategies for avoiding unused style tags in React components

Expanding beyond React, I'm unsure if React itself is the culprit of this issue. In a React environment with TypeScript, I utilize CSS imports in component files to have specific stylesheets for each component. I assumed these styles would only be ad ...

What is the process for integrating ng-bootstrap into an Angular 5 project?

Has anyone encountered issues loading ng-bootstrap in their Angular project? I'm experiencing difficulties and would appreciate any insights. Thank you for your help! This is my app.module.ts file: import { BrowserModule } from '@angular/platf ...

Encountering a Javascript error while trying to optimize bundling operations

After bundling my JavaScript with the .net setting BundleTable.EnableOptimizations = true;, I've encountered a peculiar issue. Here's the snippet of the generated code causing the error (simplified): var somVar = new b({ searchUrl: "/so ...

The issue arises when attempting to use the search feature in Ionic because friend.toLowerCase is not a valid function

I keep encountering an error message that says "friend.toLowerCase" is not a function when I use Ionic's search function. The unique aspect of my program is that instead of just a list of JSON items, I have a list with 5 properties per item, such as f ...

Accurately locate all ChildComponents throughout the entire Component hierarchy

I am facing a challenge in Angular where I need to retrieve all the ChildComponents from my ParentComponent. The issue is that the ChildComponents are not directly nested within the ParentComponent, but instead they are children of other components which a ...

Utilize a method categorization while implicitly deducing parameters

Scenario In my project, I have a unique class setup where methods are passed in as a list and can be called through the class with added functionality. These methods are bound to the class (Foo) when called, creating a specific type FooMethod. class Foo { ...

Comparing Angular 2 with Angular.js, React.js, and Typescript

Hello there, I am a fresh-faced web developer looking to create a modest website for my personal use. However, my knowledge is limited when it comes to JavaScript and jQuery concepts. In order to expand my skills and build an enhanced website, I decided ...