github logaretm/villus v1.0.0-alpha.2

latest releases: v3.4.0, v3.3.0, v3.2.0...
pre-release4 years ago

tldr:

Breaking change, now useQuery, useMutation, useSubscription and Query, Mutation and Subscription components will no longer expose an errors prop/slot-prop and will instead expose a single error prop/slot-prop

This PR adds the ability to fully type responses returned from executing queries, mutations, and subscriptions.

Typed Queries

You can type your queries like this:

interface Post {
  id: number;
  title: string;
  slug: string;
  isLiked: boolean;
}

interface PostQueryResponse {
  posts: Post[];
}

const { data } = useQuery<PostQueryResponse>({ query: '{ posts { id title } }' });

return { data };

You can also type your variables:

interface Post {
  id: number;
  title: string;
  slug: string;
  isLiked: boolean;
}

interface FindPostQueryResponse {
  post: Post;
}

interface PostQueryVariables {
  id: number;
}

const { data } = useQuery<FindPostQueryResponse, PostQueryVariables>({
  query: `
    query FindPost($id: Int!) {
      post(id: $id) { id title }
    }`,
  variables: { id: 12 }
});

return { data };

And you will get typing support when providing variables to your query, the useMutation function is identical to useQuery.

Typed Subscriptions

First, you can type the response just like previously seen with useQuery:

interface Message {
  id: number;
  message: string;
}

const { data } = useSubscription<Message>({ query: `subscription { newMessages }` });

return { messages: data };

This isn't very useful because subscriptions are event-based, meaning rarely you will be using a single return value from the active subscription, that is why useSubscription accepts a reducer that acts as subscription handler, this PR allows you to fully type-proof it:

interface Message {
  id: number;
  message: string;
}


const { data } = useSubscription<Message, string[]>(
  { query: `subscription { newMessages }` },
  (oldMessages, response) => {
    if (!response.data || !oldMessages) {
      return oldMessages || [];
    }

    return [...oldMessages, response.data.message];
  }
);

Both oldMessages and response will be typed and data will now have a type of string[] instead of Message.


Typed Errors

This is a breaking change, now useQuery, useMutation, useSubscription and Query, Mutation and Subscription components will no longer expose an errors prop/slot-prop and will instead expose a single error prop/slot-prop, that error object is typed as such:

interface CombinedError extends Error {
  name: 'CombinedError';
  message: string;
  response: any;
  networkError?: Error;
  graphqlErrors?: GraphQLError[];
  isGraphQLError: boolean;
}

This allows you to have better handling and fine-grained control over which error type to handle.

Don't miss a new villus release

NewReleases is sending notifications on new releases.