Unexpected Union Type Return from Apollo Server

When I call my resolver to return a union type (either a User or an object with a message key and value of type String, such as my UserNotFoundError type), it always comes back with

"__typename": "User"
. Why is this happening and how can I fix it?

Resolver:

async validateUser(
      _: undefined,
      { email, password }: { email: string; password: string }
    ) {
      const user = await prisma.user.findUnique({
        where: {
          email,
        },
      });
      console.log('user before ', user);
      if (!user || user.password !== password) {
        const err = { message: 'Invalid user or password' };
        return err;
      }
      return user;
    },

typeDefs

 type User {
    email: String!
    password: String
    id: ID!
  }

  type UserNotFoundError {
    message: String!
  }

  union UserOrError = User | UserNotFoundError

  type Query {
    allUsers: [User!]!
    userByEmail(email: String!): User!
    validateUser(email: String!, password: String!): User
  }

When testing in Apollo Studio/Explorer, regardless of the actual return from the resolver:

{
  "data": {
    "validateUser": {
      "__typename": "User"
    }
  }
}

Answer №1

One problem I encountered was not specifying __typename on the objects I was sending back.

The solution that worked for me was:

const errorObj = {
  __typename: 'UserNotFoundError',
    message: 'Invalid user or password',
};

return errorObj;
return {
  __typename: 'User',
  ...userData,
};

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

What could be causing the module version discrepancy with the package.json file I created?

Recently, I created a project using create-next-app and decided to downgrade my Next.js version to 12. After that, I proceeded to install some necessary modules using Yarn and specified the versions for TypeScript, React, and others. During this setup, I b ...

Come back to Angular 2 on your return function

Having a problem with an asynchronous function. There is a service that retrieves data from a Firebase database. One of the functions returns a value: historialDeConsumi() { this.item = this.af.database.object('/users/' + this.uid + '/a ...

What methods are typically used for testing functions that return HTTP observables?

My TypeScript project needs to be deployed as a JS NPM package, and it includes http requests using rxjs ajax functions. I now want to write tests for these methods. One of the methods in question looks like this (simplified!): getAllUsers(): Observable& ...

Exploring the Magic of Class Variable Destructuring in React

Is there a simpler method to break down a prop object and assign them to variables of the same name in the class? I am familiar with ({ first: this.first, second: this.second, } = props) however, it can get complicated when dealing with numerous variable ...

Troubleshooting issue with applying hover effect to child divs

How come when I hover over one of the child items in my parentDiv, the background of the last childDiv changes no matter which child I place my mouse on? for (let i = 0; i < Number(height); i++) { for (let j = 0; j < Number(width); j++ ...

Encountered Runtime Error: TypeError - Carousel triggering issue with reading properties of null (specifically 'classList') in Tailwind Elements

Currently, I am encountering the error message: Unhandled Runtime Error TypeError: Cannot read properties of null (reading 'classList') while utilizing the Carousel component. The problem arises when I attempt to populate the carousel with images ...

The interfaces being used in the Redux store reducers are not properly implemented

My Redux store has been set up with 2 distinct "Slice" components. The first one is the appSlice: appSlice.ts import { createSlice, PayloadAction } from "@reduxjs/toolkit"; import type { RootState } from "./store"; export interface CounterState { value ...

Error: The data passed to updateDoc() is invalid and cannot be processed

Currently, I am in the process of creating a function called uploadPost(). Within this function, I am adding a document to a collection in Firebase Firestore. However, when I attempt to choose an image and update the document by obtaining the download URL ...

Implementing a global provider in Ionic 3

I have integrated a provider in my app that needs to stay active at all times while the application is running to monitor the network connection status. Following this guide, I included the class in my app.module.ts file to ensure it functions as a global ...

Can you explain the significance of this particular method signature in the TypeScript code snippet shown above?

Referencing the ngrx example, we encounter the code snippet for the method store.select, which has a complex signature with two arrows. What is the significance of this method signature? The interface definition in the type file presents the following sig ...

The "void" type cannot be assigned to the type "ObservableInput<{}>"

I recently encountered this issue after updating to TS 2.2.2, and I suspect that is the root cause... While the code still functions properly, I am now seeing this error. I attempted various solutions such as returning an empty observable, catching the re- ...

Issue: React-Firebase-Hooks failing to retrieve dataHaving trouble with React-F

I've been utilizing the React-Firebase-Hooks package in my project, but I'm encountering some difficulties with its usage. In the code snippet below, the user.data().username is displayed correctly. However, when I try to use it within useState, ...

How can one break down enum values in typescript?

I've defined an enum in TypeScript as shown below: export enum XMPPElementName { state = "state", presence = "presence", iq = "iq", unreadCount = "uc", otherUserUnreadCount = "ouc", sequenc ...

unable to successfully complete parameter in angular 2

After receiving data from the API, I am using the subscribe method to execute lines of code. Below is the code snippet: this.attRecService.getAgendaData(moment(this.viewDate).format('YYYY-MM')).subscribe( resp => { this.ag ...

What is causing the duplication of leaves when using this DFS implementation?

I created an algorithm to compare if two trees have the same leaves. Both trees display matching leaf numbers in the exact order, resulting in a true outcome. Below is the code that I formulated: function leafSimilar(root1: TreeNode | null, root2: TreeNo ...

Animating Page Transitions within Ionic 2

In my Ionic 3 application, I have a basic tabs template where I switch between tabs by swiping left or right. Everything works perfectly except there is no animation effect when transitioning between tabs either by tapping or swiping. I am able to achieve ...

What is the most efficient way to perform an inline property check and return a boolean value

Can someone help me with optimizing my TypeScript code for a function I have? function test(obj?: { someProperty: string}) { return obj && obj.someProperty; } Although WebStorm indicates that the return value should be a boolean, the TypeScript compil ...

What could be the reason behind tsx excluding attribute names with "-" in them from being checked?

Why doesn't TypeScript check attributes with a hyphen in the name? declare namespace JSX { interface ElementAttributesProperty { props:any; // specify the property name to use } } class A{ props!:{p1:string} } const tsx = <A p1="&q ...

How can you display a loading indicator after a delay using Observables, but make sure to cancel it if the loading is completed

Within my customer-detail component, I have implemented code that achieves the desired outcome. However, I believe there might be a more reactive and observable way to approach this task. Instead of using an if statement to set this.isLoading = true;, is ...

What is the best way to share image data between pages in Next.js?

I'm currently developing a project that mimics Instagram (simply because I want to explore Next.js further) and I'm looking for a way to handle image uploads. My goal is to allow users to upload their images and then redirect them to the "create ...