首页 > 解决方案 > 在反应本机应用程序中使用 AWS Amplify 在 GraphQL 突变中出错

问题描述

尝试执行 graphql 突变,其中突变应采用自定义类型。在 App Sync 架构中,我定义了这些自定义类型:

架构:

  input CreateConversationInput {
        user: UserInput
        doctor: DoctorInput
        questionsAndAnsers: [ConversationQAInput]
        pet: UpdatePetInput
    }

反应本机代码:

  const createConversationInput = {

        user: {
            username: "deep",
            userType: "Patient",
            fullName: "Deep A"
        },
        doctor: {
            name: "Raman",
            speciality: "dog",
            doctorId: "0bd9855e-a3f2-4616-8132-aed490973bf7"
        },
        questionsAndAnswers: [{ question: "Question 1", answer: "Answer 1" }, { question: "Question 2", answer: "Answer 2" }],
        pet: { username: "deep39303903", petId: "238280340932", category: "Canine" }


    }

    API.graphql(graphqlOperation(CreateConversation, createConversationInput)).then(response => {

        console.log(response);

    }).catch(err => {
        console.log(err);
    });

我已经定义了这样的突变:

export const CreateConversation = `mutation CreateConversation( $user: Object, 
    $doctor: Object, $questionsAndAnswers: Object, $pet: Object ) {

        createConversation(

             input : {

                user: $user
                doctor: $doctor
                questionsAndAnswers: $questionsAndAnswers
                pet: $pet
            }
        ){
    username
    createdAt

  }

  }`;

突变在 AWS GraphQL 控制台中正常工作。但是,在反应本机应用程序中,我收到错误。

错误:

“UnknownType 类型的验证错误:未知类型的对象”。

我相信错误是因为我将类型定义为突变中的 Object 而不是 AWS Schema 中定义的实际类型。如果这是问题,我如何在 React Native 代码中定义自定义类型?

标签: javascriptreact-nativegraphqlaws-amplify

解决方案


您只需要更改定义变量的方式:

mutation CreateConversation(
  $user: UserInput,
  $doctor: DoctorInput,
  $questionsAndAnswers: [ConversationQAInput],
  $pet: UpdatePetInput
) {
  createConversation(input: {
    user: $user
    doctor: $doctor
    questionsAndAnswers: $questionsAndAnswers
    pet: $pet
  }) {
    username
    createdAt
  }
}

在 GraphQL 中使用变量时,您需要为该变量指定输入类型(或标量)。然后将其与您使用该变量的任何参数所期望的类型进行比较。这里的输入类型是指你的模式中的一种类型,而不是任何与 JS 相关的东西,所以你不需要在你的代码中做任何特殊的事情。


推荐阅读