graphql-zeus icon indicating copy to clipboard operation
graphql-zeus copied to clipboard

GraphQL-Zeus should use TypedDocumentNode

Open ivasilov opened this issue 3 years ago • 2 comments

Hello,

I don't know if you know about typed-document-node but it seems like the perfect abstraction needed by GraphQL-Zeus.

In short, TypedDocumentNode<Result,Variables> can be consumed by most of GraphQL libraries to provide Typescript typings. The TypedDocumentNode type contains the result and needed variables for each GraphQL document. Zeus queries should just return TypedDocumentNode and most GraphQL libs would work.

An example implementation would be by using the following abstraction function:

import { TypedDocumentNode } from '@graphql-typed-document-node/core';
import gql from 'graphql-tag';
import { GraphQLTypes, InputType, Selectors, ValueTypes, Zeus } from '../../zeus';

export const constructQuery = <T extends ValueTypes['Query']>(q: T) => {
  const gqlString = Zeus.query(q);
  const selector = Selectors.query(q);
  type InferredResponseType = InputType<GraphQLTypes['Query'], typeof selector>;
  return gql(gqlString) as TypedDocumentNode<InferredResponseType, {}>;
};

const drawCardDocument = constructQuery({
  drawCard: {
    Attack: true,
    Children: true,
    id: true,
  },
});

The type of drawCardDocument would be TypedDocumentNode<{ listCards: { name: string, skills: string, Attack: string }, {}> which when consumed like this:

import { useQuery } from '@apollo/client';

const Component = () => {
  const { data, loading, error } = useQuery(drawCardDocument, { fetchPolicy: 'network-only' });
  
  ...
}

it would give the proper types.

One issue is extracting variables which I couldn't figure out, but it's surely possible.

This approach would instantly enable graphql-zeus to be used with @apollo/client, apollo-angular, urql and graphql-js. You can see the full list of compatible libs here.

ivasilov avatar Nov 29 '21 11:11 ivasilov

Great idea!

aexol avatar Nov 29 '21 14:11 aexol

This is exactly what I've been looking for. Would be great if this was implemented

thdxr avatar Mar 17 '22 17:03 thdxr