KeystoneJS relationships, how can I connect using an array of ids

Viewed 374

I am using the new version Keystone Next and I am trying to connect multiple items at once using an array of ids. It seems connect supports that, accepting an array of objects.

const FINISH_VOCABULARY_QUIZ_MUTATION = gql`
mutation FINISH_VOCABULARY_QUIZ_MUTATION(
    $userId: ID!
    $wordId: ID!
) {
    updateUser(id: $userId, data: {
        wrongAnswers: {
            connect: [{id: "idblabla"}, {id: "idblabla2"}]
        }
    }) {
        id
    }
}`;

But what I just can't seem to figure out is how do I pass this array of ids as a variable to my mutation. I understand that I would need to create a new type? The documentation is still unfinished, so there is nothing on that yet. I have also tried using string interpolation to form my query, but it seems that it's not a thing in GraphQl.

2 Answers

This is more of a GraphQL question than a KeystoneJS but one but to head to the right direction here you'd need to change your query to something like below:

const FINISH_VOCABULARY_QUIZ_MUTATION = gql`
mutation FINISH_VOCABULARY_QUIZ_MUTATION(
    $userId: ID!,
    $ids: [UserWhereUniqueInput!]!
) {
    updateUser(id: $userId, data: {
        wrongAnswers: {
            connect: $ids
        }
    }) {
        id
    }
}`;

And then map your array of ids to an array of objects with id fields.

There is a better method:

const FINISH_VOCABULARY_QUIZ_MUTATION = gql`
mutation FINISH_VOCABULARY_QUIZ_MUTATION(
    $userId: ID!,
    $data: SomeAPIDefinedMutationUniqueInput
) {
    updateUser(id: $userId, data: $data)
      id
    }
}`;

This way you:

  • don't have to define types for internal arguments ($wordsIdWrong: [WordWhereUniqueInput]);
  • can reuse/share this mutation - import it from some, common for queries, place (dir) - just call it with different data variables;
  • easier for reading/maintenance;

PS. To be honest, there should be some specific [to quizes] mutation (don't use userUpdate for that), with user (or better quiz) id defined within SomeAPIDefinedUniqueInput.

Related