I'm using the hooks such as useQuery
from @apollo/client
in my react app for querying my AppSync backend. I have defined the schema in my Serverless AppSync project in a separate repo. In order to get intellisense in my IDE for the graphql schema in my React project, i'll need to duplicate my schema into my react app, and try and keep it up to date as I build out the schema on the backend. What are people using/doing to get around the duplication of the same schema across client and server projects? At the minute I have a schema.graphql
file in both the react project and serverless project, however it feels like a 'smell' that i've missed something, or doing something wrong? Any help is appreciated
I highly recommend using a code generation tool that uses your original schema as the source.
GraphQL Code Generator is a package that you can easily incorporate into a React app or similar. Once you add it to your project, you can run yarn graphql-codegen init
(assuming you use Yarn; there are options for npm, etc.) and it will ask a series of questions to generate a YAML configuration file. You then can add a command like yarn generate
that references that file.
Here's an example of the config I created for my project:
overwrite: true
schema: "http://localhost:8080/query"
documents: "./src/**/*.graphql"
generates:
src/generated/graphql.tsx:
plugins:
- "typescript"
- "typescript-operations"
- "typescript-react-query"
./graphql.schema.json:
plugins:
- "introspection"
When you run the yarn generate
command, it fetches your schema from your running back-end service (you'll need to make sure your service has GraphQL introspection enabled), combines that with your client-side queries, and then generates everything necessary to interact with your service. In my case, I use react-query
, and it creates a per-operation wrapper around useQuery
, e.g., useWidgetsQuery
. It works great.
I have no affiliation with the project, I'm just a fan.
If you also use code generation on the back end (through another project, depending on your back-end language), it means you can write your schema, etc. once and then generate a huge amount of types and wiring that is easy to keep in sync across projects.
© 2022 - 2024 — McMap. All rights reserved.