Skip to content

Commit

Permalink
Merge pull request #560 from acacode/next
Browse files Browse the repository at this point in the history
Release 13.0.1
  • Loading branch information
js2me authored Jul 25, 2023
2 parents 2d4c74e + 1366ece commit 5729dcf
Show file tree
Hide file tree
Showing 34 changed files with 581 additions and 131 deletions.
2 changes: 1 addition & 1 deletion .env.example
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
TEST_FILE_NAME=github-swagger.ts
TEST_SCHEMA_VERSION=v3
TEST_SCHEMA_VERSION=v3.0#v2.0|v3.0
TEST_WITH_DEBUG=true
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# next release

feat: `const` keyword OpenAPI 3.0 draft
fix: problem with using `anyOf`
feat: `--extract-responses` (nodejs: `extractResponses`) option to extract all schemas from `/components/responses`
fix: discriminator and mapping with invalid discriminator property name (#551)
fix: problem with incorrect resolving type name of discriminator mapping types data contracts

## 13.0.0

BREAKING_CHANGE: disable support NodeJS 14.x
Expand Down
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,8 @@ Options:
--debug additional information about processes inside this tool (default: false)
--another-array-type generate array types as Array<Type> (by default Type[]) (default: false)
--sort-types sort fields and types (default: false)
--sort-routes sort routes in alphabetical order (default: false)
--custom-config <string> custom config: primitiveTypeConstructs, hooks, ... (default: "")
--extract-enums extract all enums from inline interface\type content to typescript enum construction (default: false)
-h, --help display help for command
Expand Down Expand Up @@ -149,6 +151,8 @@ generateApi({
enumKeyPrefix: '',
enumKeySuffix: '',
addReadonly: false,
sortTypes: false,
sortRouters: false,
extractingOptions: {
requestBodySuffix: ["Payload", "Body", "Input"],
requestParamsSuffix: ["Params"],
Expand Down
6 changes: 6 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,12 @@ const program = cli({
default: codeGenBaseConfig.extractResponseError,
internal: { formatter: Boolean },
},
{
flags: '--extract-responses',
description: 'extract all responses described in /components/responses',
default: codeGenBaseConfig.extractResponses,
internal: { formatter: Boolean },
},
{
flags: '--modular',
description:
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
"test:--extract-response-error": "node tests/spec/extractResponseError/test.js",
"test:--enum-names-as-values": "node tests/spec/enumNamesAsValues/test.js",
"test:--default-response": "node tests/spec/defaultResponse/test.js",
"test:const-keyword": "node tests/spec/const-keyword/test.js",
"test:--js": "node tests/spec/js/test.js",
"test:jsSingleHttpClientModular": "node tests/spec/jsSingleHttpClientModular/test.js",
"test:--js--axios": "node tests/spec/jsAxios/test.js",
Expand Down
18 changes: 14 additions & 4 deletions src/code-gen-process.js
Original file line number Diff line number Diff line change
Expand Up @@ -116,9 +116,14 @@ class CodeGenProcess {
}),
);

const schemaComponents = this.schemaComponentsMap.filter('schemas');
/**
* @type {SchemaComponent[]}
*/
const componentsToParse = this.schemaComponentsMap.filter(
_.compact(['schemas', this.config.extractResponses && 'responses']),
);

const parsedSchemas = schemaComponents.map((schemaComponent) => {
const parsedSchemas = componentsToParse.map((schemaComponent) => {
const parsed = this.schemaParserFabric.parseSchema(
schemaComponent.rawTypeData,
schemaComponent.typeName,
Expand Down Expand Up @@ -234,8 +239,13 @@ class CodeGenProcess {
const components = this.schemaComponentsMap.getComponents();
let modelTypes = [];

const modelTypeComponents = _.compact([
'schemas',
this.config.extractResponses && 'responses',
]);

const getSchemaComponentsCount = () =>
components.filter((c) => c.componentName === 'schemas').length;
this.schemaComponentsMap.filter(...modelTypeComponents).length;

let schemaComponentsCount = getSchemaComponentsCount();
let processedCount = 0;
Expand All @@ -244,7 +254,7 @@ class CodeGenProcess {
modelTypes = [];
processedCount = 0;
for (const component of components) {
if (component.componentName === 'schemas') {
if (modelTypeComponents.includes(component.componentName)) {
const modelType = this.prepareModelType(component);
if (modelType) {
modelTypes.push(modelType);
Expand Down
6 changes: 5 additions & 1 deletion src/configuration.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ class CodeGenConfig {
extractRequestBody = false;
extractResponseBody = false;
extractResponseError = false;
extractResponses = false;
extractEnums = false;
fileNames = {
dataContracts: 'data-contracts',
Expand Down Expand Up @@ -240,7 +241,7 @@ class CodeGenConfig {
/**
* $A
*/
NullValue: (content) => content,
NullValue: (content) => `null`,
/**
* $A1 | $A2
*/
Expand Down Expand Up @@ -276,6 +277,9 @@ class CodeGenConfig {
*/
InterfaceDynamicField: (key, value) => `[key: ${key}]: ${value}`,

/**
* EnumName.EnumKey
*/
EnumUsageKey: (enumStruct, key) => `${enumStruct}.${key}`,
/**
* $A1 = $A2
Expand Down
10 changes: 6 additions & 4 deletions src/schema-components-map.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,12 +57,14 @@ class SchemaComponentsMap {
}

/**
* @param componentName {string}
* @params {...string[]} componentNames
* @returns {SchemaComponent[]}
*/
filter(componentName) {
return _.filter(this._data, (v) =>
_.startsWith(v.$ref, `#/components/${componentName}`),
filter(...componentNames) {
return _.filter(this._data, (it) =>
componentNames.some((componentName) =>
_.startsWith(it.$ref, `#/components/${componentName}`),
),
);
}

Expand Down
73 changes: 38 additions & 35 deletions src/schema-parser/base-schema-parsers/discriminator.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const { MonoSchemaParser } = require('../mono-schema-parser');

class DiscriminatorSchemaParser extends MonoSchemaParser {
parse() {
const ts = this.config.Ts;
const { discriminator, ...noDiscriminatorSchema } = this.schema;

if (!discriminator.mapping) {
Expand All @@ -27,7 +28,7 @@ class DiscriminatorSchemaParser extends MonoSchemaParser {
abstractSchemaStruct,
});

const schemaContent = this.config.Ts.IntersectionType(
const schemaContent = ts.IntersectionType(
[
abstractSchemaStruct?.content,
discriminatorSchemaStruct?.content,
Expand All @@ -40,7 +41,7 @@ class DiscriminatorSchemaParser extends MonoSchemaParser {
$parsedSchema: true,
schemaType: SCHEMA_TYPES.COMPLEX,
type: SCHEMA_TYPES.PRIMITIVE,
typeIdentifier: this.config.Ts.Keyword.Type,
typeIdentifier: ts.Keyword.Type,
name: this.typeName,
description: this.schemaFormatters.formatDescription(
this.schema.description,
Expand All @@ -50,6 +51,8 @@ class DiscriminatorSchemaParser extends MonoSchemaParser {
}

createDiscriminatorSchema = ({ skipMappingType, abstractSchemaStruct }) => {
const ts = this.config.Ts;

const refPath = this.schemaComponentsMap.createRef([
'components',
'schemas',
Expand All @@ -71,26 +74,26 @@ class DiscriminatorSchemaParser extends MonoSchemaParser {
});

if (ableToCreateMappingType) {
mappingTypeName = this.schemaUtils.resolveTypeName(
`${abstractSchemaStruct.typeName} ${discriminator.propertyName}`,
{
suffixes: this.config.extractingOptions.discriminatorMappingSuffix,
resolver:
this.config.extractingOptions.discriminatorMappingNameResolver,
},
);
this.schemaParserFabric.createSchema({
linkedComponent: this.schemaComponentsMap.createComponent(
this.schemaComponentsMap.createRef([
'components',
'schemas',
mappingTypeName,
]),
const mappingTypeNameRef = this.schemaComponentsMap.createRef([
'components',
'schemas',
this.schemaUtils.resolveTypeName(
`${abstractSchemaStruct.typeName} ${discriminator.propertyName}`,
{
suffixes: this.config.extractingOptions.discriminatorMappingSuffix,
resolver:
this.config.extractingOptions.discriminatorMappingNameResolver,
},
),
content: this.config.Ts.IntersectionType([
this.config.Ts.ObjectWrapper(
this.config.Ts.TypeField({
key: discriminator.propertyName,
]);
const mappingTypeNameComponent =
this.schemaComponentsMap.createComponent(mappingTypeNameRef);
const mappingTypeNameSchema = this.schemaParserFabric.createSchema({
linkedComponent: mappingTypeNameComponent,
content: ts.IntersectionType([
ts.ObjectWrapper(
ts.TypeField({
key: ts.StringValue(discriminator.propertyName),
value: 'Key',
}),
),
Expand All @@ -99,6 +102,8 @@ class DiscriminatorSchemaParser extends MonoSchemaParser {
genericArgs: [{ name: 'Key' }, { name: 'Type' }],
internal: true,
});

mappingTypeName = mappingTypeNameSchema.typeData.name;
}

/** returns (GenericType<"mapping_key", MappingType>) or ({ discriminatorProperty: "mapping_key" } & MappingType) */
Expand All @@ -112,18 +117,15 @@ class DiscriminatorSchemaParser extends MonoSchemaParser {

const mappingUsageKey =
mappingPropertySchemaEnumKeysMap[mappingKey] ||
this.config.Ts.StringValue(mappingKey);
ts.StringValue(mappingKey);

if (ableToCreateMappingType) {
return this.config.Ts.TypeWithGeneric(mappingTypeName, [
mappingUsageKey,
content,
]);
return ts.TypeWithGeneric(mappingTypeName, [mappingUsageKey, content]);
} else {
return this.config.Ts.ExpressionGroup(
this.config.Ts.IntersectionType([
this.config.Ts.ObjectWrapper(
this.config.Ts.TypeField({
return ts.ExpressionGroup(
ts.IntersectionType([
ts.ObjectWrapper(
ts.TypeField({
key: discriminator.propertyName,
value: mappingUsageKey,
}),
Expand Down Expand Up @@ -151,9 +153,7 @@ class DiscriminatorSchemaParser extends MonoSchemaParser {

if (skipMappingType) return null;

const content = this.config.Ts.ExpressionGroup(
this.config.Ts.UnionType(mappingContents),
);
const content = ts.ExpressionGroup(ts.UnionType(mappingContents));

return {
content,
Expand All @@ -164,6 +164,8 @@ class DiscriminatorSchemaParser extends MonoSchemaParser {
abstractSchemaStruct,
discPropertyName,
}) => {
const ts = this.config.Ts;

let mappingPropertySchemaEnumKeysMap = {};
let mappingPropertySchema = _.get(
abstractSchemaStruct?.component?.rawTypeData,
Expand All @@ -183,7 +185,7 @@ class DiscriminatorSchemaParser extends MonoSchemaParser {
(acc, key, index) => {
const enumKey =
mappingPropertySchema.rawTypeData.$parsed.content[index].key;
acc[key] = this.config.Ts.EnumUsageKey(
acc[key] = ts.EnumUsageKey(
mappingPropertySchema.rawTypeData.$parsed.typeName,
enumKey,
);
Expand Down Expand Up @@ -284,12 +286,13 @@ class DiscriminatorSchemaParser extends MonoSchemaParser {
};

createComplexSchemaStruct = () => {
const ts = this.config.Ts;
const complexType = this.schemaUtils.getComplexType(this.schema);

if (complexType === SCHEMA_TYPES.COMPLEX_UNKNOWN) return null;

return {
content: this.config.Ts.ExpressionGroup(
content: ts.ExpressionGroup(
this.schemaParser._complexSchemaParsers[complexType](this.schema),
),
};
Expand Down
13 changes: 3 additions & 10 deletions src/schema-parser/complex-schema-parsers/any-of.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const { MonoSchemaParser } = require('../mono-schema-parser');
const _ = require('lodash');

// T1 | T2 | (T1 & T2)
// T1 | T2
class AnyOfSchemaParser extends MonoSchemaParser {
parse() {
const ignoreTypes = [this.config.Ts.Keyword.Any];
Expand All @@ -12,20 +12,13 @@ class AnyOfSchemaParser extends MonoSchemaParser {
this.schemaPath,
),
);

const filtered = this.schemaUtils.filterSchemaContents(
combined,
(content) => !ignoreTypes.includes(content),
);

const type = this.config.Ts.UnionType(
_.compact([
...filtered,
filtered.length > 1 &&
this.config.Ts.ExpressionGroup(
this.config.Ts.IntersectionType(filtered),
),
]),
);
const type = this.config.Ts.UnionType(filtered);

return this.schemaUtils.safeAddNullToType(this.schema, type);
}
Expand Down
Loading

0 comments on commit 5729dcf

Please sign in to comment.