Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

GraphQL Code Generator v3: @graphql-codegen/cli changes #8301

Merged
merged 13 commits into from
Aug 31, 2022
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/fast-pears-wonder.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@graphql-codegen/cli': minor
'@graphql-codegen/plugin-helpers': minor
---

Introduces support for TypeScript config file and a new preset lifecycle (required for `client-preset`)
1 change: 1 addition & 0 deletions packages/graphql-codegen-cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
"chalk": "^4.1.0",
"chokidar": "^3.5.2",
"cosmiconfig": "^7.0.0",
"cosmiconfig-typescript-loader": "4.0.0",
charlypoly marked this conversation as resolved.
Show resolved Hide resolved
"debounce": "^1.2.0",
"detect-indent": "^6.0.0",
"graphql-config": "^4.3.5",
Expand Down
34 changes: 19 additions & 15 deletions packages/graphql-codegen-cli/src/codegen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -202,21 +202,29 @@ export async function executeCodegen(input: CodegenContext | Types.Config): Prom
const outputConfig = generates[filename];
const hasPreset = !!outputConfig.preset;

const title = hasPreset
? `Generate to ${filename} (using EXPERIMENTAL preset "${outputConfig.preset}")`
: `Generate ${filename}`;
const title = `Generate to ${filename}`;

