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
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
2 changes: 1 addition & 1 deletion .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ jobs:
- name: Get yarn cache directory path
id: yarn-cache-dir-path
run: echo "::set-output name=dir::$(yarn cache dir)"
- uses: actions/cache@v2
- uses: actions/cache@v4
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ jobs:
- name: Get yarn cache directory path
id: yarn-cache-dir-path
run: echo "::set-output name=dir::$(yarn cache dir)"
- uses: actions/cache@v2
- uses: actions/cache@v4
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ jobs:
- name: Get yarn cache directory path
id: yarn-cache-dir-path
run: echo "::set-output name=dir::$(yarn cache dir)"
- uses: actions/cache@v2
- uses: actions/cache@v4
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ jobs:
- name: Get yarn cache directory path
id: yarn-cache-dir-path
run: echo "::set-output name=dir::$(yarn cache dir)"
- uses: actions/cache@v2
- uses: actions/cache@v4
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
Expand Down
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
Loading
Loading