Creating a notification following the deletion of a user using Typescript and GraphQL

As someone who is new to Typescript and GraphQL, I recently implemented CRUD functionalities in a To-Do list. However, I am facing a challenge when it comes to including messages within GraphQL responses. Specifically, when I delete a User, I would like the response to include deleted: true.

So far, I have successfully created all the necessary logic to delete a User.

Here is my Delete User mutation:

import { getRepository } from 'typeorm';
import { Entities } from '../../../entities/entities';

export const deleteUserMutation = {
    async deleteUser(_, { id }): Promise<typeof user> {
        const repository = getRepository(Entities.user);
        const user = await repository.findOne({ id });
        await repository.delete({ id });
        return {
            ...user,
        };
    },
};   

User Mutation schema snippet:

 export const UserMutation = `
        extend type Mutation {
          createUser (
            user: NewUserPatch!
          ): User
          updateUser (
            id: String!
            patch: UserPatch!
          ): User
          deleteUser (
            id: String!
          ): User
        }
    `;

If there are additional details you'd like me to provide, please let me know so I can include them.

To summarize my issue, I need the response message to indicate that the deletion was successful:

{
  "data": {
    "deleteUser": {
      "deleted": true
    }
  }
}

Answer №1

In order to receive the specific message "deleted": true, adjustments need to be made to both your mutation schema and resolver logic. The current implementation of the deleteUser mutation returns an object of type User, which likely does not include the boolean flag you desire. To address this issue, consider creating a new payload type for the deleteUser mutation that includes the boolean flag along with any additional information related to the deleted user.

    type DeleteUserPayload {
        deleted: Boolean!
        user: User
    }

    // Modify the mutation to return the new payload type
    deleteUser (id: String!): DeleteUserPayload

It will be necessary to update the resolver for deleteUser to ensure that the correct payload values are returned as expected.

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

The Angular directive ng-if does not function properly when trying to evaluate if array[0] is equal to the string value 'Value'

In my code, I want to ensure that the icon is only visible if the value at array index 0 is equal to 'Value': HTML <ion-icon *ngIf="allFamily[0] === 'Value'" class="checkas" name="checkmark"></ion-icon> TS allFamily = [ ...

What is the best way to determine if a mat-menu in Material Angular is currently displaying or hidden?

Is there a way to determine if the mat-menu is currently open so that I can dynamically apply a class to the corresponding button using [ngClass] depending on the menu's state? <button mat-stroked-button mdbWavesEffect [matMenuTriggerFor]="menu"&g ...

Tips for creating a generic type that is versatile

I came across this helpful solution here After studying it, I saw potential for improvement to make it more versatile. That's when I developed a new, even more universal generic type: export type extractGeneric<Type, Parent> = Type extends Pare ...

Having trouble utilizing a custom array of objects in TypeScript and React?

After rendering a Functional Component that retrieves a list of objects, I successfully run a foreach loop with it. However, when I attempt to make http requests with each object to create a new array, something seems off. The formatting appears to be inco ...

Mentioning a specific key more than once within a data structure

Sorry for the vague title, I'm struggling to articulate this idea. Here is a type definition that I have: type Foo = { a: number, b: string, c: boolean, } I am looking to utilize this type as follows: type FooInfo = { property: keyof Foo, ...

What causes TypeScript to display an 'Object is potentially undefined' error message when utilizing array.at(-1)?

An issue arises in Typescript with the error message "Object is possibly 'undefined'" when attempting to access an element at a negative index using array.at(-1).key //array[array.length - 1].key. This error does not occur in the following code: ...

Is there a way to access a value from one observer within another observer?

How can I modify this line to return a value in the subscribe function instead of an observable? let test = undefined; of(test, this.myService.whatever(var1, var2)) .pipe( first(n=>!!n) ).subscribe(result=>console.log(result)); // r ...

tips for resolving pm2 issue in cluster mode when using ts-node

I'm having an issue using pm2 with ts-node for deployment. Whenever I try to use cluster-mode, a pm2 instance error occurs, saying "Cannot find module..." Error: Cannot find module '{path}/start' at main ({path}/node_modules/ts-node/dist/b ...

Unspecified data stored within an object

I am looking to populate a page with data from the server and have the ability to update the information. To achieve this, I am using formbuilder to fetch data from the server as the default value. Here's how I am implementing it: createForm(){ ...

The value of 'this.selectedNodes' does not support iteration and is causing a

I am currently utilizing v-network-graphs to generate graphs in the front end with Vue. I have set up my data like this: data(){ return{ test: test_data, nodes:{}, edges:{}, nextNodeIndex: Number, selectedNodes: ref<st ...

Storing JSON data in a variable using .subscribe is not possible in Angular

Currently, I am encountering an issue where I cannot successfully store the specific data obtained from a Post request into a variable. How can I resolve this and ensure that only the desired data is stored? After making a Post request and receiving back ...

Unexpected behavior encountered when using TypeScript type declarations

I am currently working on a Gatsby side project incorporating Typescript for the first time. I initially expected Typescript to behave similarly to PHP type declarations, but I have encountered some unforeseen issues. Despite feeling confident in my Typesc ...

Using Typescript to override an abstract method that has a void return type

abstract class Base{ abstract sayHello(): void; } class Child extends Base{ sayHello() { return 123; } } The Abstract method in this code snippet has a return type of void, but the implementation in the Child class returns a number. S ...

The automatic filtering feature does not kick in when the sorting is changed

I've been working on an app that features a video database, allowing users to filter videos by category and sort them by rating. https://i.sstatic.net/cESZT.png Currently, the filtering system works fine once the options are changed. However, there ...

Creating nested return types: A guide to defining function return types within a Typescript class

My large classes contain functions that return complex objects which I am looking to refactor. class BigClass { ... getReferenceInfo(word: string): { isInReferenceList:boolean, referenceLabels:string[] } { ... } } I am considering somethi ...

Rotating images on a canvas

We're currently implementing Ionic and Angular in our project. One issue we are facing is regarding image rotation on canvas. When we click on an image, the rotation works perfectly if it's a jpg file. However, when we pass a base64 image, the r ...

Unexpected alteration of property value when using methods like Array.from() or insertAdjacentElement

I'm encountering an issue where a property of my class undergoes an unintended transformation. import { Draggable, DragTarget } from '../Models/eventlisteners'; import { HeroValues } from '../Models/responseModels'; import { Uti ...

Tips for effortlessly incorporating a new chip while maintaining a neat arrangement and ensuring button alignment

I am looking to enhance my website by adding chips with new tags in a neatly organized manner. Specifically, I want each new chip to be positioned next to the previous one and have the add-button shift to the right side, always staying in front of the last ...

React Bootstrap Forms: The <Form.Control.Feedback> element is failing to display when the validation is set to false

Problem: I am facing difficulties with displaying the React Bootstrap <Form.Control.Feedback></Form.Control.Feedback> when the validation is false in my form implementation. Steps to Recreate: Upon clicking the Send Verification Code button, ...

SVG: What could be causing the shapes inside the svg to not be visible when overlaid on an image?

I am currently working on a project using Angular where my objective is to create a polygon within an image. In order to achieve this, I have placed an SVG element inside the image tag. Both the image and the SVG have fixed width and height dimensions, and ...