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

add support for useImplementingTypes #125

Merged
merged 10 commits into from
Apr 11, 2023
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 73 additions & 15 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,12 @@
import { ASTKindToNode, ListTypeNode, NamedTypeNode, parse, printSchema, TypeNode } from 'graphql';
import {
parse,
printSchema,
TypeNode,
ASTKindToNode,
ListTypeNode,
NamedTypeNode,
ObjectTypeDefinitionNode,
} from 'graphql';
import { faker } from '@faker-js/faker';
import casual from 'casual';
import { oldVisit, PluginFunction, resolveExternalModuleAndFn } from '@graphql-codegen/plugin-helpers';
Expand Down Expand Up @@ -26,6 +34,7 @@ type Options<T = TypeNode> = {
generateLibrary: 'casual' | 'faker';
fieldGeneration?: TypeFieldMap;
enumsAsTypes?: boolean;
useImplementingTypes: boolean;
};

const convertName = (value: string, fn: (v: string) => string, transformUnderscore: boolean): string => {
Expand Down Expand Up @@ -230,6 +239,17 @@ const handleValueGeneration = (
return baseGenerator();
};

const getNamedImplementType = (opts: Options<TypeItem['types']>): string => {
if (!opts.currentType || !('name' in opts.currentType)) {
return '';
}

const name = opts.currentType.name.value;
const casedName = createNameConverter(opts.typeNamesConvention, opts.transformUnderscore)(name);

return `${toMockName(name, casedName, opts.prefix)}()`;
};

const getNamedType = (opts: Options<NamedTypeNode>): string | number | boolean => {
if (!opts.currentType) {
return '';
Expand Down Expand Up @@ -264,8 +284,14 @@ const getNamedType = (opts: Options<NamedTypeNode>): string | number | boolean =
return handleValueGeneration(opts, customScalar, mockValueGenerator.integer);
}
default: {
const foundType = opts.types.find((enumType: TypeItem) => enumType.name === name);
if (foundType) {
const foundTypes = opts.types.filter((foundType: TypeItem) => {
if (foundType.types && 'interfaces' in foundType.types)
return foundType.types.interfaces.every((item) => item.name.value === name);
return foundType.name === name;
});

if (foundTypes.length) {
const foundType = foundTypes[0];
switch (foundType.type) {
case 'enum': {
// It's an enum
Expand Down Expand Up @@ -300,6 +326,15 @@ const getNamedType = (opts: Options<NamedTypeNode>): string | number | boolean =
foundType.name === 'Date' ? mockValueGenerator.date : mockValueGenerator.word,
);
}
case 'implement':
return foundTypes
.map((implementType: TypeItem) =>
getNamedImplementType({
...opts,
currentType: implementType.types,
}),
)
.join(' || ');
default:
throw `foundType is unknown: ${foundType.name}: ${foundType.type}`;
}
Expand Down Expand Up @@ -470,13 +505,14 @@ export interface TypescriptMocksPluginConfig {
fieldGeneration?: TypeFieldMap;
locale?: string;
enumsAsTypes?: boolean;
useImplementingTypes?: boolean;
}

interface TypeItem {
name: string;
type: 'enum' | 'scalar' | 'union';
type: 'enum' | 'scalar' | 'union' | 'implement';
values?: string[];
types?: readonly NamedTypeNode[];
types?: readonly NamedTypeNode[] | ObjectTypeDefinitionNode;
}

type VisitFn<TAnyNode, TVisitedNode = TAnyNode> = (
Expand Down Expand Up @@ -516,14 +552,15 @@ export const plugin: PluginFunction<TypescriptMocksPluginConfig> = (schema, docu
const dynamicValues = !!config.dynamicValues;
const generateLibrary = config.generateLibrary || 'casual';
const enumsAsTypes = config.enumsAsTypes ?? false;
const useImplementingTypes = config.useImplementingTypes ?? false;

if (generateLibrary === 'faker' && config.locale) {
faker.setLocale(config.locale);
}

// List of types that are enums
const types: TypeItem[] = [];
const visitor: VisitorType = {
const typeVisitor: VisitorType = {
EnumTypeDefinition: (node) => {
const name = node.name.value;
if (!types.find((enumType: TypeItem) => enumType.name === name)) {
Expand All @@ -544,6 +581,32 @@ export const plugin: PluginFunction<TypescriptMocksPluginConfig> = (schema, docu
});
}
},
ObjectTypeDefinition: (node) => {
// This function triggered per each type
const typeName = node.name.value;

if (config.useImplementingTypes && !config.fieldGeneration) {
if (!types.find((objectType) => objectType.name === typeName)) {
node.interfaces.length &&
types.push({
name: typeName,
type: 'implement',
types: node,
});
}
}
},
ScalarTypeDefinition: (node) => {
const name = node.name.value;
if (!types.find((scalarType) => scalarType.name === name)) {
types.push({
name,
type: 'scalar',
});
}
},
};
const visitor: VisitorType = {
FieldDefinition: (node) => {
const fieldName = node.name.value;

Expand All @@ -568,6 +631,7 @@ export const plugin: PluginFunction<TypescriptMocksPluginConfig> = (schema, docu
generateLibrary,
fieldGeneration: config.fieldGeneration,
enumsAsTypes,
useImplementingTypes,
});

return ` ${fieldName}: overrides && overrides.hasOwnProperty('${fieldName}') ? overrides.${fieldName}! : ${value},`;
Expand Down Expand Up @@ -601,6 +665,7 @@ export const plugin: PluginFunction<TypescriptMocksPluginConfig> = (schema, docu
generateLibrary,
fieldGeneration: config.fieldGeneration,
enumsAsTypes,
useImplementingTypes,
});

return ` ${field.name.value}: overrides && overrides.hasOwnProperty('${field.name.value}') ? overrides.${field.name.value}! : ${value},`;
Expand Down Expand Up @@ -665,17 +730,10 @@ export const plugin: PluginFunction<TypescriptMocksPluginConfig> = (schema, docu
},
};
},
ScalarTypeDefinition: (node) => {
const name = node.name.value;
if (!types.find((enumType) => enumType.name === name)) {
types.push({
name,
type: 'scalar',
});
}
},
};

// run on the types first
oldVisit(astNode, { leave: typeVisitor });
const result = oldVisit(astNode, { leave: visitor });
const definitions = result.definitions.filter((definition: any) => !!definition);
const typesFile = config.typesFile ? config.typesFile.replace(/\.[\w]+$/, '') : null;
Expand Down
Loading