What is the best way to execute a GraphQL mutation query with a variable object?

My Register Mutation GraphQL Query is causing an error when executed. The error message states: "Variable "$options" of type "UsernamePasswordInput" used in position expecting type "UsernamePasswordInput!". How can I properly run my GraphQL query for mutation using the variable object UsernamePasswordInput?

Any assistance on resolving this issue is greatly appreciated.

mutation($options: UsernamePasswordInput){
  register(options: $options){
    errors {
      field
      message
    }
    user {
      id
      username
    }
  }
}

The following GraphQL code is functioning correctly, but I am unsure how to utilize the Variable object:

mutation{
  register(options: { username: "test6", password:"test6"}){
    errors {
      field
      message
    }
    user {
      id
      username
    }
  }
}

Below is the code for my resolver:

@InputType()
class UsernamePasswordInput {
    @Field()
    username: string;
    @Field()
    password: string;
} 

@ObjectType()
class FieldError {
    @Field()
    field: string;    
    @Field()
    message: string;
}

@ObjectType()
class UserResponse {
    @Field(() => [FieldError], { nullable: true } )
    errors?: FieldError[];

    @Field(() => User, { nullable: true } )
    user?: User;
}

@Resolver()
export class UserResolver {
   @Mutation(() => UserResponse)
   async register(
       @Arg("options", () => UsernamePasswordInput) options: UsernamePasswordInput,
       @Ctx() {em, req}: MyContext

   ): Promise<UserResponse>{
       if(options.username.length <= 2)
       {
           return{
               errors: [{
                  field: 'username',
                  message: 'Length of user name must be greater than 2'
               }]
           }
       }
       if(options.password.length <= 2)
       {
           return{
               errors: [{
                  field: 'password',
                  message: 'Length of password must be greater than 2'
               }]
           }
       }
       const hashedPassword = await argon2.hash(options.password);
       let user;
        try{
            const result = await (em as EntityManager)
            .createQueryBuilder(User)
            .getKnexQuery()
            .insert({
                    username: options.username,
                    password: hashedPassword,
                    created_at: new Date(),
                    updated_at: new Date()
                })
                .returning("*");  
                user = result[0];        
        }
        catch(err){
            if(err.detail.includes("already exists")){
               return {
                   errors: [{
                    field: 'username',
                    message: 'Username already exists ',
                   }]
               }      
            }
            
        }
        
        req.session.userId = user.id;

        return {user};
   }
}

Below is the code for my Entity:

import { Entity, PrimaryKey, Property } from "@mikro-orm/core";
import { Field,  ObjectType } from "type-graphql";

@ObjectType()
@Entity()
export class User {
  @Field()
  @PrimaryKey()
  id!: number;

  @Field(() => String)
  @Property({type: "date"})
  createdAt = new Date();

  @Field(() => String)
  @Property({ type: "date", onUpdate: () => new Date() })
  updatedAt = new Date();

  @Field()
  @Property({ type: "text", unique: true})
  username!: string;

  @Property({ type: "text"})
  password!: string;
  
}

Answer №1

If you are facing an issue, you can resolve it by updating the declaration from

