graphQL vue this. $ apollo.query не работает с параметром (переменными) - PullRequest
0 голосов
/ 30 августа 2018

У меня есть приложение на Vuejs и функция, которая загружает анкету через graphQL. Функция прекрасно работает, пока я не добавлю variables к запросу.

Рабочий код функции:

downloadQuestionnaire() {
  console.log("downloadQuestionnaire: " + questionnaireVersion);
  this.$apollo
    .query({
      query: gql`
        query questionnaire {
          questionnaire(inputParams: { language: "en", version: 1 }) {
            sections {
              section
              cssClass
              remainingItemsType
              endingMessageText
              questions {
                qId
                label
                question
                inputType
                possibleAnswers {
                  paId
                  text
                }
                multipleAnswersAccepted
                individualFormat
                answers
              }
            }
          }
        }
      `,
      client: "questionnaire",
      variables: {
        version: questionnaireVersion
      }
    })
    .then(data => {
      // this.sections = data.questionnaire;
      // console.log(data);
      this.copyQuestionnaie(data.data.questionnaire.sections);
      // console.log(JSON.stringify(data.data.questionnaire.sections));
    })
    .catch(error => {
      this.error = error;
      alert("E " + error);
    });
},

и мне нужно параметризовать version в запросе, изменив его на:

downloadQuestionnaire() {
  console.log("downloadQuestionnaire: " + questionnaireVersion);
  this.$apollo
    .query({
      query: gql`
        query questionnaire($version: Int) {
          questionnaire(
            inputParams: { language: "en", version: $version }
          ) {
            sections {
              section
              cssClass
              remainingItemsType
              endingMessageText
              questions {
                qId
                label
                question
                inputType
                possibleAnswers {
                  paId
                  text
                }
                multipleAnswersAccepted
                individualFormat
                answers
              }
            }
          }
        }
      `,
      client: "questionnaire",
      variables: {
        version: 1
      }
    })
    .then(data => {
      // this.sections = data.questionnaire;
      // console.log(data);
      this.copyQuestionnaie(data.data.questionnaire.sections);
      // console.log(JSON.stringify(data.data.questionnaire.sections));
    })
    .catch(error => {
      this.error = error;
      alert("E " + error);
      console.log("ERROR: " + error);
    });
},

И тогда я получаю ошибку: RROR: Error: Network error: Response not successful: Received status code 400

Я пытался использовать тот же синтаксис, что и в примере здесь . Я неправильно ввожу параметры или наблюдаю за опечаткой?

Обновление:

Ниже приведен код Python схемы для бэкэнда:

import graphene

from .db import get_questionnaire_in_dict, getAnswers, putAnswers


class InputParam(graphene.InputObjectType):  # type: ignore
    """Input parameters for questionnaire."""

    language = graphene.String(required=True)
    version = graphene.Int(required=True)


class PossibleAnswer(graphene.ObjectType):  # type: ignore
    """Possible answers pair of key and text."""

    paId = graphene.String(description="Answer id")
    text = graphene.String(description="Answer text")

    def __init__(self, paId: str, text: str) -> None:
        self.paId = paId
        self.text = text

    def display(self) -> None:
        """Print self content."""
        print("Label: {label},\nQuestion: {question}".format(
            label=self.label, question=self.question))


class Question(graphene.ObjectType):  # type: ignore
    """Question object."""

    qId = graphene.String()
    label = graphene.String(description="Translated question label")
    question = graphene.String(description="Translated question")
    # qPointer = graphene.Field(QuestionItems)
    multipleAnswersAccepted = graphene.Boolean()
    possibleAnswers = graphene.List(PossibleAnswer)
    answers = graphene.List(graphene.String)
    inputType = graphene.String(description="HTML input type")
    individualFormat = graphene.String()

    def __init__(self, questionObj):
        self.qId = questionObj["qPointer"]
        self.label = questionObj["label"]
        self.question = questionObj["question"]
        self.inputType = questionObj["inputType"]
        self.multipleAnswersAccepted = questionObj["multipleAnswersAccepted"]
        if "individualFormat" in questionObj:
            self.individualFormat = questionObj["individualFormat"]
        else:
            self.individualFormat = None
        if questionObj["possibleAnswersPointer"]:
            self.possibleAnswers = []
            for key, value in enumerate(questionObj["possibleAnswersPointer"]):
                possibleAnswer = PossibleAnswer(key, value)
                self.addPossibleAnswer(possibleAnswer)
        else:
            self.possibleAnswers = None

        self.answers = []

    def display(self):
        print("Question {inputType}".format(inputType=self.inputType))
        self.qPointer.display()

    def addPossibleAnswer(self, possibleAnswer):
        self.possibleAnswers.append(possibleAnswer)


