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

orval/core - generating factory method for schema interfaces #1334

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions packages/core/src/generators/component-definition.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ export const generateComponentDefinition = (
if (modelName !== type) {
acc.push({
name: modelName,
factoryMethod: '',
model,
imports,
});
Expand Down
14 changes: 12 additions & 2 deletions packages/core/src/generators/imports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
GeneratorMutator,
GeneratorVerbOptions,
GetterPropType,
OutputModelFactoryMethodsMode,
} from '../types';
import { camel, upath } from '../utils';

Expand All @@ -14,12 +15,16 @@ export const generateImports = ({
isRootKey,
specsName,
specKey: currentSpecKey,
factoryMethodOutput,
factoryMethodPrefix
}: {
imports: GeneratorImport[];
target: string;
isRootKey: boolean;
specsName: Record<string, string>;
specKey: string;
factoryMethodOutput?: (typeof OutputModelFactoryMethodsMode)[keyof typeof OutputModelFactoryMethodsMode];
factoryMethodPrefix?: string;
}) => {
if (!imports.length) {
return '';
Expand Down Expand Up @@ -47,9 +52,14 @@ export const generateImports = ({
} } from \'./${upath.join(path, camel(name))}\';`;
}

return `import ${!values ? 'type ' : ''}{ ${name}${
let mainImport = `import ${!values ? 'type ' : ''}{ ${name}${
alias ? ` as ${alias}` : ''
} } from \'./${camel(name)}\';`;
}${factoryMethodOutput == OutputModelFactoryMethodsMode.SINGLE ? `${factoryMethodPrefix}${name}` : ''} } from \'./${camel(name)}\';`;
if (factoryMethodOutput == OutputModelFactoryMethodsMode.SPLIT) {
let factoryMethodImport = `import { ${factoryMethodPrefix}${name} } from \'./${camel(name)}.factory\';`;
mainImport += '\n' + factoryMethodImport;
}
return mainImport;
})
.join('\n');
};
Expand Down
14 changes: 12 additions & 2 deletions packages/core/src/generators/interface.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { SchemaObject } from 'openapi3-ts/oas30';
import { getScalar } from '../getters';
import { ContextSpecs } from '../types';
import { ContextSpecs, OutputModelFactoryMethodsMode } from '../types';
import { jsDoc } from '../utils';

