Skip to content
Draft
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
48 changes: 13 additions & 35 deletions packages/core/src/getters/combine.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import uniq from 'lodash.uniq';
import { SchemaObject } from 'openapi3-ts/oas30';
import { resolveExampleRefs, resolveObject } from '../resolvers';
import {
Expand All @@ -7,10 +8,9 @@ import {
ScalarValue,
SchemaType,
} from '../types';
import { getNumberWord, pascal, isSchema } from '../utils';
import { getEnumImplementation, getEnumNames } from './enum';
import { getNumberWord, isSchema, pascal } from '../utils';
import { getCombineEnumValue, getEnumPropertyType } from './enum';
import { getScalar } from './scalar';
import uniq from 'lodash.uniq';

type CombinedData = {
imports: GeneratorImport[];
Expand Down Expand Up @@ -191,12 +191,18 @@ export const combineSchemas = ({
const isAllEnums = resolvedData.isEnum.every((v) => v);

if (isAllEnums && name && items.length > 1) {
const newEnum = `// eslint-disable-next-line @typescript-eslint/no-redeclare\nexport const ${pascal(
const newEnum = getCombineEnumValue(
resolvedData,
name,
)} = ${getCombineEnumValue(resolvedData)}`;
context.output.override.enumGenerationType,
);
const propertyType = getEnumPropertyType(
pascal(name),
context.output.override.enumGenerationType,
);

return {
value: `typeof ${pascal(name)}[keyof typeof ${pascal(name)}] ${nullable}`,
value: propertyType,
imports: [
{
name: pascal(name),
Expand All @@ -212,7 +218,7 @@ export const combineSchemas = ({
})),
],
model: newEnum,
name: name,
name: pascal(name),
},
],
isEnum: false,
Expand Down Expand Up @@ -262,31 +268,3 @@ export const combineSchemas = ({
examples: resolveExampleRefs(schema.examples, context),
};
};

const getCombineEnumValue = ({
values,
isRef,
originalSchema,
}: CombinedData) => {
if (values.length === 1) {
if (isRef[0]) {
return values[0];
}

return `{${getEnumImplementation(values[0])}} as const`;
}

const enums = values
.map((e, i) => {
if (isRef[i]) {
return `...${e},`;
}

const names = getEnumNames(originalSchema[i]);

return getEnumImplementation(e, names);
})
.join('');

return `{${enums}} as const`;
};
80 changes: 77 additions & 3 deletions packages/core/src/getters/enum.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ import { SchemaObject } from 'openapi3-ts/dist/model/openapi30';
import { EnumGeneration } from '../types';
import { isNumeric, sanitize } from '../utils';

export const getEnumNames = (schemaObject: SchemaObject | undefined) => {
export const getEnumNames = (
schemaObject: SchemaObject | undefined,
): string[] | undefined => {
return (
schemaObject?.['x-enumNames'] ||
schemaObject?.['x-enumnames'] ||
Expand All @@ -26,6 +28,78 @@ export const getEnum = (
throw new Error(`Invalid enumGenerationType: ${enumGenerationType}`);
};

const getEnumItems = (
value: string,
names: string[] | undefined,
enumGenerationType: EnumGeneration,
) => {
if (enumGenerationType === EnumGeneration.CONST)
return getConstEnumItems(value, names);
if (enumGenerationType === EnumGeneration.ENUM)
return getNativeEnumItems(value, names);
if (enumGenerationType === EnumGeneration.UNION) return value;
return '';
};

const getEnumDefinition = (
enumValue: string,
enumName: string,
enumGenerationType: EnumGeneration,
) => {
if (enumGenerationType === EnumGeneration.CONST)
return `// eslint-disable-next-line @typescript-eslint/no-redeclare\nexport const ${enumName} = {${enumValue}} as const`;
if (enumGenerationType === EnumGeneration.ENUM)
return `export enum ${enumName} {${enumValue}}`;
if (enumGenerationType === EnumGeneration.UNION)
return `export type ${enumName} = ${enumValue}`;
return '';
};

export const getEnumPropertyType = (
enumName: string,
enumGenerationType: EnumGeneration,
) => {
if (enumGenerationType === EnumGeneration.CONST)
return `typeof ${enumName}[keyof typeof ${enumName}]`;
if (enumGenerationType === EnumGeneration.ENUM) return enumName;
if (enumGenerationType === EnumGeneration.UNION) return enumName;
return '';
};

export const getCombineEnumValue = (
{
values,
isRef,
originalSchema,
}: {
values: string[];
isRef: boolean[];
originalSchema: (SchemaObject | undefined)[];
},
name: string,
enumGenerationType: EnumGeneration,
): string => {
if (values.length === 1) {
const names = getEnumNames(originalSchema[0]);
const items = getEnumItems(values[0], names, enumGenerationType);
return getEnumDefinition(items, name, enumGenerationType);
}

const enums = values
.map((e, i) => {
if (isRef[i]) {
return `...${e},`;
}

const names = getEnumNames(originalSchema[i]);

return getEnumItems(e, names, enumGenerationType);
})
.join('');

return getEnumDefinition(enums, name, enumGenerationType);
};

const getTypeConstEnum = (
value: string,
enumName: string,
Expand All @@ -40,7 +114,7 @@ const getTypeConstEnum = (

enumValue += ';\n';

const implementation = getEnumImplementation(value, names);
const implementation = getConstEnumItems(value, names);

enumValue += `\n\n`;

Expand All @@ -51,7 +125,7 @@ const getTypeConstEnum = (
return enumValue;
};

export const getEnumImplementation = (value: string, names?: string[]) => {
const getConstEnumItems = (value: string, names?: string[]) => {
// empty enum or null-only enum
if (value === '') return '';

Expand Down
21 changes: 1 addition & 20 deletions packages/mock/src/faker/getters/scalar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -337,26 +337,7 @@ const getEnum = (

let enumValue = `[${joindEnumValues}]`;
if (context.output.override.enumGenerationType === EnumGeneration.ENUM) {
if (item.isRef || existingReferencedProperties.length === 0) {
Copy link
Member

Choose a reason for hiding this comment

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

@AllieJonsson

so type annotations are no longer possible.
Is this a temporary fix? Or will it become permanent?

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 is temporary, I will mark this as a draft as there are more issues that needs to be fixed in #2065

enumValue += ` as ${item.name}${item.name.endsWith('[]') ? '' : '[]'}`;
imports.push({
name: item.name,
...(!isRootKey(context.specKey, context.target)
? { specKey: context.specKey }
: {}),
});
} else {
enumValue += ` as ${existingReferencedProperties[existingReferencedProperties.length - 1]}['${item.name}']`;
if (!item.path?.endsWith('[]')) enumValue += '[]';
imports.push({
name: existingReferencedProperties[
existingReferencedProperties.length - 1
],
...(!isRootKey(context.specKey, context.target)
? { specKey: context.specKey }
: {}),
});
}
enumValue += ' as any[]';
} else {
enumValue += ' as const';
}
Expand Down
39 changes: 39 additions & 0 deletions tests/configs/default.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -390,6 +390,45 @@ export default defineConfig({
target: '../specifications/enums.yaml',
},
},
constCombineEnums: {
output: {
target: '../generated/default/enums/combine/const/endpoints.ts',
schemas: '../generated/default/enums/combine/const/model',
mock: true,
override: {
enumGenerationType: 'const',
},
},
input: {
target: '../specifications/combine-enums.yaml',
},
},
nativeCombineEnums: {
output: {
target: '../generated/default/enums/combine/native/endpoints.ts',
schemas: '../generated/default/enums/combine/native/model',
mock: true,
override: {
enumGenerationType: 'enum',
},
},
input: {
target: '../specifications/combine-enums.yaml',
},
},
unionCombineEnums: {
output: {
target: '../generated/default/enums/combine/union/endpoints.ts',
schemas: '../generated/default/enums/combine/union/model',
mock: true,
override: {
enumGenerationType: 'union',
},
},
input: {
target: '../specifications/combine-enums.yaml',
},
},
formDataExplode: {
output: {
target: '../generated/default/form-data-explode/endpoints.ts',
Expand Down
23 changes: 23 additions & 0 deletions tests/specifications/combine-enums.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
openapi: 3.1.0
info:
title: Combine Enums
version: 1.0.0
paths:
/api:
get:
responses:
'200':
description: Example response
content:
application/json:
schema:
type: object
properties:
foo:
anyOf:
- type: string
enum:
- example-true
- type: string
enum:
- example-false