Skip to content

Bugfix/Feature: pascalCase; Bugfix: recursive nesting #9

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 4 commits into from
Apr 5, 2020
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
42 changes: 35 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ Defines the file path containing all GraphQL types. This file can also be genera

Adds `__typename` property to mock data

### enumValues (`string`, defaultValue: `pascal-case#pascalCase`)

Change the case of the enums. Accept `upper-case#upperCase` or `pascal-case#pascalCase`

## Example of usage

**codegen.yml**
Expand All @@ -33,6 +37,7 @@ generates:
plugins:
- 'graphql-codegen-typescript-mock-data':
typesFile: '../generated-types.ts'
enumValues: upper-case#upperCase
```

## Example or generated code
Expand All @@ -49,30 +54,53 @@ type User {
id: ID!
login: String!
avatar: Avatar
status: Status!
}

type Query {
user: User!
}

input UpdateUserInput {
id: ID!
login: String
avatar: Avatar
}

enum Status {
ONLINE
OFFLINE
}

type Mutation {
updateUser(user: UpdateUserInput): User
}
```

The code generated will look like:

```typescript
export const anAvatar = (overrides?: Partial<Avatar>): Avatar => {
return {
id: '1550ff93-cd31-49b4-bc38-ef1cb68bdc38',
url: 'aliquid',
...overrides,
id: overrides && overrides.hasOwnProperty('id') ? overrides.id! : '0550ff93-dd31-49b4-8c38-ff1cb68bdc38',
url: overrides && overrides.hasOwnProperty('url') ? overrides.url! : 'aliquid',
};
};

export const aUpdateUserInput = (overrides?: Partial<UpdateUserInput>): 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! : anAvatar(),
};
};

export const aUser = (overrides?: Partial<User>): User => {
return {
id: 'b5756f00-51a6-422a-9a7d-c13ee6a63750',
login: 'libero',
avatar: anAvatar(),
...overrides,
id: overrides && overrides.hasOwnProperty('id') ? overrides.id! : 'a5756f00-41a6-422a-8a7d-d13ee6a63750',
login: overrides && overrides.hasOwnProperty('login') ? overrides.login! : 'libero',
avatar: overrides && overrides.hasOwnProperty('avatar') ? overrides.avatar! : anAvatar(),
status: overrides && overrides.hasOwnProperty('status') ? overrides.status! : Status.Online,
};
};
```
Expand Down
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,11 @@
"dependencies": {
"@graphql-codegen/plugin-helpers": "^1.13.1",
"casual": "^1.6.2",
"pascal-case": "^3.1.1"
"pascal-case": "^3.1.1",
"upper-case": "^2.0.1"
},
"peerDependencies": {
"graphql": "^14.0.0"
"graphql": "^14.6.0"
},
"devDependencies": {
"@auto-it/conventional-commits": "^9.25.0",
Expand Down
62 changes: 42 additions & 20 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,27 @@ import { printSchema, parse, visit, ASTKindToNode, NamedTypeNode, TypeNode, Visi
import casual from 'casual';
import { PluginFunction } from '@graphql-codegen/plugin-helpers';
import { pascalCase } from 'pascal-case';
import { upperCase } from 'upper-case';

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

const toMockName = (name: string) => {
const isVowel = name.match(/^[AEIO]/);
return isVowel ? `an${name}` : `a${name}`;
};

const updateTextCase = (str: string, enumValues: EnumValuesTypes) => {
const convert = (value: string) =>
enumValues === 'upper-case#upperCase' ? upperCase(value || '') : pascalCase(value || '');

export function toPascalCase(str: string) {
if (str.charAt(0) === '_') {
return str.replace(
/^(_*)(.*)/,
(_match, underscorePrefix, typeName) => `${underscorePrefix}${pascalCase(typeName || '')}`,
(_match, underscorePrefix, typeName) => `${underscorePrefix}${convert(typeName)}`,
);
}

return pascalCase(str || '');
}

const toMockName = (name: string) => {
const isVowel = name.match(/^[AEIO]/);
return isVowel ? `an${name}` : `a${name}`;
return convert(str);
};

const hashedString = (value: string) => {
Expand All @@ -38,6 +44,7 @@ const getNamedType = (
typeName: string,
fieldName: string,
types: TypeItem[],
enumValues: EnumValuesTypes,
namedType?: NamedTypeNode,
): string | number | boolean => {
if (!namedType) {
Expand Down Expand Up @@ -66,11 +73,17 @@ const getNamedType = (
case 'enum': {
// It's an enum
const value = foundType.values ? foundType.values[0] : '';
return `${foundType.name}.${toPascalCase(value)}`;
return `${foundType.name}.${updateTextCase(value, enumValues)}`;
}
case 'union':
// Return the first union type node.
return getNamedType(typeName, fieldName, types, foundType.types && foundType.types[0]);
return getNamedType(
typeName,
fieldName,
types,
enumValues,
foundType.types && foundType.types[0],
);
default:
throw `foundType is unknown: ${foundType.name}: ${foundType.type}`;
}
Expand All @@ -84,15 +97,16 @@ const generateMockValue = (
typeName: string,
fieldName: string,
types: TypeItem[],
enumValues: EnumValuesTypes,
currentType: TypeNode,
): string | number | boolean => {
switch (currentType.kind) {
case 'NamedType':
return getNamedType(typeName, fieldName, types, currentType as NamedTypeNode);
return getNamedType(typeName, fieldName, types, enumValues, currentType as NamedTypeNode);
case 'NonNullType':
return generateMockValue(typeName, fieldName, types, currentType.type);
return generateMockValue(typeName, fieldName, types, enumValues, currentType.type);
case 'ListType': {
const value = generateMockValue(typeName, fieldName, types, currentType.type);
const value = generateMockValue(typeName, fieldName, types, enumValues, currentType.type);
return `[${value}]`;
}
}
Expand All @@ -104,21 +118,21 @@ const getMockString = (typeName: string, fields: string, addTypename = false) =>
export const ${toMockName(typeName)} = (overrides?: Partial<${typeName}>): ${typeName} => {
return {${typename}
${fields}
...overrides
};
};`;
};

export interface TypescriptMocksPluginConfig {
typesFile?: string;
enumValues?: EnumValuesTypes;
addTypename?: boolean;
}

interface TypeItem {
name: string;
type: string;
values?: string[];
types?: ReadonlyArray<NamedTypeNode>;
types?: readonly NamedTypeNode[];
}

type VisitorType = { [K in keyof ASTKindToNode]?: VisitFn<ASTKindToNode[keyof ASTKindToNode], ASTKindToNode[K]> };
Expand All @@ -129,6 +143,8 @@ type VisitorType = { [K in keyof ASTKindToNode]?: VisitFn<ASTKindToNode[keyof AS
export const plugin: PluginFunction<TypescriptMocksPluginConfig> = (schema, documents, config) => {
const printedSchema = printSchema(schema); // Returns a string representation of the schema
const astNode = parse(printedSchema); // Transforms the string into ASTNode

const enumValues = config.enumValues || 'pascal-case#pascalCase';
// List of types that are enums
const types: TypeItem[] = [];
const visitor: VisitorType = {
Expand Down Expand Up @@ -158,9 +174,9 @@ export const plugin: PluginFunction<TypescriptMocksPluginConfig> = (schema, docu
return {
name: fieldName,
mockFn: (typeName: string) => {
const value = generateMockValue(typeName, fieldName, types, node.type);
const value = generateMockValue(typeName, fieldName, types, enumValues, node.type);

return ` ${fieldName}: ${value},`;
return ` ${fieldName}: overrides && overrides.hasOwnProperty('${fieldName}') ? overrides.${fieldName}! : ${value},`;
},
};
},
Expand All @@ -173,9 +189,15 @@ export const plugin: PluginFunction<TypescriptMocksPluginConfig> = (schema, docu
const mockFields = node.fields
? node.fields
.map((field) => {
const value = generateMockValue(fieldName, field.name.value, types, field.type);

return ` ${field.name.value}: ${value},`;
const value = generateMockValue(
fieldName,
field.name.value,
types,
enumValues,
field.type,
);

return ` ${field.name.value}: overrides && overrides.hasOwnProperty('${field.name.value}') ? overrides.${field.name.value}! : ${value},`;
})
.join('\n')
: '';
Expand Down
Loading