GraphQL Codegen Static Data Plugin
This plugin for GraphQL Code Generator facilitates fetching data from a GraphQL server using specific queries and subsequently generates static TypeScript files that encapsulate this data.
Features
- Automated Data Fetching: Automatically fetches data from a GraphQL server using predefined queries.
- Static Data Export: Generates TypeScript files containing static constants with the fetched data.
Installation
To install the plugin, run:
npm install --save-dev @graphql-codegen/plugin-helpers graphql-request
Configuration
In your codegen.yml
file, the plugin should be configured as follows:
schema: "http://localhost:4000/graphql"
documents: "src/**/*.graphql"
generates:
src/generated/staticData.ts:
plugins:
- "path/to/your-plugin"
config:
url: "http://localhost:4000/graphql"
queries:
- |
query {
data {
foo
bar
}
}
- |
query {
otherData {
id
value
}
}
outputFile: "src/generated/staticData.ts"
Usage
-
Define your GraphQL queries to fetch the required static data.
-
Configure the plugin in your codegen.yml
file as shown above.
-
Run the GraphQL Code Generator:
npx graphql-codegen
-
The plugin will generate a TypeScript file containing static constants that hold the data fetched by your queries.
Output
The generated TypeScript file (staticData.ts
) will include static constants representing the results of your queries, structured as follows:
export const Query0 = {
data: {
boo: false,
bar: true
}
};
export const Query1 = {
otherData: {
id: 1,
value: 'example'
}
};
Development
To build the plugin for both CommonJS and ES Modules:
-
Ensure TypeScript is installed:
npm install --save-dev typescript
-
Execute the build scripts:
npm run build:cjs
npm run build:esm
-
The compiled files will be available in the cjs
and esm
directories.
License
This project is licensed under the MIT License - see the LICENSE file for details.
Acknowledgements