我如何 运行 我的 GraphQL 查询使用变量对象进行变异

How do I run my GraphQL query for mutation using variable object

下面是我的 Register Mutation GraphQL 查询,当我 运行 它时我得到一个错误。 “Errormessage”:“UsernamePasswordInput”类型的变量“$options”用于预期类型“UsernamePasswordInput!”的位置。,strong text 我如何使用变量对象 UsernamePasswordInput 运行 我的 GraphQL 查询突变。

感谢您的帮助。

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

下面的 GraphQL 工作正常,但我如何使用变量对象。

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

下面是我的解析器的代码

@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: 'User name already exists ',
                   }]
               }      
            }
            
        }
        
        req.session.userId = user.id;

        return {user};
   }
}

下面是我的实体的代码

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;
  
}

为了解决这个问题,您可能需要从

更新声明
mutation($options: UsernamePasswordInput){

mutation($options: UsernamePasswordInput!){

然后更新 graphql 如下:

 mutation Register($options: UsernamePasswordInput!) {
    register(options: $options) {
    // you may change the format below
    errors {
        ...
    }
    user {
    ...
    }
  }
}

最后,您可以像下面这样从前端调用它:

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

请注意,您可能需要调用 graphql codegen 来生成 useRegisterMutation 挂钩,才能使上述代码以 Formik 形式工作。