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 terminateCircularRelationships option #31

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
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,6 @@ npm-debug.log*
yarn-debug.log*
yarn-error.log*

# generated test file
/tests/circular-mocks/mocks.ts

5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@ Defines the file path containing all GraphQL types. This file can also be genera

Adds `__typename` property to mock data

### terminateCircularRelationships (`boolean`, defaultValue: `false`)

When enabled, prevents circular relationships from triggering infinite recursion. After the first resolution of a
specific type in a particular call stack, subsequent resolutions will return an empty object cast to the correct type.

### prefix (`string`, defaultValue: `a` for constants & `an` for vowels)

The prefix to add to the mock function name. Cannot be empty since it will clash with the associated
Expand Down
1 change: 1 addition & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ module.exports = {
transform: {
'^.+\\.tsx?$': 'ts-jest',
},
globalSetup: './tests/circular-mocks/create-mocks.ts',
};
47 changes: 41 additions & 6 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ const getNamedType = (
types: TypeItem[],
typenamesConvention: NamingConvention,
enumValuesConvention: NamingConvention,
terminateCircularRelationships: boolean,
prefix?: string,
namedType?: NamedTypeNode,
customScalars?: ScalarMap,
Expand Down Expand Up @@ -113,6 +114,7 @@ const getNamedType = (
types,
typenamesConvention,
enumValuesConvention,
terminateCircularRelationships,
prefix,
foundType.types && foundType.types[0],
);
Expand Down Expand Up @@ -150,7 +152,15 @@ const getNamedType = (
throw `foundType is unknown: ${foundType.name}: ${foundType.type}`;
}
}
return `${toMockName(name, name, prefix)}()`;
if (terminateCircularRelationships) {
return `relationshipsToOmit.has('${name}') ? {} as ${name} : ${toMockName(
name,
name,
prefix,
)}({}, relationshipsToOmit)`;
} else {
return `${toMockName(name, name, prefix)}()`;
}
}
}
};
Expand All @@ -161,6 +171,7 @@ const generateMockValue = (
types: TypeItem[],
typenamesConvention: NamingConvention,
enumValuesConvention: NamingConvention,
terminateCircularRelationships: boolean,
prefix: string | undefined,
currentType: TypeNode,
customScalars: ScalarMap,
Expand All @@ -173,6 +184,7 @@ const generateMockValue = (
types,
typenamesConvention,
enumValuesConvention,
terminateCircularRelationships,
prefix,
currentType as NamedTypeNode,
customScalars,
Expand All @@ -184,6 +196,7 @@ const generateMockValue = (
types,
typenamesConvention,
enumValuesConvention,
terminateCircularRelationships,
prefix,
currentType.type,
customScalars,
Expand All @@ -195,6 +208,7 @@ const generateMockValue = (
types,
typenamesConvention,
enumValuesConvention,
terminateCircularRelationships,
prefix,
currentType.type,
customScalars,
Expand All @@ -208,22 +222,38 @@ const getMockString = (
typeName: string,
fields: string,
typenamesConvention: NamingConvention,
terminateCircularRelationships: boolean,
addTypename = false,
prefix,
typesPrefix = '',
) => {
const casedName = createNameConverter(typenamesConvention)(typeName);
const typename = addTypename ? `\n __typename: '${casedName}',` : '';
return `

if (terminateCircularRelationships) {
return `
export const ${toMockName(
typeName,
casedName,
prefix,
)} = (overrides?: Partial<${typesPrefix}${casedName}>, relationshipsToOmit: Set<string> = new Set()): ${typesPrefix}${casedName} => {
relationshipsToOmit.add('${casedName}');
return {${typename}
${fields}
};
};`;
} else {
return `
export const ${toMockName(
typeName,
casedName,
prefix,
)} = (overrides?: Partial<${typesPrefix}${casedName}>): ${typesPrefix}${casedName} => {
typeName,
casedName,
prefix,
)} = (overrides?: Partial<${typesPrefix}${casedName}>): ${typesPrefix}${casedName} => {
return {${typename}
${fields}
};
};`;
}
};

type ScalarGeneratorName = keyof Casual.Casual | keyof Casual.functions;
Expand All @@ -243,6 +273,7 @@ export interface TypescriptMocksPluginConfig {
addTypename?: boolean;
prefix?: string;
scalars?: ScalarMap;
terminateCircularRelationships?: boolean;
typesPrefix?: string;
}

Expand Down Expand Up @@ -299,6 +330,7 @@ export const plugin: PluginFunction<TypescriptMocksPluginConfig> = (schema, docu
types,
typenamesConvention,
enumValuesConvention,
!!config.terminateCircularRelationships,
config.prefix,
node.type,
config.scalars,
Expand All @@ -323,6 +355,7 @@ export const plugin: PluginFunction<TypescriptMocksPluginConfig> = (schema, docu
types,
typenamesConvention,
enumValuesConvention,
!!config.terminateCircularRelationships,
config.prefix,
field.type,
config.scalars,
Expand All @@ -337,6 +370,7 @@ export const plugin: PluginFunction<TypescriptMocksPluginConfig> = (schema, docu
fieldName,
mockFields,
typenamesConvention,
!!config.terminateCircularRelationships,
false,
config.prefix,
config.typesPrefix,
Expand All @@ -362,6 +396,7 @@ export const plugin: PluginFunction<TypescriptMocksPluginConfig> = (schema, docu
typeName,
mockFields,
typenamesConvention,
!!config.terminateCircularRelationships,
!!config.addTypename,
config.prefix,
config.typesPrefix,
Expand Down
41 changes: 41 additions & 0 deletions tests/__snapshots__/typescript-mock-data.spec.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -670,3 +670,44 @@ export const aUSER = (overrides?: Partial<USER>): USER => {
};
"
`;

exports[`should use relationshipsToOmit argument to terminate circular relationships with terminateCircularRelationships enabled 1`] = `
"
export const anAbcType = (overrides?: Partial<AbcType>, relationshipsToOmit: Set<string> = new Set()): AbcType => {
relationshipsToOmit.add('AbcType');
return {
abc: overrides && overrides.hasOwnProperty('abc') ? overrides.abc! : 'sit',
};
};

export const anAvatar = (overrides?: Partial<Avatar>, relationshipsToOmit: Set<string> = new Set()): Avatar => {
relationshipsToOmit.add('Avatar');
return {
id: overrides && overrides.hasOwnProperty('id') ? overrides.id! : '0550ff93-dd31-49b4-8c38-ff1cb68bdc38',
url: overrides && overrides.hasOwnProperty('url') ? overrides.url! : 'aliquid',
};
};

export const anUpdateUserInput = (overrides?: Partial<UpdateUserInput>, relationshipsToOmit: Set<string> = new Set()): UpdateUserInput => {
relationshipsToOmit.add('UpdateUserInput');
return {
id: overrides && overrides.hasOwnProperty('id') ? overrides.id! : '1d6a9360-c92b-4660-8e5f-04155047bddc',
login: overrides && overrides.hasOwnProperty('login') ? overrides.login! : 'qui',
avatar: overrides && overrides.hasOwnProperty('avatar') ? overrides.avatar! : relationshipsToOmit.has('Avatar') ? {} as Avatar : anAvatar({}, relationshipsToOmit),
};
};

export const aUser = (overrides?: Partial<User>, relationshipsToOmit: Set<string> = new Set()): User => {
relationshipsToOmit.add('User');
return {
id: overrides && overrides.hasOwnProperty('id') ? overrides.id! : 'a5756f00-41a6-422a-8a7d-d13ee6a63750',
creationDate: overrides && overrides.hasOwnProperty('creationDate') ? overrides.creationDate! : '1970-01-09T16:33:21.532Z',
login: overrides && overrides.hasOwnProperty('login') ? overrides.login! : 'libero',
avatar: overrides && overrides.hasOwnProperty('avatar') ? overrides.avatar! : relationshipsToOmit.has('Avatar') ? {} as Avatar : anAvatar({}, relationshipsToOmit),
status: overrides && overrides.hasOwnProperty('status') ? overrides.status! : Status.Online,
customStatus: overrides && overrides.hasOwnProperty('customStatus') ? overrides.customStatus! : AbcStatus.HasXyzStatus,
scalarValue: overrides && overrides.hasOwnProperty('scalarValue') ? overrides.scalarValue! : 'neque',
};
};
"
`;
21 changes: 21 additions & 0 deletions tests/circular-mocks/create-mocks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import fs from 'fs';
import { buildSchema } from 'graphql';
import { plugin } from '../../src';
export default async () => {
const circularSchema = buildSchema(/* GraphQL */ `
type A {
B: B!
C: C!
}
type B {
A: A!
}
type C {
aCollection: [A!]!
}
`);

const output = await plugin(circularSchema, [], { typesFile: './types.ts', terminateCircularRelationships: true });

fs.writeFileSync('./tests/circular-mocks/mocks.ts', output.toString());
};
12 changes: 12 additions & 0 deletions tests/circular-mocks/spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { aB, aC, anA } from './mocks';

it('should terminate circular relationships when terminateCircularRelationships is true', () => {
const a = anA();
expect(a).toEqual({ B: { A: {} }, C: { aCollection: [{}] } });

const b = aB();
expect(b).toEqual({ A: { B: {}, C: { aCollection: [{}] } } });

const c = aC();
expect(c).toEqual({ aCollection: [{ B: { A: {} }, C: {} }] });
});
12 changes: 12 additions & 0 deletions tests/circular-mocks/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
export type A = {
B: B;
C: C;
};

export type B = {
A: A;
};

export type C = {
aCollection: A[];
};
10 changes: 10 additions & 0 deletions tests/typescript-mock-data.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -232,3 +232,13 @@ it('should add typesPrefix to all types when option is specified', async () => {
expect(result).not.toMatch(/: User/);
expect(result).toMatchSnapshot();
});

it('should use relationshipsToOmit argument to terminate circular relationships with terminateCircularRelationships enabled', async () => {
const result = await plugin(testSchema, [], { terminateCircularRelationships: true });

expect(result).toBeDefined();
expect(result).toMatch(/relationshipsToOmit.add\('User'\)/);
expect(result).toMatch(/relationshipsToOmit.has\('Avatar'\) \? {} as Avatar : anAvatar\({}, relationshipsToOmit\)/);
expect(result).not.toMatch(/: anAvatar\(\)/);
expect(result).toMatchSnapshot();
});