Search code examples
vue.jsvue-apollo

Is smart query custom variable name possible?


I'm using Vue alongside with Apollo in order to query a GraphQL endpoint in my project. Everything's fine but I want to start programming generic components to ease and fasten the development.

The thing is, in most views, I use the Smart Query system. For instance, I use :

  apollo: {
    group: {
      query: GROUP_QUERY,
      variables () { return { id: this.groupId } },
      skip () { return this.groupId === undefined },
      result ({ data }) {
        this.form.name = data.group.name
      }
    }
  }

With the GROUP_QUERY that is :

const GROUP_QUERY = gql`
  query groupQuery ($id: ID) {
    group (id: $id) {
      id
      name
      usersCount
      userIds {
        id
        username
      }
    }
  }
`

So my group variable in my apollo smart query has the same name as the query itself group (id: $id). It is this mechanism that is quite annoying for what I try to achieve. Is there a way to avoid that default mechanism ?

I'd like for instance to be able to give a generic name such as record, and it would be records for queries that potentially return multiple records.

With that, I would be able to make generic components or mixins that operate either on record or records.

Or have I to rename all my queries to record and records which would be annoying later on in case of troubleshooting with error messages ?

Or maybe there's another way to achieve that and I didn't think about it ?

Thanks in advance.


Solution

  • By doing so :

    const GROUP_QUERY = gql`
      query groupQuery ($id: ID) {
        record: group (id: $id) {
          id
          name
          usersCount
          userIds {
            id
            username
          }
        }
      }
    `
    

    If the GROUP_QUERY is used at several places, the result will be accessible under the record name, because it is defined as an alias over group. See documentation for Aliases.