Skip to content

Instantly share code, notes, and snippets.

@angeloashmore
Last active December 8, 2021 23:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save angeloashmore/3a08e28c82e9d78ecb645af2258285a9 to your computer and use it in GitHub Desktop.
Save angeloashmore/3a08e28c82e9d78ecb645af2258285a9 to your computer and use it in GitHub Desktop.

How to setup GraphQL Code Generator for Prismic repositories

Note: This is not an officially supported solution. It's something that could work but may require some additional tweaks to be 100% usable.

To learn how to customize GraphQL Code Generator, see their documentation.

  1. Install packages

    npm i -D @graphql-codegen/cli @graphql-codegen/typescript @graphql-codegen/typescript-operations node-fetch@cjs @prismicio/client@beta ts-node
  2. Add a file named scripts/gen.ts. See the gist for file contents. Update it for your project (repository name, access token, source files, generated file name, etc.).

  3. Add a script to package.json

    {
      "scripts": {
        "gen": "ts-node-script --skip-project scripts/gen.ts"
      }
    }

When you need types to be generated, run the following command.

npm run gen
import * as prismic from "@prismicio/client";
import * as graphqlCodegen from "@graphql-codegen/cli";
import fetch from "node-fetch";
const repositoryName = "your-repo-name";
const accessToken = "your-access-token";
async function main() {
const restEndpoint = prismic.getEndpoint(repositoryName);
const graphqlEndpoint = `https://${repositoryName}.cdn.prismic.io/graphql`;
const client = prismic.createClient(restEndpoint, { fetch });
const ref = (await client.getMasterRef()).ref;
await graphqlCodegen.generate({
schema: {
[graphqlEndpoint]: {
headers: {
Authorization: `Token ${accessToken}`,
"Prismic-Ref": ref,
},
method: "GET",
},
},
documents: ["./pages/**/*.{ts,tsx}"],
generates: {
"./types.generated.ts": {
plugins: ["typescript", "typescript-operations"],
config: {
skipTypename: true,
avoidOptionals: true,
scalars: {
Date: "string",
DateTime: "string",
Json: "unknown",
Long: "number",
},
},
},
},
});
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment