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

feat: add generatorLibrary options and allow faker to select #93

Merged
merged 12 commits into from
Sep 29, 2022
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
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,11 @@ When disabled, underscores will be retained for type names when the case is chan

When enabled, values will be generated dynamically when the mock function is called rather than statically when the mock function is generated. The values are generated consistently from a [casual seed](https://github.com/boo1ean/casual#seeding) that can be manually configured using the generated `seedMocks(seed: number)` function, as shown in [this test](https://github.com/JimmyPaolini/graphql-codegen-typescript-mock-data/blob/dynamic-mode/tests/dynamicValues/spec.ts#L13).

### generateLibrary (`'casual' | 'faker'`, defaultValue: `'casual'`)

Select a library to generate mock values. The default is [casual](https://github.com/boo1ean/casual), Other options include [faker](https://github.com/faker-js/faker).
casual dependents on Node API and cannot be executed in a browser. faker is useful when you want to use a mock function with the dynamicValues option enabled in the browser.

## Examples of usage

**codegen.yml**
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
"fakes"
],
"dependencies": {
"@faker-js/faker": "^7.5.0",
"@graphql-codegen/plugin-helpers": "^2.4.1",
"casual": "^1.6.2",
"indefinite": "^2.4.1",
Expand All @@ -36,7 +37,6 @@
"devDependencies": {
"@auto-it/conventional-commits": "^10.33.0",
"@graphql-codegen/testing": "^1.17.7",
"@types/faker": "^5.5.9",
Copy link
Contributor Author

Choose a reason for hiding this comment

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

It was probably left in there because it was forgotten to erase it, but now the type definitions have been imported into the repository and are no longer needed.
5a8cd1b

"@types/jest": "^27.0.2",
"@typescript-eslint/eslint-plugin": "^5.1.0",
"@typescript-eslint/parser": "^5.1.0",
Expand Down
37 changes: 22 additions & 15 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { pascalCase } from 'pascal-case';
import { upperCase } from 'upper-case';
import { sentenceCase } from 'sentence-case';
import a from 'indefinite';
import { setupFunctionTokens, setupMockValueGenerator } from './mockValueGenerator';

type NamingConvention = 'upper-case#upperCase' | 'pascal-case#pascalCase' | 'keep';

Expand All @@ -23,6 +24,7 @@ type Options<T = TypeNode> = {
transformUnderscore: boolean;
listElementCount: number;
dynamicValues: boolean;
generateLibrary: 'casual' | 'faker';
};

const convertName = (value: string, fn: (v: string) => string, transformUnderscore: boolean): string => {
Expand Down Expand Up @@ -104,22 +106,24 @@ const getNamedType = (opts: Options<NamedTypeNode>): string | number | boolean =
return '';
}

if (!opts.dynamicValues) casual.seed(hashedString(opts.typeName + opts.fieldName));
const mockValueGenerator = setupMockValueGenerator({
generateLibrary: opts.generateLibrary,
dynamicValues: opts.dynamicValues,
});
if (!opts.dynamicValues) mockValueGenerator.seed(hashedString(opts.typeName + opts.fieldName));
const name = opts.currentType.name.value;
const casedName = createNameConverter(opts.typenamesConvention, opts.transformUnderscore)(name);
switch (name) {
case 'String':
return opts.dynamicValues ? `casual.word` : `'${casual.word}'`;
return mockValueGenerator.word();
case 'Float':
return opts.dynamicValues
? `Math.round(casual.double(0, 10) * 100) / 100`
: Math.round(casual.double(0, 10) * 100) / 100;
return mockValueGenerator.float();
case 'ID':
return opts.dynamicValues ? `casual.uuid` : `'${casual.uuid}'`;
return mockValueGenerator.uuid();
case 'Boolean':
return opts.dynamicValues ? `casual.boolean` : casual.boolean;
return mockValueGenerator.boolean();
case 'Int':
return opts.dynamicValues ? `casual.integer(0, 9999)` : casual.integer(0, 9999);
return mockValueGenerator.integer();
default: {
const foundType = opts.types.find((enumType: TypeItem) => enumType.name === name);
if (foundType) {
Expand Down Expand Up @@ -151,11 +155,9 @@ const getNamedType = (opts: Options<NamedTypeNode>): string | number | boolean =
// mapping for this particular scalar
if (!customScalar || !customScalar.generator) {
if (foundType.name === 'Date') {
return opts.dynamicValues
? `new Date(casual.unix_time).toISOString()`
: `'${new Date(casual.unix_time).toISOString()}'`;
return mockValueGenerator.date();
}
return opts.dynamicValues ? `casual.word` : `'${casual.word}'`;
return mockValueGenerator.word();
}

// If there is a mapping to a `casual` type, then use it and make sure
Expand Down Expand Up @@ -332,6 +334,7 @@ export interface TypescriptMocksPluginConfig {
transformUnderscore?: boolean;
listElementCount?: number;
dynamicValues?: boolean;
generateLibrary?: 'casual' | 'faker';
}

interface TypeItem {
Expand Down Expand Up @@ -372,6 +375,7 @@ export const plugin: PluginFunction<TypescriptMocksPluginConfig> = (schema, docu
const transformUnderscore = config.transformUnderscore ?? true;
const listElementCount = config.listElementCount > 0 ? config.listElementCount : 1;
const dynamicValues = !!config.dynamicValues;
const generateLibrary = config.generateLibrary || 'casual';
// List of types that are enums
const types: TypeItem[] = [];
const visitor: VisitorType = {
Expand Down Expand Up @@ -416,6 +420,7 @@ export const plugin: PluginFunction<TypescriptMocksPluginConfig> = (schema, docu
transformUnderscore,
listElementCount,
dynamicValues,
generateLibrary,
});

return ` ${fieldName}: overrides && overrides.hasOwnProperty('${fieldName}') ? overrides.${fieldName}! : ${value},`;
Expand Down Expand Up @@ -446,6 +451,7 @@ export const plugin: PluginFunction<TypescriptMocksPluginConfig> = (schema, docu
transformUnderscore,
listElementCount,
dynamicValues,
generateLibrary,
});

return ` ${field.name.value}: overrides && overrides.hasOwnProperty('${field.name.value}') ? overrides.${field.name.value}! : ${value},`;
Expand Down Expand Up @@ -541,13 +547,14 @@ export const plugin: PluginFunction<TypescriptMocksPluginConfig> = (schema, docu
.filter((mockFn: () => string) => !!mockFn)
.map((mockFn: () => string) => mockFn())
.join('\n');
const functionTokens = setupFunctionTokens(generateLibrary);

let mockFile = '';
if (dynamicValues) mockFile += "import casual from 'casual';\n";
if (dynamicValues) mockFile += `${functionTokens.import}\n`;
mockFile += typesFileImport;
if (dynamicValues) mockFile += '\ncasual.seed(0);\n';
if (dynamicValues) mockFile += `\n${functionTokens.seed}\n`;
mockFile += mockFns;
if (dynamicValues) mockFile += '\n\nexport const seedMocks = (seed: number) => casual.seed(seed);';
if (dynamicValues) mockFile += `\n\n${functionTokens.seedFunction}`;
mockFile += '\n';
return mockFile;
};
104 changes: 104 additions & 0 deletions src/mockValueGenerator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import { faker } from '@faker-js/faker';
import casual from 'casual';

interface MockValueGenerator {
dynamicValues: boolean;
word: () => string;
uuid: () => string;
boolean: () => boolean | string;
integer: () => number | string;
float: () => number | string;
date: () => string;
seed: (seed: number) => void;
}

type MockValueGeneratorOptions = {
dynamicValues: boolean;
};

type FunctionTokens = Record<'import' | 'seed' | 'seedFunction', string>;

type SetupMockValueGeneratorOptions = {
generateLibrary: 'casual' | 'faker';
dynamicValues: boolean;
};

class CasualMockValueGenerator implements MockValueGenerator {
dynamicValues: boolean;

constructor(opts: MockValueGeneratorOptions) {
this.dynamicValues = opts.dynamicValues;
}

word = () => (this.dynamicValues ? `casual.word` : `'${casual.word}'`);
uuid = () => (this.dynamicValues ? `casual.uuid` : `'${casual.uuid}'`);
boolean = () => (this.dynamicValues ? `casual.boolean` : casual.boolean);
integer = () => (this.dynamicValues ? `casual.integer(0, 9999)` : `${casual.integer(0, 9999)}`);
float = () =>
this.dynamicValues
? `Math.round(casual.double(0, 10) * 100) / 100`
: `${Math.round(casual.double(0, 10) * 100) / 100}`;
date = () =>
this.dynamicValues
? `new Date(casual.unix_time).toISOString()`
: `'${new Date(casual.unix_time).toISOString()}'`;
seed = (seed: number) => casual.seed(seed);
}

const casualFunctionTokens: FunctionTokens = {
import: `import casual from 'casual';`,
seed: 'casual.seed(0);',
seedFunction: 'export const seedMocks = (seed: number) => casual.seed(seed);',
};

class FakerMockValueGenerator implements MockValueGenerator {
dynamicValues: boolean;

constructor(opts: MockValueGeneratorOptions) {
this.dynamicValues = opts.dynamicValues;
}

word = () => (this.dynamicValues ? `faker.lorem.word()` : `'${faker.lorem.word()}'`);
uuid = () => (this.dynamicValues ? `faker.datatype.uuid()` : `'${faker.datatype.uuid()}'`);
boolean = () => (this.dynamicValues ? `faker.datatype.boolean()` : faker.datatype.boolean());
integer = () =>
this.dynamicValues
? `faker.datatype.number({ min: 0, max: 9999 })`
: faker.datatype.number({ min: 0, max: 9999 });
float = () =>
this.dynamicValues
? `faker.datatype.float({ min: 0, max: 10, precision: 0.1 })`
: faker.datatype.float({ min: 0, max: 10, precision: 0.1 });
date = () =>
this.dynamicValues
? `faker.date.past().toISOString(1, new Date(2022, 0))`
: `'${faker.date.past(1, new Date(2022, 0)).toISOString()}'`;
seed = (seed: number) => faker.seed(seed);
}
Copy link
Contributor Author

Choose a reason for hiding this comment

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

The compatibility of the execution results of each function is checked here:
#92 (comment)


const fakerFunctionTokens: FunctionTokens = {
import: `import { faker } from '@faker-js/faker';`,
seed: 'faker.seed(0);',
seedFunction: 'export const seedMocks = (seed: number) => faker.seed(seed);',
};

export const setupMockValueGenerator = ({
generateLibrary,
dynamicValues,
}: SetupMockValueGeneratorOptions): MockValueGenerator => {
switch (generateLibrary) {
case 'casual':
return new CasualMockValueGenerator({ dynamicValues });
case 'faker':
return new FakerMockValueGenerator({ dynamicValues });
}
};

export const setupFunctionTokens = (generateLibrary: 'casual' | 'faker'): FunctionTokens => {
switch (generateLibrary) {
case 'casual':
return casualFunctionTokens;
case 'faker':
return fakerFunctionTokens;
}
};
Loading