return {
title,
task: (_, subTask) => {
task: async (_, subTask) => {
let outputSchemaAst: GraphQLSchema;
let outputSchema: DocumentNode;
const outputFileTemplateConfig = outputConfig.config || {};
let outputDocuments: Types.DocumentFile[] = [];
const outputSpecificSchemas = normalizeInstanceOrArray<Types.Schema>(outputConfig.schema);
const outputSpecificDocuments = normalizeInstanceOrArray<Types.OperationDocument>(
outputConfig.documents
);
let outputSpecificDocuments = normalizeInstanceOrArray<Types.OperationDocument>(outputConfig.documents);

const preset: Types.OutputPreset | null = hasPreset
? typeof outputConfig.preset === 'string'
? await getPresetByName(outputConfig.preset, makeDefaultLoader(context.cwd))
: outputConfig.preset
: null;

if (preset) {
if (preset.prepareDocuments) {
charlypoly marked this conversation as resolved.
Show resolved Hide resolved
outputSpecificDocuments = await preset.prepareDocuments(filename, outputSpecificDocuments);
}
}

return subTask.newListr(
[
Expand Down Expand Up @@ -296,13 +304,9 @@ export async function executeCodegen(input: CodegenContext | Types.Config): Prom
normalizedPluginsArray.map(plugin => getPluginByName(Object.keys(plugin)[0], pluginLoader))
);

const preset: Types.OutputPreset = hasPreset
? typeof outputConfig.preset === 'string'
? await getPresetByName(outputConfig.preset, makeDefaultLoader(context.cwd))
: outputConfig.preset
: null;

const pluginMap: { [name: string]: CodegenPlugin } = Object.fromEntries(
const pluginMap: {
[name: string]: CodegenPlugin;
} = Object.fromEntries(
pluginPackages.map((pkg, i) => {
const plugin = normalizedPluginsArray[i];
const name = Object.keys(plugin)[0];
Expand All @@ -318,7 +322,7 @@ export async function executeCodegen(input: CodegenContext | Types.Config): Prom
emitLegacyCommonJSImports: shouldEmitLegacyCommonJSImports(config, filename),
};

const outputs: Types.GenerateOptions[] = hasPreset
const outputs: Types.GenerateOptions[] = preset
? await context.profiler.run(
async () =>
preset.buildGeneratesSection({
Expand Down
12 changes: 10 additions & 2 deletions packages/graphql-codegen-cli/src/config.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { cosmiconfig, defaultLoaders } from 'cosmiconfig';
import { TypeScriptLoader } from 'cosmiconfig-typescript-loader';
import { resolve } from 'path';
import {
DetailedError,
Expand All @@ -21,6 +22,8 @@ import { createHash } from 'crypto';

const { lstat } = promises;

export type CodegenConfig = Types.Config;

export type YamlCliFlags = {
config: string;
watch: boolean | string | string[];
Expand All @@ -38,7 +41,7 @@ export type YamlCliFlags = {
};

export function generateSearchPlaces(moduleName: string) {
const extensions = ['json', 'yaml', 'yml', 'js', 'config.js'];
const extensions = ['json', 'yaml', 'yml', 'js', 'ts', 'config.js'];
// gives codegen.json...
const regular = extensions.map(ext => `${moduleName}.${ext}`);
// gives .codegenrc.json... but no .codegenrc.config.js
Expand All @@ -47,7 +50,7 @@ export function generateSearchPlaces(moduleName: string) {
return [...regular.concat(dot), 'package.json'];
}

function customLoader(ext: 'json' | 'yaml' | 'js') {
function customLoader(ext: 'json' | 'yaml' | 'js' | 'ts') {
function loader(filepath: string, content: string) {
if (typeof process !== 'undefined' && 'env' in process) {
content = env(content);
Expand All @@ -70,6 +73,10 @@ function customLoader(ext: 'json' | 'yaml' | 'js') {
if (ext === 'js') {
return defaultLoaders['.js'](filepath, content);
}

if (ext === 'ts') {
return TypeScriptLoader()(filepath, content);
}
}

return loader;
Expand Down Expand Up @@ -124,6 +131,7 @@ export async function loadCodegenConfig({
'.yaml': customLoader('yaml'),
'.yml': customLoader('yaml'),
'.js': customLoader('js'),
'.ts': customLoader('ts'),
charlypoly marked this conversation as resolved.
Show resolved Hide resolved
noExt: customLoader('yaml'),
...customLoaders,
},
Expand Down
1 change: 1 addition & 0 deletions packages/graphql-codegen-cli/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ export * from './init/index.js';
export * from './utils/cli-error.js';
export * from './cli.js';
export * from './graphql-config.js';
export { CodegenConfig } from './config.js';
14 changes: 7 additions & 7 deletions packages/graphql-codegen-cli/src/presets.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { DetailedError, Types } from '@graphql-codegen/plugin-helpers';
import { Types } from '@graphql-codegen/plugin-helpers';
import { resolve } from 'path';

export async function getPresetByName(
Expand Down Expand Up @@ -31,9 +31,9 @@ export async function getPresetByName(
/** ESM Error code */
err.code !== 'ERR_MODULE_NOT_FOUND'
) {
throw new DetailedError(
`Unable to load preset matching ${name}`,
`
throw new Error(
charlypoly marked this conversation as resolved.
Show resolved Hide resolved
`Unable to load preset matching ${name}

Unable to load preset matching '${name}'.
Reason:
${err.message}
Expand All @@ -51,9 +51,9 @@ export async function getPresetByName(
)
.join('');

throw new DetailedError(
`Unable to find preset matching ${name}`,
`
throw new Error(
`Unable to find preset matching ${name}

Unable to find preset matching '${name}'
Install one of the following packages:

Expand Down
2 changes: 1 addition & 1 deletion packages/graphql-codegen-cli/src/utils/watcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ export const createWatcher = (
.map(filename => ({ filename, config: normalizeOutputParam(config.generates[filename]) }))
.forEach(entry => {
if (entry.config.preset) {
const extension = entry.config.presetConfig && entry.config.presetConfig.extension;
const extension = entry.config.presetConfig && (entry.config.presetConfig as any).extension;
charlypoly marked this conversation as resolved.
Show resolved Hide resolved
if (extension) {
ignored.push(join(entry.filename, '**', '*' + extension));
}
Expand Down
1 change: 1 addition & 0 deletions packages/utils/plugins-helpers/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ export * from './errors.js';
export * from './getCachedDocumentNodeFromSchema.js';
export * from './oldVisit.js';
export * from './profiler.js';
export { Types } from './types.js';
14 changes: 13 additions & 1 deletion packages/utils/plugins-helpers/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,14 @@ export namespace Types {
export type NamedPreset = string;
export type OutputConfig = NamedPlugin | ConfiguredPlugin;

export type PresetNamesBase =
charlypoly marked this conversation as resolved.
Show resolved Hide resolved
| 'client'
| 'near-operation-file'
| 'gql-tag-operations'
| 'graphql-modules'
| 'import-types-preset';
export type PresetNames = `${PresetNamesBase}-preset` | PresetNamesBase;

/**
* @additionalProperties false
*/
Expand All @@ -242,7 +250,7 @@ export namespace Types {
*
* List of available presets: https://graphql-code-generator.com/docs/presets/presets-index
*/
preset?: string | OutputPreset;
preset?: PresetNames | OutputPreset;
/**
* @description If your setup uses Preset to have a more dynamic setup and output, set the configuration object of your preset here.
*
Expand Down Expand Up @@ -330,6 +338,10 @@ export namespace Types {

export type OutputPreset<TPresetConfig = any> = {
buildGeneratesSection: (options: PresetFnArgs<TPresetConfig>) => Promisable<GenerateOptions[]>;
prepareDocuments?: (
outputFilePath: string,
outputSpecificDocuments: Types.OperationDocument[]
) => Promisable<Types.OperationDocument[]>;
};

/* Require Extensions */
Expand Down
2 changes: 1 addition & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -5760,7 +5760,7 @@ cosmiconfig-toml-loader@1.0.0:
dependencies:
"@iarna/toml" "^2.2.5"

cosmiconfig-typescript-loader@^4.0.0:
cosmiconfig-typescript-loader@4.0.0, cosmiconfig-typescript-loader@^4.0.0:
version "4.0.0"
resolved "https://registry.yarnpkg.com/cosmiconfig-typescript-loader/-/cosmiconfig-typescript-loader-4.0.0.tgz#4a6d856c1281135197346a6f64dfa73a9cd9fefa"
integrity sha512-cVpucSc2Tf+VPwCCR7SZzmQTQkPbkk4O01yXsYqXBIbjE1bhwqSyAgYQkRK1un4i0OPziTleqFhdkmOc4RQ/9g==
Expand Down