mutation($options: UsernamePasswordInput){

to

mutation($options: UsernamePasswordInput!){

After that, make sure to update the graphql code as shown below:

 mutation Register($options: UsernamePasswordInput!) {
    register(options: $options) {
    // Feel free to modify the structure below
    errors {
        ...
    }
    user {
    ...
    }
  }
}

Lastly, you can trigger it from the frontend like this:

const response = await register({ options: value });

Keep in mind that you might have to utilize graphql codegen to create a useRegisterMutation hook to enable the above code to function properly in a Formik form.

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

Creating a Button with Icon and Text in TypeScript: A step-by-step guide

I attempted to create a button with both text and an icon. Initially, I tried doing it in HTML. <button> <img src="img/favicon.png" alt="Image" width="30px" height="30px" > Button Text ...

You were supposed to provide 2 arguments, but you only gave 1.ts(2554)

Hey everyone, I hope you're having a good morning. Apologies for the inconvenience, I've been practicing to improve my skills and encountered an issue while working on a login feature. I'm trying to connect it to an API but facing a strange ...

Error in Angular 7: ActivatedRoute paramId returns null value

On page load, I am trying to subscribe to my paramsID, but when I use console.log(), it returns null. I am currently working with Angular 7. Here is my TypeScript code: import { Component, OnInit } from '@angular/core'; import { Activat ...

What is the correct way to handle Vue props that include a dash in their name?

I am currently working on a project using Vue. Following the guidelines of eslint, I am restricted from naming props in camel case. If I try to do so, it triggers a warning saying Attribute ':clientId' must be hyphenated. eslint vue/attribute-hyp ...

Encountering a TypeError while working with Next.js 14 and MongoDB: The error "res.status is not a function"

Currently working on a Next.js project that involves MongoDB integration. I am using the app router to test API calls with the code below, and surprisingly, I am receiving a response from the database. import { NextApiRequest, NextApiResponse, NextApiHandl ...

Having trouble retrieving a value from a reference object in React Typescript?

Struggling with a login form issue in my React TypeScript project. Below is the code for the react login form: login-form.tsx import * as React from 'react'; import { Button, FormGroup, Input, Label } from 'reactstrap' ...

Unable to display results in React Native due to FlatList not being shown

I'm a beginner to React Native and I'm attempting to create a simple flatlist populated from an API at , but unfortunately, no results are displaying. Here's my App.tsx code: import React from 'react'; import type {PropsWithChildre ...

Dealing with Cross-Origin Resource Sharing problem in a React, TypeScript, Vite application with my .NET backend

I'm encountering a CORS issue when trying to make a Request using Fetch and Axios in my application hosted on the IIS Server. Here are my Server API settings: <httpProtocol> <customHeaders> <add name="Access-Control-Allow-O ...

Ensuring type integrity for intersections containing varying numbers of elements

Currently, I am navigating a sophisticated custom typeguard library developed for a project I'm involved in. I am facing challenges in grasping the concept of function signatures used in typeguards. The library includes a generic Is function that has ...

Angular's Dynamic Reactive Forms

I encountered an issue while using Typed Reactive Forms in Angular 14. I have defined a type that connects a model to a strict form group. The problem arises specifically when utilizing the Date or Blob type. Note: I am working with Angular 14. Error: src/ ...

Using ts-node-dev (and ts-node) with ECMAScript exports and modules

Currently, we are in the process of upgrading TypeScript to a more modern standard due to changes in libraries like nanoid that no longer support commonjs exports. Our goal is to integrate the ts-node-dev library with exporting to ECMAScript modules. The ...

The generic type does not narrow correctly when using extends union

I'm working with the isResult function below: export function isResult< R extends CustomResult<string, Record<string, any>[]>, K extends R[typeof _type] >(result: R, type: K): result is Extract<R, { [_type]: K }> { ...

Enhance your FullCalendar experience with React by displaying extra information on your calendar

I am new to using React and FullCalendar, and I have a page layout similar to the image linked below. https://i.sstatic.net/MooTR.png Additionally, I have a list of events structured as shown: id: "9", eventId: "1", ...

The process of exporting a singleton instance

I have created a new class called AppViewModel with a setting property set to 1: class AppViewModel { setting: number = 1; } export = AppViewModel; Afterward, I imported the class and instantiated it within another class named OrderEntry: import AppV ...

Straightforward npm package importing syntax

I am looking for a way to simplify the import statements when publishing a new TypeScript package on npm. Ideally, I would like to be able to use something like: import { FirstClass, SecondClass } from "my-repo"; However, currently I have to use longer i ...

Encounter issue with async function in produce using Immer

Having an issue while attempting to create an asynchronous produce with immer. When calling the async function, this error is encountered: Below is my code snippet: import { combineReducers, createStore } from 'redux'; import produce from ' ...

Make sure to include a property that is indexed when typing

I am currently working on defining a type to represent a list (hash) of HTTP headers. This type is supposed to be a hash that only contains key / string pairs: type TStringStringHash = { [key: string]: string } However, the issue I am facing is that i ...

Understanding the basics of reading a JSON object in TypeScript

Displayed below is a basic JSON structure: { "carousel": [], "column-headers": [{ "header": "Heading", "text": "Donec sed odio dui. Etiam porta sem malesuada magna mollis euismod. Nullam id dolor id nibh ultricies vehicula ut id el ...

retrieve the initial subarray from the array using rxjs

Looking to extract the first array from a subarray, my current setup is as follows: Map: map; Map() { Service }); } This is the interface structure: export interface map { } Encountering an error message: ERROR TypeError: ...

Incorporating Google Pay functionality within Angular applications

I have been attempting to incorporate Google Pay into my Angular project, but I am struggling to find reliable resources. My main issue revolves around the following code... <script async src="https://pay.google.com/gp/p/js/pay.js" onloa ...