/**
Expand Down Expand Up @@ -53,17 +53,27 @@ export const generateInterface = ({
} else {
model += `export type ${name} = ${scalar.value};\n`;
}

// Filter out imports that refer to the type defined in current file (OpenAPI recursive schema definitions)
const externalModulesImportsOnly = scalar.imports.filter(
(importName) => importName.name !== name,
);

let factoryMethod: string = '';
if (context?.output.modelFactoryMethods) {
let factoryMethodPrefix = context?.output.override?.modelFactoryMethods?.factoryMethodPrefix!;
factoryMethod = `export function ${factoryMethodPrefix}${name}(): ${name} ${scalar.factoryMethodValue}\n`;
if (context?.output.override?.modelFactoryMethods?.outputMode == OutputModelFactoryMethodsMode.SINGLE) {
model += factoryMethod;
factoryMethod = '';
}
}

return [
...scalar.schemas,
{
name,
model,
factoryMethod,
imports: externalModulesImportsOnly,
},
];
Expand Down
2 changes: 2 additions & 0 deletions packages/core/src/generators/parameter-definition.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ export const generateParameterDefinition = (
if (!schema.schema || imports.length) {
acc.push({
name: modelName,
factoryMethod: '',
imports: imports.length
? [
{
Expand Down Expand Up @@ -63,6 +64,7 @@ export const generateParameterDefinition = (
if (modelName !== resolvedObject.value) {
acc.push({
name: modelName,
factoryMethod: '',
model,
imports: resolvedObject.imports,
});
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/generators/schema-definition.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ export const generateSchemasDefinition = (

acc.push(...resolvedValue.schemas, {
name: schemaName,
factoryMethod: '',
model: output,
imports,
});
Expand Down
2 changes: 2 additions & 0 deletions packages/core/src/getters/array.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ export const getArray = ({
}
return {
type: 'array',
factoryMethodValue: `[]`,
isEnum: false,
isRef: false,
value: `[${resolvedObjects.map((o) => o.value).join(', ')}]`,
Expand Down Expand Up @@ -71,6 +72,7 @@ export const getArray = ({
? `(${resolvedObject.value})[]`
: `${resolvedObject.value}[]`
}`,
factoryMethodValue: `[]`,
imports: resolvedObject.imports,
schemas: resolvedObject.schemas,
isEnum: false,
Expand Down
3 changes: 3 additions & 0 deletions packages/core/src/getters/combine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,7 @@ export const combineSchemas = ({

return {
value: `typeof ${pascal(name)}[keyof typeof ${pascal(name)}] ${nullable}`,
factoryMethodValue: `{}`,
imports: [
{
name: pascal(name),
Expand All @@ -192,6 +193,7 @@ export const combineSchemas = ({
})),
],
model: newEnum,
factoryMethod: '',
name: name,
},
],
Expand Down Expand Up @@ -219,6 +221,7 @@ export const combineSchemas = ({

return {
value: value + nullable,
factoryMethodValue: `{}`,
imports: resolvedValue
? [...resolvedData.imports, ...resolvedValue.imports]
: resolvedData.imports,
Expand Down
11 changes: 11 additions & 0 deletions packages/core/src/getters/object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ export const getObject = ({
const { name, specKey } = getRefInfo(item.$ref, context);
return {
value: name + nullable,
factoryMethodValue: `''`,
imports: [{ name, specKey }],
schemas: [],
isEnum: false,
Expand Down Expand Up @@ -115,12 +116,16 @@ export const getObject = ({
const isReadOnly = item.readOnly || (schema as SchemaObject).readOnly;
if (!index) {
acc.value += '{';
acc.factoryMethodValue += '{\n return {';
}

const doc = jsDoc(schema as SchemaObject, true);

acc.hasReadonlyProps ||= isReadOnly || false;
acc.imports.push(...resolvedValue.imports);
if (!isReadOnly || isRequired) {
acc.factoryMethodValue += `\n ${getKey(key)}: ${resolvedValue.factoryMethodValue},`;
}
acc.value += `\n ${doc ? `${doc} ` : ''}${
isReadOnly && !context.output.override.suppressReadonlyModifier
? 'readonly '
Expand All @@ -142,6 +147,7 @@ export const getObject = ({
}
} else {
acc.value += '\n}';
acc.factoryMethodValue += '\n };\n}';
}

acc.value += nullable;
Expand All @@ -153,6 +159,7 @@ export const getObject = ({
imports: [],
schemas: [],
value: '',
factoryMethodValue: '',
isEnum: false,
type: 'object' as SchemaType,
isRef: false,
Expand All @@ -168,6 +175,7 @@ export const getObject = ({
if (isBoolean(item.additionalProperties)) {
return {
value: `{ [key: string]: unknown }` + nullable,
factoryMethodValue: `{}`,
imports: [],
schemas: [],
isEnum: false,
Expand All @@ -183,6 +191,7 @@ export const getObject = ({
});
return {
value: `{[key: string]: ${resolvedValue.value}}` + nullable,
factoryMethodValue: `{}`,
imports: resolvedValue.imports ?? [],
schemas: resolvedValue.schemas ?? [],
isEnum: false,
Expand All @@ -196,6 +205,7 @@ export const getObject = ({
if (itemWithConst.const) {
return {
value: `'${itemWithConst.const}'` + nullable,
factoryMethodValue: `null`,
imports: [],
schemas: [],
isEnum: false,
Expand All @@ -209,6 +219,7 @@ export const getObject = ({
value:
(item.type === 'object' ? '{ [key: string]: unknown }' : 'unknown') +
nullable,
factoryMethodValue: `${item.type === 'object' ? '{}' : 'null'}`,
imports: [],
schemas: [],
isEnum: false,
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/getters/props.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ export const getProps = ({
required: true,
schema: {
name: parameterTypeName,
factoryMethod: '',
model: namedParametersTypeDefinition,
imports: params.flatMap((property) => property.imports),
},
Expand Down
3 changes: 2 additions & 1 deletion packages/core/src/getters/query-params.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ const getQueryParamsTypes = (
imports: [{ name: enumName }],
schemas: [
...resolvedValue.schemas,
{ name: enumName, model: enumValue, imports: resolvedValue.imports },
{ name: enumName, model: enumValue, factoryMethod: '', imports: resolvedValue.imports },
],
originalSchema: resolvedValue.originalSchema,
};
Expand Down Expand Up @@ -125,6 +125,7 @@ export const getQueryParams = ({

const schema = {
name,
factoryMethod: '',
model: `export type ${name} = {\n${type}\n};\n`,
imports,
};
Expand Down
3 changes: 3 additions & 0 deletions packages/core/src/getters/res-req-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ export const getResReqTypes = (
return [
{
value: name,
factoryMethodValue: name,
imports: [{ name, specKey, schemaName }],
schemas: [],
type: 'unknown',
Expand Down Expand Up @@ -129,6 +130,7 @@ export const getResReqTypes = (
{
value: name,
imports: [{ name, specKey, schemaName }, ...additionalImports],
factoryMethodValue: name,
schemas: [],
type: 'unknown',
isEnum: false,
Expand Down Expand Up @@ -223,6 +225,7 @@ export const getResReqTypes = (
return [
{
value: defaultType,
factoryMethodValue: `''`,
imports: [],
schemas: [],
type: defaultType,
Expand Down
5 changes: 5 additions & 0 deletions packages/core/src/getters/scalar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ export const getScalar = ({

return {
value: value + nullable,
factoryMethodValue: `0`,
isEnum,
type: 'number',
schemas: [],
Expand All @@ -79,6 +80,7 @@ export const getScalar = ({

return {
value: value + nullable,
factoryMethodValue: `false`,
type: 'boolean',
isEnum: false,
schemas: [],
Expand Down Expand Up @@ -133,6 +135,7 @@ export const getScalar = ({

return {
value: value + nullable,
factoryMethodValue: `''`,
isEnum,
type: 'string',
imports: [],
Expand All @@ -147,6 +150,7 @@ export const getScalar = ({
case 'null':
return {
value: 'null',
factoryMethodValue: `null`,
isEnum: false,
type: 'null',
imports: [],
Expand All @@ -167,6 +171,7 @@ export const getScalar = ({

return {
value: value + nullable,
factoryMethodValue: enumItems[0],
isEnum: true,
type: 'string',
imports: [],
Expand Down
8 changes: 8 additions & 0 deletions packages/core/src/resolvers/object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,13 @@ const resolveObjectOriginal = ({
) {
return {
value: propName,
factoryMethodValue: `{}`,
imports: [{ name: propName }],
schemas: [
...resolvedValue.schemas,
{
name: propName,
factoryMethod: `export function ${context.output.override.modelFactoryMethods?.factoryMethodPrefix}${propName}(): ${propName}${resolvedValue.factoryMethodValue}`,
model: `${doc}export type ${propName} = ${resolvedValue.value};\n`,
imports: resolvedValue.imports,
},
Expand All @@ -54,13 +56,19 @@ const resolveObjectOriginal = ({
resolvedValue.originalSchema?.['x-enumNames'],
context.output.override.useNativeEnums,
);
const factoryMethodValue = context?.output.override?.useTypeOverInterfaces
? `${propName}[${resolvedValue.value.split(' | ')[0]}]`
: `${resolvedValue.value.split(' | ')[0]}`;


return {
value: propName,
factoryMethodValue,
imports: [{ name: propName }],
schemas: [
...resolvedValue.schemas,
{
factoryMethod: '',
name: propName,
model: doc + enumValue,
imports: resolvedValue.imports,
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/resolvers/value.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ export const resolveValue = ({

return {
value: resolvedImport.name,
factoryMethodValue: `${context.output.override.modelFactoryMethods?.factoryMethodPrefix}${resolvedImport.name}()`,
imports: [
{
name: resolvedImport.name,
Expand Down
Loading
Loading