Dotan Simha’s graphql-code-generator is a really useful utility to generate integration code from GraphQL APIs for multiple languages.
As outlined in their docs, using the graphql-codegen cli with static config is straightforward:
1 2 3 |
graphql-codegen --config ./path/to/config.yml |
This post outlines how to use the code-generator CLI when the API is authenticated.
graphql-codegen uses cosmiconfig for loading the configuration. Thanks to cosmiconfig, this configuration can be a dynamic module instead of a static yaml/json file.
So we can have arbitrary logic inside the module. For instance if our graphql API is protected by HTTP basic auth, we can prompt the user for credentials and send them as a header:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
const prompts = require("prompts"); const promptCredentials = () => prompts([{ type: 'text', name: 'name', message: "Enter username" }, { type: 'text', name: 'password', message: "Enter password" }]); module.exports = (async () => { const user = await promptCredentials() return { overwrite: true, schema: [ { "http://localhost:9000/graphql": { headers: { Authorization: "Basic " + Buffer.from(`${user.name}:${user.password}`).toString("base64") } } } ], documents: "components/**/*.graphql", generates: { "api/graphql.tsx": { plugins: [ "typescript", "typescript-operations" ] } } } })() |
So the next time we run graphql-codegen --config ./path/to/config.js
we will be prompted for password.
You can, of course, also do things like keep the credentials in an uncommitted file and then read them in the config file.