Skip to content

Instantly share code, notes, and snippets.

@adamkl
Last active September 28, 2022 15:04
Show Gist options
  • Save adamkl/27539b3a8129f23e3576bfc37b3ea235 to your computer and use it in GitHub Desktop.
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
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