-
-
Save ifiokjr/e1c2755a4d8b39b5a7dbc123800319c7 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 hidden or 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