acro5piano / typed-graphqlify

Build Typed GraphQL Queries in TypeScript without the code generation
https://www.npmjs.com/package/typed-graphqlify
MIT License
649 stars 29 forks source link

graphql-tag integration #8

Open acro5piano opened 5 years ago

acro5piano commented 5 years ago

I would like to keep this library thin, but every time writing

import gql from 'graphql-tag'

const getUser = graphqlify.query({ getUser: ... })

const Compoent = graphql(gql(getUser))({ data }: Props) => ...

is annoying, so it would be great to have gql compatible mode.

If we implement it, the code should be like this:

// in bootstrap
import { useGraphQLTag } from 'typed-graphqlify'
useGraphQLTag(true)

// in Component.ts
const getUser = graphqlify.query({ getUser: ... })

const Compoent = graphql(getUser)({ data }: Props) => ...
capaj commented 5 years ago

agree. I'd say gql-tag usage is more probable than a user wanting a plain string output. So it should default to returning gql-tag.

I'd model it something like:

const getUserGqlTag = graphqlify.query({ getUser: ... })
const getUserString = graphqlify.query.asString({ getUser: ... })

because then user can choose string/gql-tag for each individual query.

acro5piano commented 5 years ago

Thank you for your response.

asString property looks flexible. I will try to implement it after #10 merged!

hcharley commented 2 years ago

fwiw, I use this little helper:

/* ./lib/to-operation.ts */
import { gql } from '@apollo/client';
import { CompiledResult } from 'typed-graphqlify';

export const toOperation = <D, V>(value: CompiledResult<D, V>) =>
  gql(value.toString());
/* ./lib/gql-operation.ts */
import { CompiledResult } from 'typed-graphqlify';
import { toOperation } from './to-operation';

export class GqlOperation<D, V> {
  constructor(public tag: CompiledResult<D, V>) {}

  get type(): D {
    return this.tag.result.data;
  }

  get operation() {
    return toOperation(this.tag);
  }
}
/* ./domain/post.ts */
import { query, types } from 'typed-graphqlify';
import { GqlOperation } from '../lib/gql-operation';

export const getPostQuery = new GqlOperation(
  query('getPost', {
    post: {
      name: types.string,
    },
  })
);

export const getPostsQuery = new GqlOperation(
  query('getPosts', {
    post: {
      name: types.string,
    },
  })
);
export function PostList(props: PropsWithChildren<PostListProps>) {
  const { loading, error, data } = useQuery<typeof getPostsQuery.type>(
    getPostsQuery.operation
  );

  return (
    <StyledPostList>
      <h2>Post List</h2>
      {JSON.stringify({ loading, error, data })}
      {props.children}
    </StyledPostList>
  );
}