Last active
September 28, 2022 15:04
-
-
Save adamkl/27539b3a8129f23e3576bfc37b3ea235 to your computer and use it in GitHub Desktop.
Generating typescript definitions from .graphql files using apollo-codegen and graphql-code-generator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { introspectSchema } = require("apollo-codegen"); | |
const { executeWithOptions } = require("graphql-code-generator/dist/cli"); | |
const fs = require("fs"); | |
const path = require("path"); | |
const graphqlPath = "./src/graphql/"; | |
const schemaInput = "./src/graphql/temp.graphql"; | |
const jsonOutput = "./src/graphql/temp.json"; | |
const dtsOutput = "./src/graphql/domain.d.ts"; | |
function regen() { | |
cleanTempFiles(); | |
combineSchema(schemaInput); | |
introspectSchema(schemaInput, jsonOutput) | |
.then(async () => { | |
const dts = await executeWithOptions({ | |
file: jsonOutput, | |
out: dtsOutput, | |
template: "typescript", | |
schema: true | |
}); | |
fs.writeFileSync(dts[0].filename, dts[0].content); | |
}) | |
.catch(err => { | |
console.log(err); | |
}) | |
.then(() => { | |
cleanTempFiles(); | |
}); | |
} | |
function cleanTempFiles() { | |
if (fs.existsSync(schemaInput)) { | |
fs.unlinkSync(schemaInput); | |
} | |
if (fs.existsSync(jsonOutput)) { | |
fs.unlinkSync(jsonOutput); | |
} | |
} | |
function combineSchema(outputFilename) { | |
const files = fs.readdirSync(graphqlPath); | |
const schemas = files.filter(f => f.endsWith(".graphql")); | |
const outputFile = fs.openSync(outputFilename, "ax"); | |
schemas.forEach(s => | |
fs.appendFileSync(outputFile, fs.readFileSync(path.resolve(graphqlPath, s))) | |
); | |
fs.closeSync(outputFile); | |
} | |
regen(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment