-
Notifications
You must be signed in to change notification settings - Fork 54
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
ardeois
merged 2 commits into
ardeois:main
from
curative:thomasobrien99/add-support-for-one-of-directive
Feb 6, 2025
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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
This file contains hidden or 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
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; | ||
|
@@ -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; | ||
|
@@ -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}`; | ||
|
||
if (terminateCircularRelationships) { | ||
const relationshipsToOmitInit = | ||
terminateCircularRelationships === 'immediate' ? '_relationshipsToOmit' : 'new Set(_relationshipsToOmit)'; | ||
|
@@ -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} | ||
|
@@ -489,7 +487,7 @@ export const ${toMockName( | |
typeName, | ||
casedName, | ||
prefix, | ||
)} = (overrides?: Partial<${casedNameWithPrefix}>): ${typenameReturnType}${casedNameWithPrefix} => { | ||
)} = (${overridesArgumentString}): ${typenameReturnType}${casedNameWithPrefix} => { | ||
return {${typename} | ||
${fields} | ||
}; | ||
|
@@ -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) { | ||
|
@@ -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; | ||
|
@@ -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},`; | ||
|
@@ -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({ | ||
thomasobrien99 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
typeName: fieldName, | ||
fieldName: field.name.value, | ||
currentType: field.type, | ||
...sharedGenerateMockOpts, | ||
}); | ||
|
||
mockFieldsString = ` ...(override ? override : {${field.name.value} : ${value}}),`; | ||
} else if (node.fields) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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, | ||
); | ||
}, | ||
}; | ||
|
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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.