Created
November 15, 2023 20:16
-
-
Save lpessoa/26b850b9437522f61c0ce8cf12d1e14d to your computer and use it in GitHub Desktop.
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
/* eslint-disable no-console */ | |
import { NestFactory } from '@nestjs/core'; | |
import { | |
GraphQLSchemaBuilderModule, | |
GraphQLSchemaFactory, | |
} from '@nestjs/graphql'; | |
import { printSchema } from 'graphql'; | |
import fs from 'fs/promises'; | |
import f from 'fs'; | |
import path from 'path'; | |
import { exit } from 'process'; | |
import { glob } from 'glob'; | |
import chalk from 'chalk'; | |
import { INestApplication } from '@nestjs/common'; | |
import ora from 'ora'; | |
async function generateSchema() { | |
const p = ora('generating schema...').start(); | |
let app: INestApplication; | |
app = await NestFactory.create(GraphQLSchemaBuilderModule, { | |
logger: false, | |
}); | |
//console.log(chalk.bold.blueBright('initializing app...')); | |
await app.init(); | |
const gqlSchemaFactory = app.get(GraphQLSchemaFactory); | |
const gqlPath = 'schema/schema.gql'; | |
p.succeed().start('fetching resolvers...'); | |
//console.log(chalk.bold.blueBright('fetching resolvers...')); | |
const jsfiles = await glob('./src/**/*.resolver.ts', { absolute: true }); | |
const resolvers = []; | |
for (let i = 0; i < jsfiles.length; ++i) { | |
const mod = await import(jsfiles[i]); | |
const klass = mod[Object.keys(mod)[0]]; | |
resolvers.push(klass); | |
} | |
//console.log(chalk.bold.blueBright('generating schema...')); | |
const schema = await gqlSchemaFactory.create(resolvers); | |
const strSchema = printSchema(schema); | |
if (!f.existsSync(gqlPath)) { | |
f.mkdirSync(path.dirname(gqlPath)); | |
} | |
//console.log(chalk.bold.blueBright(`writing schema to ${gqlPath} ...`)); | |
await fs.writeFile(gqlPath, strSchema); | |
//console.log(chalk.bold.green(`successfuly wrote schema to ${gqlPath}.`)); | |
app.close(); | |
p.succeed().info('finished').stop(); | |
} | |
(async () => { | |
try { | |
await generateSchema(); | |
} catch (e) { | |
console.error(chalk.bold.red(`error while generating SDL: ${e}`)); | |
exit(1); | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment