Types generation
Types are only enforced between the backend and frontend with GraphQL at runtime (when sending the request). What happens if we change something in the backend and forget to reflect this change in the frontend? It will crash. Let's make sure this doesn't happen.
We are going to generate types from the GraphQL schema with Apollo CLI. Then use them on the frontend. If something changes on the backend, Typescript will let us know.
yarn add apolloStart the server:
$ ts-node -T src/index.tsCreate a new package:
mkdir packages/typesGenerate the types:
apollo codegen:generate --target=typescript --queries='packages/web/src/**/*.tsx' --endpoint=http://localhost:8080/graphql --tagName=gql --outputFlat packages/types/graphql.d.tsTo fix Apollo does not support anonymous operations change:
const { data, loading, error } = useQuery(gql`
{
health {
ok
}
}
`);to
const { data, loading, error } = useQuery(gql`
query health {
health {
ok
}
}
`);You should now see types.d.ts in packages/types. Let's create a package.json and index.d.ts for this package:
and now use Lerna to add the types to web:
We can now import the variables:
and enforce types with queries and mutations:
yarn add <dependency> won't work in anymore. Use lerna add dependency> --scope=web instead.
Later, if we have a React Native app or a queue worker, we will be able to reuse the types from this package.
Last updated
Was this helpful?