Ideas

Give us your best ideas!

Put GraphQL queries in separate files and generate types with apollo-client based on query/schema

Type-safe access will simplify accessing data, inform about accessing nullable objects and also show in build warning/errors when schema has changed but queries are not updates.

  • Kamil Piekara
  • Apr 22 2024
  • Not right now
  • Attach files
  • Christian Norrman commented
    11 May 13:12

    I tried to add graphql types with the apollo codegen and also gql-tada. Both approaches does not handle Union types well as they require explicit typename checks in order to work with TypeScript.

    This requires every time a union is use in a query that the developer checks the typename before accessing any of the properties of the data object. This creates unnecessary checks and very verbose code. Unfortunately most of the Storefront API uses union types (for example content, blocks, organization, persons, etc.).

    It is probably better to put the queries in seperate files but have the type definition for each query "manually typed". As this is much easier when we know the query to define the possible outcomes of the query.

    Defining each query as a single service is probably better (for example homePageService where all the queries for home page is stored). As then we can co-locate the graphql query, the type, aswell as the code for the query itself.