zendesk / laika

Log, test, intercept and modify Apollo Client's operations
https://zendesk.github.io/laika
Apache License 2.0
122 stars 7 forks source link

Typed returned Data #59

Open jBernavaPrah opened 1 year ago

jBernavaPrah commented 1 year ago

Hi! Thanks for sharing this package!

It's possible to use Types during mocking?

I'm using graphql-codegen to generate all the Types for my graphQL endpoint.


export type ReturnDataQuery = { __typename?: 'Query', something?: string | null };

const intercept = laika.intercept({operationName: 'getUsers'});
// something like this:
intercept.mockResult<ReturnDataQuery>(
  {
  result: {
  data: {
         something: "ABC" // typescript checked
  }
  }
);

So this will be more easy create the mocked response, knowing what is required and what is not.

Thank!

danielvanmil commented 9 months ago

+1

For now we use https://the-guild.dev/graphql/codegen/plugins/typescript/typed-document-node and created a helper function like:

export function getLaikaMatcher<D, V>(query: ComponentDocument<D, V>): Matcher {
  return {operationName: (query.definitions[0] as OperationDefinitionNode).name.value};
}

and then use the generated typed document (GetAllAccountsDocument in this case):

laika.intercept(getLaikaMatcher(GetAllAccountsDocument)).mockResult(() => {
  const result: Data<typeof GetAllAccountsDocument> = {allAccounts: accounts};
  return {
    result: {data: result},
  };
});

This provides at least type safety when our API changes etc.

It would be nice when Laika could add the generics to the API so we can use typed-document-node without custom helper functions etc.

niieani commented 9 months ago

Good suggestion! PRs welcome.

bbrzoska commented 4 months ago

Adding one more suggestion: it would be nice if we could provide the operation document itself as the argument, i.e.:

laika.intercept({operation: QueryDocument})