class Section(graphene.ObjectType):
    section = graphene.String()
    css_class = graphene.String()
    remainingItemsCount = graphene.Int
    remainingItemsType = graphene.String()
    endingMessageText = graphene.String()
    questions = graphene.List(graphene.NonNull(Question))

    def __init__(self, sectionObj):
        self.section = sectionObj["section"]
        self.css_class = sectionObj["class"]
        self.remainingItemsCount = sectionObj["remainingItemsCount"]
        self.remainingItemsType = sectionObj["remainingItemsType"]
        self.endingMessageText = sectionObj["endingMessageText"]
        self.questions = []

    def display(self):
        print("Section {section}, class: {css_class}".format(
            section=self.section, css_class=self.css_class))

    def addQuestion(self, question):
        self.questions.append(question)


class Questionnaire(graphene.ObjectType):  # type: ignore
    lang = graphene.String()
    sections = graphene.List(Section)

    def __init__(self, lang):
        self.lang = lang.language
        self.sections = []

    def addSection(self, section):
        self.sections.append(section)


class AnswersInputParam(graphene.InputObjectType):  # type: ignore
    userId = graphene.String(required=True)
    version = graphene.Int(required=True)


class Answer(graphene.ObjectType):  # type: ignore
    qId = graphene.String()
    answers = graphene.List(graphene.String)

    def __init__(self, answerObj):
        print("Answer creator: {}".format(answerObj))
        self.qId = answerObj["qId"]
        self.answers = answerObj["answers"]


class Answers(graphene.ObjectType):  # type: ignore
    userId = graphene.String()
    version = graphene.Int()
    answers = graphene.List(Answer)

    def __init__(self, answersObj, userId, version):
        self.userId = userId
        self.version = version
        self.answers = []
        # print("answersObj[\"answers\"]: {}".format(answersObj))
        for index, value in enumerate(answersObj):
            print("_XXX_: {idx}={val}".format(idx=index, val=value))
            answer = Answer(value)
            self.addAnswer(answer)

    def addAnswer(self, answer):
        self.answers.append(answer)


class SaveAnswers(graphene.Mutation):
    class Arguments:
        userId = graphene.String(required=True)
        version = graphene.Int(required=True)
        answers = graphene.JSONString(required=True)

    Output = Answers

    def mutate(self, info, answers, version, userId):
        putAnswers(userId, version, answers)
        return Answers(answers, userId, version)


class Mutation(graphene.ObjectType):
    save_answers = SaveAnswers.Field()


class Query(graphene.ObjectType):
    answers = graphene.Field(
        Answers, inputParams=AnswersInputParam(required=True))

    def resolve_answers(self, info, inputParams):
        answers = getAnswers(inputParams.userId, inputParams.version)
        return Answers(answers, inputParams.userId, inputParams.version)

    questionnaire = graphene.Field(
        Questionnaire, inputParams=InputParam(required=True))

    def resolve_questionnaire(self, info, inputParams):
        qest = Questionnaire(inputParams)
        _struct = get_questionnaire_in_dict(
            inputParams.language, inputParams.version)

        for _sectionRef, sectionData in _struct.items():
            s = Section(sectionObj=sectionData)
            # s.display()
            for key, value in sectionData.items():
                # print(key, value)
                if key == "questions":
                    for _questionNum, questionData in enumerate(value):
                        q = Question(questionObj=questionData)
                        # q.display()
                        s.addQuestion(question=q)
            qest.addSection(s)
        return qest


schema1 = graphene.Schema(query=Query, mutation=Mutation)

# sample calls
# mutation{
#     saveAnswers
#     (
#         userId: "U123",
#         version: 1,
#         answers: "[{\"qId\":\"s1q4\",\"answers\":\"0\"},{\"qId\":\"s2q1\",\"answers\":\"1\"},{\"qId\":\"s2q10\",\"answers\":[\"1\",\"3\"]}]"
#     ) {
#         userId
#         version
#         answers {
#             qId
#             answers
#         }
#     }
# }

# {
#     answers(inputParams: {userId: "U123", version: 1})
#     {
#         answers{
#             qId
#             answers
#         }
#     }
# }
...