Search code examples
typescriptvue.jsgraphql-codegenurql

How to set up Types with Graphql Codegen


I have a Vue 3 component using Urql to query a Hasura graphql endpoint. I have managed to get the fairly simple query working, and am now trying to make the component Type safe.

I am using graphql Codegen to build the types, and it is generating a Types file, but there are errors thrown in the resultant generated file.

I am a bit new to Typescript so hoping someone might be able to put me right. I am keen to resolve the issues reported in the generated Types file.

I have provided the following:

  1. Copy of the working ListTodos.vue component.
  2. Abreviated copy of the Generated Types file (graphql.d.ts). The error occurs at lines 975 - 989, so I have provided a short version of the file with the relevant lines only.
  3. Copy of the errors reported
  4. Copy of my codegen.js configuration file.

Any suggestions are appreciated.

1. ListTodos.vue

<script setup lang="ts">
    import { useQuery, gql } from '@urql/vue'

    const FETCH_TODOS = gql`
        query {
            todos {
                title
                user {
                    name
                }
                is_public
            }
        }
    `
    const result = useQuery({ query: FETCH_TODOS })
</script>

<template>
    <div v-if="result.fetching.value">Loading..</div>
    <div v-else-if="result.error.value">{{ result.error.value }}</div>
    <div v-else>
        <ul>
            <li v-for="todo of result.data.value.todos">
                <h4>{{ todo.title }}</h4>
                <p>{{ todo.user.name }}</p>
            </li>
        </ul>
    </div>
</template>

2. Generated Types (abreviated) showing the error underlining 2. Generated Types showing the error underlining

3. Errors

enter image description here

4. Codegen.js configuration file

module.exports = {
    overwrite: true,
    generates: {
        './src/generated/graphql.d.ts': {
            schema: [
                {
                    'https://sample-backend-for-hasura-tutorial.hasura.app/v1/graphql': {
                        headers: {
                            'x-hasura-role': 'admin',
                            'x-hasura-admin-secret': 'secret',
                        },
                    },
                },
            ],
            documents: ['./src/**/*.vue'],
            plugins: ['typescript', 'typescript-operations', 'typescript-vue-urql'],
            config: {
                preResolveTypes: true,
                skipTypename: false,
                enumsAsTypes: true,
                constEnums: true,
            },
        },
    },
}

Solution

  • OK - I seem to have resolved the problem.

    I removed the plugin 'typescript-vue-urql' from the config which seems counter intuitive, but the generated file then had no issues.

    I also added a name for the query, then imported this 'name' from the Types file, and then typed the useQuery function.