Skip to content

Add support for oneOf directive #180

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

Merged
Merged
Show file tree
Hide file tree
Changes from all 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
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"dependencies": {
"@faker-js/faker": "^8.4.1",
"@graphql-codegen/plugin-helpers": "^5.0.4",
"@graphql-tools/utils": "^10.7.2",
"casual": "^1.6.2",
"change-case-all": "^1.0.15",
"indefinite": "^2.4.1",
Expand All @@ -40,6 +41,7 @@
"@graphql-codegen/testing": "^3.0.3",
"@graphql-codegen/typescript": "^4.0.7",
"@types/jest": "^27.0.2",
"@types/indefinite": "^2.3.4",
"@typescript-eslint/eslint-plugin": "^5.1.0",
"@typescript-eslint/parser": "^5.1.0",
"auto": "^11.1.6",
Expand All @@ -57,7 +59,7 @@
"prettier": "^2.4.1",
"prettier-config-landr": "^0.2.0",
"ts-jest": "^27.0.7",
"typescript": "^4.4.4"
"typescript": "^5.7.3"
},
"sideEffects": false,
"scripts": {
Expand Down
135 changes: 69 additions & 66 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,10 @@
import {
parse,
printSchema,
TypeNode,
ASTKindToNode,
ListTypeNode,
NamedTypeNode,
ObjectTypeDefinitionNode,
} from 'graphql';
import { parse, TypeNode, ASTKindToNode, ListTypeNode, NamedTypeNode, ObjectTypeDefinitionNode } from 'graphql';
import * as allFakerLocales from '@faker-js/faker';
import casual from 'casual';
import { oldVisit, PluginFunction, resolveExternalModuleAndFn } from '@graphql-codegen/plugin-helpers';
import { sentenceCase } from 'sentence-case';
import a from 'indefinite';
import { printSchemaWithDirectives } from '@graphql-tools/utils';
import { setupFunctionTokens, setupMockValueGenerator } from './mockValueGenerator';

type NamingConvention = 'change-case-all#pascalCase' | 'keep' | string;
Expand Down Expand Up @@ -460,6 +453,7 @@ const getMockString = (
typesPrefix = '',
transformUnderscore: boolean,
typeNamesMapping?: Record<string, string>,
hasOneOfDirective = false,
) => {
const typeNameConverter = createNameConverter(typeNamesConvention, transformUnderscore);
const NewTypeName = typeNamesMapping[typeName] || typeName;
Expand All @@ -468,6 +462,10 @@ const getMockString = (
const typename = addTypename ? `\n __typename: '${typeName}',` : '';
const typenameReturnType = addTypename ? `{ __typename: '${typeName}' } & ` : '';

const overridesArgumentString = !hasOneOfDirective
? `overrides?: Partial<${casedNameWithPrefix}>`
: `override?: ${casedNameWithPrefix}`;

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because a Partial<T> could be completely empty, it won't work for an the override which, if supplied, needs to replace the entire mock rather than merging to satisfy typescript that we're not putting multiple fields together.

if (terminateCircularRelationships) {
const relationshipsToOmitInit =
terminateCircularRelationships === 'immediate' ? '_relationshipsToOmit' : 'new Set(_relationshipsToOmit)';
Expand All @@ -476,7 +474,7 @@ export const ${toMockName(
typeName,
casedName,
prefix,
)} = (overrides?: Partial<${casedNameWithPrefix}>, _relationshipsToOmit: Set<string> = new Set()): ${typenameReturnType}${casedNameWithPrefix} => {
)} = (${overridesArgumentString}, _relationshipsToOmit: Set<string> = new Set()): ${typenameReturnType}${casedNameWithPrefix} => {
const relationshipsToOmit: Set<string> = ${relationshipsToOmitInit};
relationshipsToOmit.add('${casedName}');
return {${typename}
Expand All @@ -489,7 +487,7 @@ export const ${toMockName(
typeName,
casedName,
prefix,
)} = (overrides?: Partial<${casedNameWithPrefix}>): ${typenameReturnType}${casedNameWithPrefix} => {
)} = (${overridesArgumentString}): ${typenameReturnType}${casedNameWithPrefix} => {
return {${typename}
${fields}
};
Expand Down Expand Up @@ -622,7 +620,8 @@ type VisitorType = { [K in keyof ASTKindToNode]?: VisitFn<ASTKindToNode[keyof AS
// https://astexplorer.net
// Paste your graphql schema in it, and you'll be able to see what the `astNode` will look like
export const plugin: PluginFunction<TypescriptMocksPluginConfig> = (schema, documents, config) => {
const printedSchema = printSchema(schema); // Returns a string representation of the schema
const printedSchema = printSchemaWithDirectives(schema); // Returns a string representation of the schema

const astNode = parse(printedSchema); // Transforms the string into ASTNode

if ('typenames' in config) {
Expand Down Expand Up @@ -690,6 +689,30 @@ export const plugin: PluginFunction<TypescriptMocksPluginConfig> = (schema, docu
}
},
};

const sharedGenerateMockOpts = {
customScalars: config.scalars,
defaultNullableToNull,
dynamicValues,
enumsAsTypes,
enumsPrefix: config.enumsPrefix,
enumValuesConvention,
fieldGeneration: config.fieldGeneration,
generateLibrary,
generatorLocale,
listElementCount,
nonNull: false,
prefix: config.prefix,
terminateCircularRelationships: getTerminateCircularRelationshipsConfig(config),
transformUnderscore,
typeNamesConvention,
typeNamesMapping,
types,
typesPrefix: config.typesPrefix,
useImplementingTypes,
useTypeImports,
};

const visitor: VisitorType = {
FieldDefinition: (node) => {
const fieldName = node.name.value;
Expand All @@ -700,27 +723,8 @@ export const plugin: PluginFunction<TypescriptMocksPluginConfig> = (schema, docu
const value = generateMockValue({
typeName,
fieldName,
types,
typeNamesConvention,
enumValuesConvention,
terminateCircularRelationships: getTerminateCircularRelationshipsConfig(config),
prefix: config.prefix,
typesPrefix: config.typesPrefix,
enumsPrefix: config.enumsPrefix,
currentType: node.type,
customScalars: config.scalars,
transformUnderscore,
listElementCount,
dynamicValues,
generateLibrary,
generatorLocale,
fieldGeneration: config.fieldGeneration,
enumsAsTypes,
useTypeImports,
useImplementingTypes,
defaultNullableToNull,
nonNull: false,
typeNamesMapping: config.typeNamesMapping,
...sharedGenerateMockOpts,
});

return ` ${fieldName}: overrides && overrides.hasOwnProperty('${fieldName}') ? overrides.${fieldName}! : ${value},`;
Expand All @@ -733,50 +737,49 @@ export const plugin: PluginFunction<TypescriptMocksPluginConfig> = (schema, docu
return {
typeName: fieldName,
mockFn: () => {
const mockFields = node.fields
? node.fields
.map((field) => {
const value = generateMockValue({
typeName: fieldName,
fieldName: field.name.value,
types,
typeNamesConvention,
enumValuesConvention,
terminateCircularRelationships: getTerminateCircularRelationshipsConfig(config),
prefix: config.prefix,
typesPrefix: config.typesPrefix,
enumsPrefix: config.enumsPrefix,
currentType: field.type,
customScalars: config.scalars,
transformUnderscore,
listElementCount,
dynamicValues,
generateLibrary,
generatorLocale,
fieldGeneration: config.fieldGeneration,
enumsAsTypes,
useTypeImports,
useImplementingTypes,
defaultNullableToNull,
nonNull: false,
typeNamesMapping: config.typeNamesMapping,
});

return ` ${field.name.value}: overrides && overrides.hasOwnProperty('${field.name.value}') ? overrides.${field.name.value}! : ${value},`;
})
.join('\n')
: '';
let mockFieldsString = '';

const { directives } = node;
const hasOneOfDirective = directives.some((directive) => directive.name.value === 'oneOf');

if (node.fields && node.fields.length > 0 && hasOneOfDirective) {
const field = node.fields[0];
const value = generateMockValue({
typeName: fieldName,
fieldName: field.name.value,
currentType: field.type,
...sharedGenerateMockOpts,
});

mockFieldsString = ` ...(override ? override : {${field.name.value} : ${value}}),`;
} else if (node.fields) {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this change to the mockFieldsString is the most significant change.

mockFieldsString = node.fields
.map((field) => {
const value = generateMockValue({
typeName: fieldName,
fieldName: field.name.value,
currentType: field.type,
...sharedGenerateMockOpts,
});

const valueWithOverride = `overrides && overrides.hasOwnProperty('${field.name.value}') ? overrides.${field.name.value}! : ${value}`;

return ` ${field.name.value}: ${valueWithOverride},`;
})
.join('\n');
}

return getMockString(
fieldName,
mockFields,
mockFieldsString,
typeNamesConvention,
getTerminateCircularRelationshipsConfig(config),
false,
config.prefix,
config.typesPrefix,
transformUnderscore,
typeNamesMapping,
hasOneOfDirective,
);
},
};
Expand Down
Loading
Loading