Skip to content

feature(scalars): support distinction between input and output generator configs #182

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 9 commits into from
Apr 3, 2025
20 changes: 19 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ keep all GraphQL names as-is. Available case functions in `change-case-all` are
`localeLowerCase`, `lowerCaseFirst`, `spongeCase`, `titleCase`, `upperCase`, `localeUpperCase` and `upperCaseFirst`
[See more](https://github.com/btxtiger/change-case-all)

### scalars (`{ [Scalar: string]: GeneratorOptions }`, defaultValue: `undefined`)
### scalars (`{ [Scalar: string]: GeneratorOptions | InputOutputGeneratorOptions }`, defaultValue: `undefined`)

Allows you to define mappings for your custom scalars. Allows you to map any GraphQL Scalar to a
[casual](https://github.com/boo1ean/casual#embedded-generators) embedded generator (string or
Expand Down Expand Up @@ -371,6 +371,24 @@ fieldName: # gets translated to casual.integer.toFixed(3)
arguments: 3
```

### `InputOutputGeneratorOptions` type

This type is used in the `scalars` option. It allows you to specify different `GeneratorOptions` for `input` and `output` types for
your scalars, in the same way the [typescript-operations](https://the-guild.dev/graphql/codegen/plugins/typescript/typescript-operations#scalars) plugin does.

So, using the first example of the previous section, you can specify a `string` for your input and a `Date` for your `output`:

```yaml
plugins:
- typescript-mock-data:
scalars:
Date:
input: date.weekday # Date fields in input objects will be mocked as strings
output:
generator: date.past # Date fields in other GraphQL types will be mocked as JS Dates
arguments: 10
```

## Examples of usage

**codegen.yml**
Expand Down
68 changes: 55 additions & 13 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ type NamingConvention = 'change-case-all#pascalCase' | 'keep' | string;
type Options<T = TypeNode> = {
typeName: string;
fieldName: string;
generatorMode: 'input' | 'output';
types: TypeItem[];
typeNamesConvention: NamingConvention;
enumValuesConvention: NamingConvention;
Expand Down Expand Up @@ -90,14 +91,26 @@ const hashedString = (value: string) => {
return hash;
};

const getGeneratorDefinition = (value: GeneratorDefinition | GeneratorName): GeneratorDefinition => {
if (typeof value === 'string') {
const getGeneratorDefinition = (
opts: GeneratorOptions | InputOutputGeneratorOptions,
generatorMode: Options['generatorMode'],
): GeneratorDefinition => {
if (isAnInputOutputGeneratorOptions(opts)) {
return buildGeneratorDefinition(opts[generatorMode]);
}

return buildGeneratorDefinition(opts);
};

const buildGeneratorDefinition = (opts: GeneratorOptions) => {
if (typeof opts === 'string') {
return {
generator: value,
generator: opts,
arguments: [],
};
}
return value;

return opts;
};

const getCasualCustomValue = (
Expand Down Expand Up @@ -246,12 +259,18 @@ const handleValueGeneration = (
if (opts.fieldGeneration) {
// Check for a specific generation for the type & field
if (opts.typeName in opts.fieldGeneration && opts.fieldName in opts.fieldGeneration[opts.typeName]) {
const generatorDefinition = getGeneratorDefinition(opts.fieldGeneration[opts.typeName][opts.fieldName]);
const generatorDefinition = getGeneratorDefinition(
opts.fieldGeneration[opts.typeName][opts.fieldName],
opts.generatorMode,
);
return getCustomValue(generatorDefinition, opts);
}
// Check for a general field generation definition
if ('_all' in opts.fieldGeneration && opts.fieldName in opts.fieldGeneration['_all']) {
const generatorDefinition = getGeneratorDefinition(opts.fieldGeneration['_all'][opts.fieldName]);
const generatorDefinition = getGeneratorDefinition(
opts.fieldGeneration['_all'][opts.fieldName],
opts.generatorMode,
);
return getCustomValue(generatorDefinition, opts);
}
}
Expand Down Expand Up @@ -290,25 +309,36 @@ const getNamedType = (opts: Options<NamedTypeNode | ObjectTypeDefinitionNode>):
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': {
const customScalar = opts.customScalars ? getGeneratorDefinition(opts.customScalars['String']) : null;
const customScalar = opts.customScalars
? getGeneratorDefinition(opts.customScalars['String'], opts.generatorMode)
: null;
return handleValueGeneration(opts, customScalar, mockValueGenerator.word);
}
case 'Float': {
const customScalar = opts.customScalars ? getGeneratorDefinition(opts.customScalars['Float']) : null;
const customScalar = opts.customScalars
? getGeneratorDefinition(opts.customScalars['Float'], opts.generatorMode)
: null;
return handleValueGeneration(opts, customScalar, mockValueGenerator.float);
}
case 'ID': {
const customScalar = opts.customScalars ? getGeneratorDefinition(opts.customScalars['ID']) : null;
const customScalar = opts.customScalars
? getGeneratorDefinition(opts.customScalars['ID'], opts.generatorMode)
: null;
return handleValueGeneration(opts, customScalar, mockValueGenerator.uuid);
}
case 'Boolean': {
const customScalar = opts.customScalars ? getGeneratorDefinition(opts.customScalars['Boolean']) : null;
const customScalar = opts.customScalars
? getGeneratorDefinition(opts.customScalars['Boolean'], opts.generatorMode)
: null;
return handleValueGeneration(opts, customScalar, mockValueGenerator.boolean);
}
case 'Int': {
const customScalar = opts.customScalars ? getGeneratorDefinition(opts.customScalars['Int']) : null;
const customScalar = opts.customScalars
? getGeneratorDefinition(opts.customScalars['Int'], opts.generatorMode)
: null;
return handleValueGeneration(opts, customScalar, mockValueGenerator.integer);
}
default: {
Expand Down Expand Up @@ -345,7 +375,7 @@ const getNamedType = (opts: Options<NamedTypeNode | ObjectTypeDefinitionNode>):
});
case 'scalar': {
const customScalar = opts.customScalars
? getGeneratorDefinition(opts.customScalars[foundType.name])
? getGeneratorDefinition(opts.customScalars[foundType.name], opts.generatorMode)
: null;

// it's a scalar, let's use a string as a value if there is no custom
Expand Down Expand Up @@ -559,9 +589,18 @@ type GeneratorDefinition = {
};
};
type GeneratorOptions = GeneratorName | GeneratorDefinition;
type InputOutputGeneratorOptions = {
input: GeneratorOptions;
output: GeneratorOptions;
};

const isAnInputOutputGeneratorOptions = (
opts: GeneratorOptions | InputOutputGeneratorOptions,
): opts is InputOutputGeneratorOptions =>
opts !== undefined && typeof opts !== 'string' && 'input' in opts && 'output' in opts;

type ScalarMap = {
[name: string]: GeneratorOptions;
[name: string]: GeneratorOptions | InputOutputGeneratorOptions;
};

type TypeFieldMap = {
Expand Down Expand Up @@ -728,6 +767,7 @@ export const plugin: PluginFunction<TypescriptMocksPluginConfig> = (schema, docu
const value = generateMockValue({
typeName,
fieldName,
generatorMode: 'output',
currentType: node.type,
...sharedGenerateMockOpts,
});
Expand All @@ -753,6 +793,7 @@ export const plugin: PluginFunction<TypescriptMocksPluginConfig> = (schema, docu
typeName: fieldName,
fieldName: field.name.value,
currentType: field.type,
generatorMode: 'input',
...sharedGenerateMockOpts,
});

Expand All @@ -764,6 +805,7 @@ export const plugin: PluginFunction<TypescriptMocksPluginConfig> = (schema, docu
typeName: fieldName,
fieldName: field.name.value,
currentType: field.type,
generatorMode: 'input',
...sharedGenerateMockOpts,
});

Expand Down
158 changes: 150 additions & 8 deletions tests/scalars/__snapshots__/spec.ts.snap
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`should generate custom scalars for native and custom types using casual 1`] = `
exports[`Custom scalar generation using casual should generate custom scalars for native and custom types 1`] = `
"
export const anA = (overrides?: Partial<A>): A => {
return {
Expand All @@ -18,31 +18,75 @@ export const aB = (overrides?: Partial<B>): B => {
bool: overrides && overrides.hasOwnProperty('bool') ? overrides.bool! : false,
};
};

export const aC = (overrides?: Partial<C>): C => {
return {
anyObject: overrides && overrides.hasOwnProperty('anyObject') ? overrides.anyObject! : 'Gianni_Kutch@hotmail.com',
};
};
"
`;

exports[`Custom scalar generation using casual should generate dynamic custom scalars for native and custom types 1`] = `
"import casual from 'casual';

casual.seed(0);

export const anA = (overrides?: Partial<A>): A => {
return {
id: overrides && overrides.hasOwnProperty('id') ? overrides.id! : casual['integer'](...[1,100]),
str: overrides && overrides.hasOwnProperty('str') ? overrides.str! : casual['string'],
obj: overrides && overrides.hasOwnProperty('obj') ? overrides.obj! : aB(),
anyObject: overrides && overrides.hasOwnProperty('anyObject') ? overrides.anyObject! : casual['email'],
};
};

export const aB = (overrides?: Partial<B>): B => {
return {
int: overrides && overrides.hasOwnProperty('int') ? overrides.int! : casual['integer'](...[-100,0]),
flt: overrides && overrides.hasOwnProperty('flt') ? overrides.flt! : casual['double'](...[-100,0]),
bool: overrides && overrides.hasOwnProperty('bool') ? overrides.bool! : false,
};
};

export const aC = (overrides?: Partial<C>): C => {
return {
anyObject: overrides && overrides.hasOwnProperty('anyObject') ? overrides.anyObject! : casual['email'],
};
};

export const seedMocks = (seed: number) => casual.seed(seed);
"
`;

exports[`should generate custom scalars for native and custom types using faker 1`] = `
exports[`Custom scalar generation using casual with different input/output configurations should generate distinct custom scalars for native and custom input/output types 1`] = `
"
export const anA = (overrides?: Partial<A>): A => {
return {
id: overrides && overrides.hasOwnProperty('id') ? overrides.id! : 83,
str: overrides && overrides.hasOwnProperty('str') ? overrides.str! : 'Depereo nulla calco blanditiis cornu defetiscor.',
id: overrides && overrides.hasOwnProperty('id') ? overrides.id! : 82,
str: overrides && overrides.hasOwnProperty('str') ? overrides.str! : 'ea corrupti qui incidunt eius consequatur blanditiis',
obj: overrides && overrides.hasOwnProperty('obj') ? overrides.obj! : aB(),
anyObject: overrides && overrides.hasOwnProperty('anyObject') ? overrides.anyObject! : 'Orlando_Cremin@gmail.com',
anyObject: overrides && overrides.hasOwnProperty('anyObject') ? overrides.anyObject! : 'Kelly_Cremin@Turcotte.biz',
};
};

export const aB = (overrides?: Partial<B>): B => {
return {
int: overrides && overrides.hasOwnProperty('int') ? overrides.int! : -93,
flt: overrides && overrides.hasOwnProperty('flt') ? overrides.flt! : -24.51,
flt: overrides && overrides.hasOwnProperty('flt') ? overrides.flt! : -24.509902694262564,
bool: overrides && overrides.hasOwnProperty('bool') ? overrides.bool! : false,
};
};

export const aC = (overrides?: Partial<C>): C => {
return {
anyObject: overrides && overrides.hasOwnProperty('anyObject') ? overrides.anyObject! : 'itaque distinctio iure molestias voluptas reprehenderit quos',
};
};
"
`;

exports[`should generate dynamic custom scalars for native and custom types using casual 1`] = `
exports[`Custom scalar generation using casual with different input/output configurations should generate distinct dynamic custom scalars for native and custom types 1`] = `
"import casual from 'casual';

casual.seed(0);
Expand All @@ -64,11 +108,103 @@ export const aB = (overrides?: Partial<B>): B => {
};
};

export const aC = (overrides?: Partial<C>): C => {
return {
anyObject: overrides && overrides.hasOwnProperty('anyObject') ? overrides.anyObject! : casual['string'],
};
};

export const seedMocks = (seed: number) => casual.seed(seed);
"
`;

exports[`should generate dynamic custom scalars for native and custom types using faker 1`] = `
exports[`custom scalar generation using faker should generate custom scalars for native and custom types 1`] = `
"
export const anA = (overrides?: Partial<A>): A => {
return {
id: overrides && overrides.hasOwnProperty('id') ? overrides.id! : 83,
str: overrides && overrides.hasOwnProperty('str') ? overrides.str! : 'Depereo nulla calco blanditiis cornu defetiscor.',
obj: overrides && overrides.hasOwnProperty('obj') ? overrides.obj! : aB(),
anyObject: overrides && overrides.hasOwnProperty('anyObject') ? overrides.anyObject! : 'Orlando_Cremin@gmail.com',
};
};

export const aB = (overrides?: Partial<B>): B => {
return {
int: overrides && overrides.hasOwnProperty('int') ? overrides.int! : -93,
flt: overrides && overrides.hasOwnProperty('flt') ? overrides.flt! : -24.51,
bool: overrides && overrides.hasOwnProperty('bool') ? overrides.bool! : false,
};
};

export const aC = (overrides?: Partial<C>): C => {
return {
anyObject: overrides && overrides.hasOwnProperty('anyObject') ? overrides.anyObject! : 'Maia49@hotmail.com',
};
};
"
`;

exports[`custom scalar generation using faker should generate dynamic custom scalars for native and custom types 1`] = `
"import { fakerEN as faker } from '@faker-js/faker';

faker.seed(0);

export const anA = (overrides?: Partial<A>): A => {
return {
id: overrides && overrides.hasOwnProperty('id') ? overrides.id! : faker['number']['int'](...[{\\"min\\":1,\\"max\\":100}]),
str: overrides && overrides.hasOwnProperty('str') ? overrides.str! : faker['lorem']['sentence'](),
obj: overrides && overrides.hasOwnProperty('obj') ? overrides.obj! : aB(),
anyObject: overrides && overrides.hasOwnProperty('anyObject') ? overrides.anyObject! : faker['internet']['email'](),
};
};

export const aB = (overrides?: Partial<B>): B => {
return {
int: overrides && overrides.hasOwnProperty('int') ? overrides.int! : faker['number']['int'](...[{\\"min\\":-100,\\"max\\":0}]),
flt: overrides && overrides.hasOwnProperty('flt') ? overrides.flt! : faker['number']['float'](...[{\\"min\\":-100,\\"max\\":0}]),
bool: overrides && overrides.hasOwnProperty('bool') ? overrides.bool! : false,
};
};

export const aC = (overrides?: Partial<C>): C => {
return {
anyObject: overrides && overrides.hasOwnProperty('anyObject') ? overrides.anyObject! : faker['internet']['email'](),
};
};

export const seedMocks = (seed: number) => faker.seed(seed);
"
`;

exports[`custom scalar generation using faker with different input/output configurations should generate distinct custom scalars for native and custom input/output types 1`] = `
"
export const anA = (overrides?: Partial<A>): A => {
return {
id: overrides && overrides.hasOwnProperty('id') ? overrides.id! : 83,
str: overrides && overrides.hasOwnProperty('str') ? overrides.str! : 'Depereo nulla calco blanditiis cornu defetiscor.',
obj: overrides && overrides.hasOwnProperty('obj') ? overrides.obj! : aB(),
anyObject: overrides && overrides.hasOwnProperty('anyObject') ? overrides.anyObject! : 'Orlando_Cremin@gmail.com',
};
};

export const aB = (overrides?: Partial<B>): B => {
return {
int: overrides && overrides.hasOwnProperty('int') ? overrides.int! : -93,
flt: overrides && overrides.hasOwnProperty('flt') ? overrides.flt! : -24.51,
bool: overrides && overrides.hasOwnProperty('bool') ? overrides.bool! : false,
};
};

export const aC = (overrides?: Partial<C>): C => {
return {
anyObject: overrides && overrides.hasOwnProperty('anyObject') ? overrides.anyObject! : 'vilicus',
};
};
"
`;

exports[`custom scalar generation using faker with different input/output configurations should generate distinct dynamic custom scalars for native and custom types 1`] = `
"import { fakerEN as faker } from '@faker-js/faker';

faker.seed(0);
Expand All @@ -90,6 +226,12 @@ export const aB = (overrides?: Partial<B>): B => {
};
};

export const aC = (overrides?: Partial<C>): C => {
return {
anyObject: overrides && overrides.hasOwnProperty('anyObject') ? overrides.anyObject! : faker['lorem']['word'](),
};
};

export const seedMocks = (seed: number) => faker.seed(seed);
"
`;
Loading
Loading