From a1b713623de37e28e64a86eedf2938438d9de09d Mon Sep 17 00:00:00 2001 From: Sora Morimoto Date: Sun, 11 Aug 2024 09:56:47 +0900 Subject: [PATCH] Reduce use of lodash Signed-off-by: Sora Morimoto --- cli/execute.js | 4 +- cli/index.js | 10 +- cli/process-option.js | 38 ++-- src/code-formatter.js | 3 +- src/code-gen-process.js | 15 +- .../templates-gen-process.js | 4 +- src/configuration.js | 4 +- src/schema-components-map.js | 4 +- .../base-schema-parsers/array.js | 4 +- .../base-schema-parsers/complex.js | 2 +- .../base-schema-parsers/discriminator.js | 39 ++-- src/schema-parser/base-schema-parsers/enum.js | 20 +- .../base-schema-parsers/object.js | 9 +- .../base-schema-parsers/primitive.js | 26 +-- .../complex-schema-parsers/all-of.js | 3 +- .../complex-schema-parsers/any-of.js | 3 +- .../complex-schema-parsers/one-of.js | 3 +- src/schema-parser/schema-formatters.js | 21 +- src/schema-parser/schema-parser-fabric.js | 2 +- src/schema-parser/schema-utils.js | 47 ++--- src/schema-routes/schema-routes.js | 181 +++++++----------- src/schema-walker.js | 2 +- src/swagger-schema-resolver.js | 7 +- src/templates-worker.js | 19 +- src/type-name-formatter.js | 8 +- src/util/file-system.js | 2 +- src/util/logger.js | 10 +- src/util/name-resolver.js | 13 +- src/util/object-assign.js | 4 +- src/util/request.js | 2 +- 30 files changed, 231 insertions(+), 278 deletions(-) diff --git a/cli/execute.js b/cli/execute.js index 481845fa..de463bc3 100644 --- a/cli/execute.js +++ b/cli/execute.js @@ -98,14 +98,14 @@ const processArgs = (commands, args) => { let allFlagKeys = []; - lodash.forEach(args, (arg, i) => { + args.forEach((arg, i) => { if (error) return; if (i === 0) { command = commands[arg]; if (!command && !arg.startsWith("-")) { - const tip = didYouMean(arg, lodash.keys(commands)); + const tip = didYouMean(arg, commands.keys()); error = `unknown command ${arg}${ tip ? `\n(Did you mean ${tip} ?)` : "" }`; diff --git a/cli/index.js b/cli/index.js index f3954397..7a032c27 100644 --- a/cli/index.js +++ b/cli/index.js @@ -12,7 +12,7 @@ const cli = (input) => { commands[command.name] = { name: command.name, description: `${command.description || ""}`, - options: lodash.compact(lodash.map(command.options, processOption)), + options: lodash.compact(command.options.map(processOption)), }; if (addVersion) { @@ -57,7 +57,7 @@ const cli = (input) => { }, ); - lodash.forEach(input.options, (option) => { + for (const option of input.options) { const processed = processOption(option); if (!processed) return; @@ -68,7 +68,7 @@ const cli = (input) => { } commands[root_command].options.push(processed); - }); + } commands[root_command].options.unshift( processOption({ @@ -86,7 +86,9 @@ const cli = (input) => { }), ); - lodash.forEach(input.commands, addCommand); + for (const command of input.commands) { + addCommand(command); + } return instance; }; diff --git a/cli/process-option.js b/cli/process-option.js index 571ecc59..33ce838d 100644 --- a/cli/process-option.js +++ b/cli/process-option.js @@ -15,28 +15,30 @@ const processFlags = (flags) => { let value = null; const isNoFlag = flags.includes("--no-"); - lodash - .compact(lodash.split(flags, " ").map((str) => str.replace(/,/g, ""))) - .forEach((str) => { - if (str.startsWith("-")) { - keys.push(str); - } else if (value === null) { - if (str.startsWith("{") || str.startsWith("[") || str.startsWith("<")) { - const rawValue = str.replace(/[{[<>}\].]/g, ""); - const variadic = str.includes("..."); - value = { - raw: str, - variadic, - name: rawValue, - formatter: optionFormatters[rawValue] || optionFormatters.string, - }; - } + const strArr = lodash.compact( + flags.split(" ").map((str) => str.replace(/,/g, "")), + ); + + for (const str of strArr) { + if (str.startsWith("-")) { + keys.push(str); + } else if (value === null) { + if (str.startsWith("{") || str.startsWith("[") || str.startsWith("<")) { + const rawValue = str.replace(/[{[<>}\].]/g, ""); + const variadic = str.includes("..."); + value = { + raw: str, + variadic, + name: rawValue, + formatter: optionFormatters[rawValue] || optionFormatters.string, + }; } - }); + } + } const longestKey = keys.slice().sort((a, b) => b.length - a.length)[0]; - if (!lodash.isEmpty(longestKey)) { + if (longestKey !== "") { name = lodash.camelCase( (isNoFlag ? longestKey.replace("--no-", "") : longestKey).replace( /(--?)/, diff --git a/src/code-formatter.js b/src/code-formatter.js index d3d21bb3..5d731e2a 100644 --- a/src/code-formatter.js +++ b/src/code-formatter.js @@ -24,8 +24,7 @@ class CodeFormatter { )[0]; if (fileTextChanges?.textChanges.length) { - return lodash.reduceRight( - fileTextChanges.textChanges, + return fileTextChanges.textChanges.reduceRight( (content, { span, newText }) => `${content.slice(0, span.start)}${newText}${content.slice( span.start + span.length, diff --git a/src/code-gen-process.js b/src/code-gen-process.js index 568a9c39..f6e402ce 100644 --- a/src/code-gen-process.js +++ b/src/code-gen-process.js @@ -177,7 +177,7 @@ class CodeGenProcess { const isDirPath = this.fileSystem.pathIsDir(this.config.output); if (isDirPath) { - files.forEach((file) => { + for (const file of files) { this.fileSystem.createFile({ path: this.config.output, fileName: `${file.fileName}${file.fileExtension}`, @@ -190,7 +190,7 @@ class CodeGenProcess { `"${file.fileName}${file.fileExtension}"`, `created in ${this.config.output}`, ); - }); + } } return { @@ -289,7 +289,12 @@ class CodeGenProcess { rawTypeData, ) : rawTypeData; - let { typeIdentifier, name: originalName, content, description } = typeData; + const { + typeIdentifier, + name: originalName, + content, + description, + } = typeData; const name = this.typeNameFormatter.format(originalName); if (name === null) return null; @@ -560,11 +565,11 @@ class CodeGenProcess { injectClassInstance = (key, value) => { this[key] = value; - PATCHABLE_INSTANCES.forEach((instanceKey) => { + for (const instanceKey of PATCHABLE_INSTANCES) { if (instanceKey !== key && key in this[instanceKey]) { this[instanceKey][key] = value; } - }); + } }; } diff --git a/src/commands/generate-templates/templates-gen-process.js b/src/commands/generate-templates/templates-gen-process.js index 6fe22618..5d174608 100644 --- a/src/commands/generate-templates/templates-gen-process.js +++ b/src/commands/generate-templates/templates-gen-process.js @@ -59,7 +59,7 @@ class TemplatesGenProcess { this.fileSystem.createDir(outputPath); } - templates.forEach((template) => { + for (const template of templates) { const templateName = this.fileSystem.cropExtension(template.name); const templateEjsPath = path.resolve(outputPath, `${templateName}.ejs`); const templateEtaPath = path.resolve(outputPath, `${templateName}.eta`); @@ -94,7 +94,7 @@ class TemplatesGenProcess { }); } } - }); + } this.logger.success( `source templates has been successfully created in "${outputPath}"`, diff --git a/src/configuration.js b/src/configuration.js index 3e30c73e..fdae8728 100644 --- a/src/configuration.js +++ b/src/configuration.js @@ -213,8 +213,8 @@ class CodeGenConfig { customTranslator; Ts = { - Keyword: lodash.cloneDeep(TsKeyword), - CodeGenKeyword: lodash.cloneDeep(TsCodeGenKeyword), + Keyword: structuredClone(TsKeyword), + CodeGenKeyword: structuredClone(TsCodeGenKeyword), /** * $A[] or Array<$A> */ diff --git a/src/schema-components-map.js b/src/schema-components-map.js index db9bcf65..a8936821 100644 --- a/src/schema-components-map.js +++ b/src/schema-components-map.js @@ -61,9 +61,9 @@ class SchemaComponentsMap { * @returns {SchemaComponent[]} */ filter(...componentNames) { - return lodash.filter(this._data, (it) => + return this._data.filter((it) => componentNames.some((componentName) => - lodash.startsWith(it.$ref, `#/components/${componentName}`), + it.$ref.startsWith(`#/components/${componentName}`), ), ); } diff --git a/src/schema-parser/base-schema-parsers/array.js b/src/schema-parser/base-schema-parsers/array.js index 76595e96..690a79bb 100644 --- a/src/schema-parser/base-schema-parsers/array.js +++ b/src/schema-parser/base-schema-parsers/array.js @@ -7,7 +7,7 @@ class ArraySchemaParser extends MonoSchemaParser { let contentType; const { type, description, items } = this.schema || {}; - if (lodash.isArray(items) && type === SCHEMA_TYPES.ARRAY) { + if (Array.isArray(items) && type === SCHEMA_TYPES.ARRAY) { const tupleContent = []; for (const item of items) { tupleContent.push( @@ -25,7 +25,7 @@ class ArraySchemaParser extends MonoSchemaParser { } return { - ...(lodash.isObject(this.schema) ? this.schema : {}), + ...(typeof this.schema === "object" ? this.schema : {}), $schemaPath: this.schemaPath.slice(), $parsedSchema: true, schemaType: SCHEMA_TYPES.PRIMITIVE, diff --git a/src/schema-parser/base-schema-parsers/complex.js b/src/schema-parser/base-schema-parsers/complex.js index c00baff7..2f50d098 100644 --- a/src/schema-parser/base-schema-parsers/complex.js +++ b/src/schema-parser/base-schema-parsers/complex.js @@ -14,7 +14,7 @@ class ComplexSchemaParser extends MonoSchemaParser { ](this.schema); return { - ...(lodash.isObject(this.schema) ? this.schema : {}), + ...(typeof this.schema === "object" ? this.schema : {}), $schemaPath: this.schemaPath.slice(), $parsedSchema: true, schemaType: SCHEMA_TYPES.COMPLEX, diff --git a/src/schema-parser/base-schema-parsers/discriminator.js b/src/schema-parser/base-schema-parsers/discriminator.js index 47200fd6..276f6dc4 100644 --- a/src/schema-parser/base-schema-parsers/discriminator.js +++ b/src/schema-parser/base-schema-parsers/discriminator.js @@ -36,7 +36,7 @@ class DiscriminatorSchemaParser extends MonoSchemaParser { ); return { - ...(lodash.isObject(this.schema) ? this.schema : {}), + ...(typeof this.schema === "object" ? this.schema : {}), $schemaPath: this.schemaPath.slice(), $parsedSchema: true, schemaType: SCHEMA_TYPES.COMPLEX, @@ -121,19 +121,19 @@ class DiscriminatorSchemaParser extends MonoSchemaParser { if (ableToCreateMappingType) { return ts.TypeWithGeneric(mappingTypeName, [mappingUsageKey, content]); - } else { - return ts.ExpressionGroup( - ts.IntersectionType([ - ts.ObjectWrapper( - ts.TypeField({ - key: discriminator.propertyName, - value: mappingUsageKey, - }), - ), - content, - ]), - ); } + + return ts.ExpressionGroup( + ts.IntersectionType([ + ts.ObjectWrapper( + ts.TypeField({ + key: discriminator.propertyName, + value: mappingUsageKey, + }), + ), + content, + ]), + ); }; for (const [mappingKey, schema] of mappingEntries) { @@ -213,8 +213,8 @@ class DiscriminatorSchemaParser extends MonoSchemaParser { const mappingRefSchema = this.schemaUtils.getSchemaRefType(mappingSchema)?.rawTypeData; if (mappingRefSchema) { - complexSchemaKeys.forEach((schemaKey) => { - if (lodash.isArray(mappingRefSchema[schemaKey])) { + for (const schemaKey of complexSchemaKeys) { + if (Array.isArray(mappingRefSchema[schemaKey])) { mappingRefSchema[schemaKey] = mappingRefSchema[schemaKey].map( (schema) => { if (schema.$ref === refPath) { @@ -251,7 +251,7 @@ class DiscriminatorSchemaParser extends MonoSchemaParser { }, ); } - }); + } } } }; @@ -263,13 +263,12 @@ class DiscriminatorSchemaParser extends MonoSchemaParser { this.schemaParser._complexSchemaParsers, ); const schema = lodash.omit( - lodash.clone(noDiscriminatorSchema), + structuredClone(noDiscriminatorSchema), complexSchemaKeys, ); const schemaIsAny = - this.schemaParserFabric.getInlineParseContent( - lodash.cloneDeep(schema), - ) === this.config.Ts.Keyword.Any; + this.schemaParserFabric.getInlineParseContent(structuredClone(schema)) === + this.config.Ts.Keyword.Any; const schemaIsEmpty = !lodash.keys(schema).length; if (schemaIsEmpty || schemaIsAny) return null; diff --git a/src/schema-parser/base-schema-parsers/enum.js b/src/schema-parser/base-schema-parsers/enum.js index e1109aa9..fcd0e3e6 100644 --- a/src/schema-parser/base-schema-parsers/enum.js +++ b/src/schema-parser/base-schema-parsers/enum.js @@ -70,18 +70,12 @@ class EnumSchemaParser extends MonoSchemaParser { return this.config.Ts.NullValue(value); } if ( - lodash.includes( - keyType, - this.schemaUtils.getSchemaType({ type: "number" }), - ) + keyType.includes(this.schemaUtils.getSchemaType({ type: "number" })) ) { return this.config.Ts.NumberValue(value); } if ( - lodash.includes( - keyType, - this.schemaUtils.getSchemaType({ type: "boolean" }), - ) + keyType.includes(this.schemaUtils.getSchemaType({ type: "boolean" })) ) { return this.config.Ts.BooleanValue(value); } @@ -89,15 +83,15 @@ class EnumSchemaParser extends MonoSchemaParser { return this.config.Ts.StringValue(value); }; - if (lodash.isArray(enumNames) && lodash.size(enumNames)) { - content = lodash.map(enumNames, (enumName, index) => { + if (Array.isArray(enumNames) && lodash.size(enumNames)) { + content = enumNames.map((enumName, index) => { const enumValue = lodash.get(this.schema.enum, index); const formattedKey = this.formatEnumKey({ key: enumName, value: enumValue, }); - if (this.config.enumNamesAsValues || lodash.isUndefined(enumValue)) { + if (this.config.enumNamesAsValues || enumValue === undefined) { return { key: formattedKey, type: this.config.Ts.Keyword.String, @@ -112,7 +106,7 @@ class EnumSchemaParser extends MonoSchemaParser { }; }); } else { - content = lodash.map(this.schema.enum, (value) => { + content = this.schema.enum.map((value) => { return { key: this.formatEnumKey({ value }), type: keyType, @@ -122,7 +116,7 @@ class EnumSchemaParser extends MonoSchemaParser { } return { - ...(lodash.isObject(this.schema) ? this.schema : {}), + ...(typeof this.schema === "object" ? this.schema : {}), $ref: $ref, typeName: this.typeName || ($ref && refType.typeName) || null, $parsedSchema: true, diff --git a/src/schema-parser/base-schema-parsers/object.js b/src/schema-parser/base-schema-parsers/object.js index 7b6ebc1c..965122cb 100644 --- a/src/schema-parser/base-schema-parsers/object.js +++ b/src/schema-parser/base-schema-parsers/object.js @@ -7,7 +7,7 @@ class ObjectSchemaParser extends MonoSchemaParser { const contentProperties = this.getObjectSchemaContent(this.schema); return { - ...(lodash.isObject(this.schema) ? this.schema : {}), + ...(typeof this.schema === "object" ? this.schema : {}), $schemaPath: this.schemaPath.slice(), $parsedSchema: true, schemaType: SCHEMA_TYPES.OBJECT, @@ -17,10 +17,9 @@ class ObjectSchemaParser extends MonoSchemaParser { description: this.schemaFormatters.formatDescription( this.schema.description, ), - allFieldsAreOptional: !lodash.some( - lodash.values(contentProperties), - (part) => part.isRequired, - ), + allFieldsAreOptional: !contentProperties + .values() + .some((part) => part.isRequired), content: contentProperties, }; } diff --git a/src/schema-parser/base-schema-parsers/primitive.js b/src/schema-parser/base-schema-parsers/primitive.js index cdfde903..5ee4677f 100644 --- a/src/schema-parser/base-schema-parsers/primitive.js +++ b/src/schema-parser/base-schema-parsers/primitive.js @@ -1,4 +1,3 @@ -import * as lodash from "lodash"; import { SCHEMA_TYPES } from "../../constants.js"; import { MonoSchemaParser } from "../mono-schema-parser.js"; @@ -9,28 +8,29 @@ class PrimitiveSchemaParser extends MonoSchemaParser { this.schema || {}; if (type === this.config.Ts.Keyword.Object && additionalProperties) { - const fieldType = lodash.isObject(additionalProperties) - ? this.schemaParserFabric - .createSchemaParser({ - schema: additionalProperties, - schemaPath: this.schemaPath, - }) - .getInlineParseContent() - : this.config.Ts.Keyword.Any; + const fieldType = + typeof additionalProperties === "object" + ? this.schemaParserFabric + .createSchemaParser({ + schema: additionalProperties, + schemaPath: this.schemaPath, + }) + .getInlineParseContent() + : this.config.Ts.Keyword.Any; contentType = this.config.Ts.RecordType( this.config.Ts.Keyword.String, fieldType, ); } - if (lodash.isArray(type) && type.length) { + if (Array.isArray(type) && type.length) { contentType = this.schemaParser._complexSchemaParsers.oneOf({ - ...(lodash.isObject(this.schema) ? this.schema : {}), + ...(typeof this.schema === "object" ? this.schema : {}), oneOf: type.map((type) => ({ type })), }); } - if (lodash.isArray(items) && type === SCHEMA_TYPES.ARRAY) { + if (Array.isArray(items) && type === SCHEMA_TYPES.ARRAY) { contentType = this.config.Ts.Tuple( items.map((item) => this.schemaParserFabric @@ -41,7 +41,7 @@ class PrimitiveSchemaParser extends MonoSchemaParser { } return { - ...(lodash.isObject(this.schema) ? this.schema : {}), + ...(typeof this.schema === "object" ? this.schema : {}), $schemaPath: this.schemaPath.slice(), $parsedSchema: true, schemaType: SCHEMA_TYPES.PRIMITIVE, diff --git a/src/schema-parser/complex-schema-parsers/all-of.js b/src/schema-parser/complex-schema-parsers/all-of.js index 138de848..6e55f66c 100644 --- a/src/schema-parser/complex-schema-parsers/all-of.js +++ b/src/schema-parser/complex-schema-parsers/all-of.js @@ -1,11 +1,10 @@ -import * as lodash from "lodash"; import { MonoSchemaParser } from "../mono-schema-parser.js"; // T1 & T2 class AllOfSchemaParser extends MonoSchemaParser { parse() { const ignoreTypes = [this.config.Ts.Keyword.Any]; - const combined = lodash.map(this.schema.allOf, (childSchema) => + const combined = this.schema.allOf.map((childSchema) => this.schemaParserFabric.getInlineParseContent( this.schemaUtils.makeAddRequiredToChildSchema(this.schema, childSchema), null, diff --git a/src/schema-parser/complex-schema-parsers/any-of.js b/src/schema-parser/complex-schema-parsers/any-of.js index a1ca18e1..b586575e 100644 --- a/src/schema-parser/complex-schema-parsers/any-of.js +++ b/src/schema-parser/complex-schema-parsers/any-of.js @@ -1,11 +1,10 @@ -import * as lodash from "lodash"; import { MonoSchemaParser } from "../mono-schema-parser.js"; // T1 | T2 class AnyOfSchemaParser extends MonoSchemaParser { parse() { const ignoreTypes = [this.config.Ts.Keyword.Any]; - const combined = lodash.map(this.schema.anyOf, (childSchema) => + const combined = this.schema.anyOf.map((childSchema) => this.schemaParserFabric.getInlineParseContent( this.schemaUtils.makeAddRequiredToChildSchema(this.schema, childSchema), null, diff --git a/src/schema-parser/complex-schema-parsers/one-of.js b/src/schema-parser/complex-schema-parsers/one-of.js index 98ee62aa..bb74060c 100644 --- a/src/schema-parser/complex-schema-parsers/one-of.js +++ b/src/schema-parser/complex-schema-parsers/one-of.js @@ -1,11 +1,10 @@ -import * as lodash from "lodash"; import { MonoSchemaParser } from "../mono-schema-parser.js"; // T1 | T2 class OneOfSchemaParser extends MonoSchemaParser { parse() { const ignoreTypes = [this.config.Ts.Keyword.Any]; - const combined = lodash.map(this.schema.oneOf, (childSchema) => + const combined = this.schema.oneOf.map((childSchema) => this.schemaParserFabric.getInlineParseContent( this.schemaUtils.makeAddRequiredToChildSchema(this.schema, childSchema), null, diff --git a/src/schema-parser/schema-formatters.js b/src/schema-parser/schema-formatters.js index 966a7b4d..f97128f1 100644 --- a/src/schema-parser/schema-formatters.js +++ b/src/schema-parser/schema-formatters.js @@ -28,7 +28,7 @@ class SchemaFormatters { ...parsedSchema, $content: parsedSchema.content, content: this.config.Ts.UnionType( - lodash.map(parsedSchema.content, ({ value }) => value), + parsedSchema.content.map(({ value }) => value), ), }; } @@ -63,20 +63,19 @@ class SchemaFormatters { ? parsedSchema.typeName : this.config.Ts.UnionType( lodash.compact([ - ...lodash.map(parsedSchema.content, ({ value }) => `${value}`), + ...parsedSchema.content.map(({ value }) => `${value}`), parsedSchema.nullable && this.config.Ts.Keyword.Null, ]), ) || this.config.Ts.Keyword.Any, }; }, [SCHEMA_TYPES.OBJECT]: (parsedSchema) => { - if (lodash.isString(parsedSchema.content)) { + if (typeof parsedSchema.content === "string") return { ...parsedSchema, typeIdentifier: this.config.Ts.Keyword.Type, content: this.schemaUtils.safeAddNullToType(parsedSchema.content), }; - } return { ...parsedSchema, @@ -111,25 +110,21 @@ class SchemaFormatters { formatDescription = (description, inline) => { if (!description) return ""; - let prettified = description; - - prettified = lodash.replace(prettified, /\*\//g, "*/"); - - const hasMultipleLines = lodash.includes(prettified, "\n"); + const hasMultipleLines = description.includes("\n"); - if (!hasMultipleLines) return prettified; + if (!hasMultipleLines) return description; if (inline) { return lodash - ._(prettified) + ._(description) .split(/\n/g) - .map((part) => lodash.trim(part)) + .map((part) => part.trim()) .compact() .join(" ") .valueOf(); } - return lodash.replace(prettified, /\n$/g, ""); + return description.replace(/\n$/g, ""); }; formatObjectContent = (content) => { diff --git a/src/schema-parser/schema-parser-fabric.js b/src/schema-parser/schema-parser-fabric.js index 34323b38..ced460da 100644 --- a/src/schema-parser/schema-parser-fabric.js +++ b/src/schema-parser/schema-parser-fabric.js @@ -73,7 +73,7 @@ class SchemaParserFabric { }; createParsedComponent = ({ typeName, schema, schemaPath }) => { - const schemaCopy = lodash.cloneDeep(schema); + const schemaCopy = structuredClone(schema); const customComponent = this.schemaComponentsMap.createComponent( this.schemaComponentsMap.createRef(["components", "schemas", typeName]), schemaCopy, diff --git a/src/schema-parser/schema-utils.js b/src/schema-parser/schema-utils.js index 0c9558e9..48f18e46 100644 --- a/src/schema-parser/schema-utils.js +++ b/src/schema-parser/schema-utils.js @@ -27,7 +27,7 @@ class SchemaUtils { getRequiredProperties = (schema) => { return lodash.uniq( - (schema && lodash.isArray(schema.required) && schema.required) || [], + (schema && Array.isArray(schema.required) && schema.required) || [], ); }; @@ -55,11 +55,12 @@ class SchemaUtils { return true; } - const isRequired = lodash.isBoolean(propertySchema.required) - ? !!propertySchema.required - : lodash.isArray(rootSchema.required) - ? rootSchema.required.includes(name) - : !!rootSchema.required; + const isRequired = + typeof propertySchema.required === "boolean" + ? !!propertySchema.required + : Array.isArray(rootSchema.required) + ? rootSchema.required.includes(name) + : !!rootSchema.required; if (this.config.convertedFromSwagger2) { return typeof propertySchema.nullable === this.config.Ts.Keyword.Undefined @@ -75,7 +76,7 @@ class SchemaUtils { (nullable || !!lodash.get(schema, "x-nullable") || schemaType === this.config.Ts.Keyword.Null) && - lodash.isString(type) && + typeof type === "string" && !type.includes(` ${this.config.Ts.Keyword.Null}`) && !type.includes(`${this.config.Ts.Keyword.Null} `) ); @@ -155,7 +156,9 @@ class SchemaUtils { ...childSchema, $$requiredKeys: existedRequiredKeys, }; - } else if (childSchema.properties) { + } + + if (childSchema.properties) { const childSchemaProperties = lodash.keys(childSchema.properties); const existedRequiredKeys = childSchemaProperties.filter((key) => required.includes(key), @@ -176,7 +179,7 @@ class SchemaUtils { }; filterSchemaContents = (contents, filterFn) => { - return lodash.uniq(lodash.filter(contents, (type) => filterFn(type))); + return lodash.uniq(contents.filter((type) => filterFn(type))); }; resolveTypeName = ( @@ -187,19 +190,19 @@ class SchemaUtils { return this.config.componentTypeNameResolver.resolve(null, (reserved) => { return resolver(pascalCase(typeName), reserved); }); - } else { - return this.config.componentTypeNameResolver.resolve( - [ - ...(prefixes || []).map((prefix) => - pascalCase(`${prefix} ${typeName}`), - ), - ...(suffixes || []).map((suffix) => - pascalCase(`${typeName} ${suffix}`), - ), - ], - shouldReserve, - ); } + + return this.config.componentTypeNameResolver.resolve( + [ + ...(prefixes || []).map((prefix) => + pascalCase(`${prefix} ${typeName}`), + ), + ...(suffixes || []).map((suffix) => + pascalCase(`${typeName} ${suffix}`), + ), + ], + shouldReserve, + ); }; getComplexType = (schema) => { @@ -269,7 +272,7 @@ class SchemaUtils { lodash.get(this.config.primitiveTypes, [primitiveType, "$default"]) || this.config.primitiveTypes[primitiveType]; - if (lodash.isFunction(typeAlias)) { + if (typeof typeAlias === "function") { resultType = typeAlias(schema, this); } else { resultType = typeAlias || primitiveType; diff --git a/src/schema-routes/schema-routes.js b/src/schema-routes/schema-routes.js index d94b30e0..e30bb33e 100644 --- a/src/schema-routes/schema-routes.js +++ b/src/schema-routes/schema-routes.js @@ -84,7 +84,7 @@ class SchemaRoutes { routeInfoByMethodsMap, (acc, requestInfo, method) => { if ( - lodash.startsWith(method, "x-") || + method.startsWith("x-") || ["parameters", "$ref"].includes(method) ) { return acc; @@ -116,11 +116,11 @@ class SchemaRoutes { const pathParams = lodash.reduce( pathParamMatches, (pathParams, match) => { - const paramName = lodash.replace(match, /\{|\}|:/g, ""); + const paramName = match.replace(/\{|\}|:/g, ""); if (!paramName) return pathParams; - if (lodash.includes(paramName, "-")) { + if (paramName.includes("-")) { this.logger.warn("wrong path param name", paramName); } @@ -141,53 +141,49 @@ class SchemaRoutes { [], ); - let fixedRoute = lodash.reduce( - pathParams, - (fixedRoute, pathParam, i, arr) => { - const insertion = - this.config.hooks.onInsertPathParam( - pathParam.name, - i, - arr, - fixedRoute, - ) || pathParam.name; - return lodash.replace(fixedRoute, pathParam.$match, `\${${insertion}}`); - }, - routeName || "", - ); + let fixedRoute = pathParams.reduce((fixedRoute, pathParam, i, arr) => { + const insertion = + this.config.hooks.onInsertPathParam( + pathParam.name, + i, + arr, + fixedRoute, + ) || pathParam.name; + return fixedRoute.replace(pathParam.$match, `\${${insertion}}`); + }, routeName || ""); const queryParamMatches = fixedRoute.match(/(\{\?.*\})/g); const queryParams = []; if (queryParamMatches?.length) { - queryParamMatches.forEach((match) => { + for (const match of queryParamMatches) { fixedRoute = fixedRoute.replace(match, ""); - }); + } - lodash - .uniq( - queryParamMatches - .join(",") - .replace(/(\{\?)|(\})|\s/g, "") - .split(","), - ) - .forEach((paramName) => { - if (lodash.includes(paramName, "-")) { - this.logger.warn("wrong query param name", paramName); - } + const paramNames = lodash.uniq( + queryParamMatches + .join(",") + .replace(/(\{\?)|(\})|\s/g, "") + .split(","), + ); + + for (const paramName of paramNames) { + if (paramName.includes("-")) { + this.logger.warn("wrong query param name", paramName); + } - queryParams.push({ - $match: paramName, - name: lodash.camelCase(paramName), - required: true, + queryParams.push({ + $match: paramName, + name: lodash.camelCase(paramName), + required: true, + type: "string", + description: "", + schema: { type: "string", - description: "", - schema: { - type: "string", - }, - in: "query", - }); + }, + in: "query", }); + } } const result = { @@ -255,27 +251,26 @@ class SchemaRoutes { }); // used in case when path parameters is not declared in requestInfo.parameters ("in": "path") - lodash.each(pathParamsFromRouteName, (pathParam) => { - const alreadyExist = lodash.some( - routeParams.path, + for (const pathParam of pathParamsFromRouteName) { + const alreadyExist = routeParams.path.some( (parameter) => parameter.name === pathParam.name, ); if (!alreadyExist) { routeParams.path.push(pathParam); } - }); + } + // used in case when path parameters is not declared in requestInfo.parameters ("in": "path") - lodash.each(queryParamsFromRouteName, (queryParam) => { - const alreadyExist = lodash.some( - routeParams.query, + for (const queryParam of queryParamsFromRouteName) { + const alreadyExist = routeParams.query.some( (parameter) => parameter.name === queryParam.name, ); if (!alreadyExist) { routeParams.query.push(queryParam); } - }); + } return routeParams; }; @@ -296,12 +291,10 @@ class SchemaRoutes { getContentKind = (contentTypes) => { if ( - lodash.some(contentTypes, (contentType) => - lodash.startsWith(contentType, "application/json"), + contentTypes.some((contentType) => + contentType.startsWith("application/json"), ) || - lodash.some(contentTypes, (contentType) => - lodash.endsWith(contentType, "+json"), - ) + contentTypes.some((contentType) => contentType.endsWith("+json")) ) { return CONTENT_KIND.JSON; } @@ -314,19 +307,11 @@ class SchemaRoutes { return CONTENT_KIND.FORM_DATA; } - if ( - lodash.some(contentTypes, (contentType) => - lodash.includes(contentType, "image/"), - ) - ) { + if (contentTypes.some((contentType) => contentType.includes("image/"))) { return CONTENT_KIND.IMAGE; } - if ( - lodash.some(contentTypes, (contentType) => - lodash.startsWith(contentType, "text/"), - ) - ) { + if (contentTypes.some((contentType) => contentType.startsWith("text/"))) { return CONTENT_KIND.TEXT; } @@ -377,12 +362,11 @@ class SchemaRoutes { typeName, [operationId], ); - const foundedSchemaByName = lodash.find( - parsedSchemas, + const foundedSchemaByName = parsedSchemas.find( (parsedSchema) => this.typeNameFormatter.format(parsedSchema.name) === content, ); - const foundSchemaByContent = lodash.find(parsedSchemas, (parsedSchema) => + const foundSchemaByContent = parsedSchemas.find((parsedSchema) => lodash.isEqual(parsedSchema.content, content), ); @@ -398,17 +382,8 @@ class SchemaRoutes { // const foundedSchemaByName = _.find(parsedSchemas, ({ name }) => name === refType || name === refTypeWithoutOpId) // TODO:HACK fix problem of swagger2opeanpi - const typeNameWithoutOpId = lodash.replace( - refTypeInfo.typeName, - operationId, - "", - ); - if ( - lodash.find( - parsedSchemas, - (schema) => schema.name === typeNameWithoutOpId, - ) - ) { + const typeNameWithoutOpId = refTypeInfo.typeName.replace(operationId, ""); + if (parsedSchemas.find((schema) => schema.name === typeNameWithoutOpId)) { return this.typeNameFormatter.format(typeNameWithoutOpId); } @@ -465,7 +440,7 @@ class SchemaRoutes { requestInfo.description || "", true, ), - status: lodash.isNaN(+status) ? status : +status, + status: Number.isNaN(+status) ? status : +status, isSuccess: this.isSuccessStatus(status), }, ]; @@ -542,8 +517,7 @@ class SchemaRoutes { }; convertRouteParamsIntoObject = (params) => { - return lodash.reduce( - params, + return params.reduce( (objectSchema, schemaPart) => { if (!schemaPart || !schemaPart.name) return objectSchema; @@ -625,7 +599,7 @@ class SchemaRoutes { // but request body data type contains form data types like File if ( this.FORM_DATA_TYPES.some((dataType) => - lodash.includes(content, `: ${dataType}`), + content.includes(`: ${dataType}`), ) ) { contentKind = CONTENT_KIND.FORM_DATA; @@ -664,25 +638,21 @@ class SchemaRoutes { }) => { if (!queryParams || !queryParams.length) return null; - const pathParams = lodash.reduce( - pathArgsSchemas, - (acc, pathArgSchema) => { - if (pathArgSchema.name) { - acc[pathArgSchema.name] = { - ...pathArgSchema, - in: "path", - }; - } + const pathParams = pathArgsSchemas.reduce((acc, pathArgSchema) => { + if (pathArgSchema.name) { + acc[pathArgSchema.name] = { + ...pathArgSchema, + in: "path", + }; + } - return acc; - }, - {}, - ); + return acc; + }, {}); const fixedQueryParams = lodash.reduce( lodash.get(queryObjectSchema, "properties", {}), (acc, property, name) => { - if (name && lodash.isObject(property)) { + if (name && typeof property === "object") { acc[name] = { ...property, in: "query", @@ -739,7 +709,7 @@ class SchemaRoutes { responseBodyInfo.success.schema, ); - let successResponse = responseBodyInfo.success; + const successResponse = responseBodyInfo.success; if (successResponse.schema && !successResponse.schema.$ref) { const contentKind = successResponse.schema.contentKind; @@ -894,9 +864,7 @@ class SchemaRoutes { const moduleName = moduleNameFirstTag && firstTag ? lodash.camelCase(firstTag) - : lodash.camelCase( - lodash.compact(lodash.split(route, "/"))[moduleNameIndex], - ); + : lodash.camelCase(lodash.compact(route.split("/"))[moduleNameIndex]); let hasSecurity = !!globalSecurity?.length; if (security) { hasSecurity = security.length > 0; @@ -1065,7 +1033,7 @@ class SchemaRoutes { return { id: routeId, - namespace: lodash.replace(moduleName, /^(\d)/, "v$1"), + namespace: moduleName.replace(/^(\d)/, "v$1"), routeName, routeParams, requestBodyInfo, @@ -1107,10 +1075,10 @@ class SchemaRoutes { const pathsEntries = lodash.entries(usageSchema.paths); - lodash.forEach(pathsEntries, ([rawRouteName, routeInfoByMethodsMap]) => { + for (const [rawRouteName, routeInfoByMethodsMap] of pathsEntries) { const routeInfosMap = this.createRequestsMap(routeInfoByMethodsMap); - lodash.forEach(routeInfosMap, (routeInfo, method) => { + for (const [method, routeInfo] of Object.entries(routeInfosMap)) { const parsedRouteInfo = this.parseRouteInfo( rawRouteName, routeInfo, @@ -1135,8 +1103,8 @@ class SchemaRoutes { this.routes.push(route); } - }); - }); + } + } }; getGroupedRoutes = () => { @@ -1169,7 +1137,7 @@ class SchemaRoutes { acc.combined.push({ moduleName, - routes: lodash.map(routesGroup, (route) => { + routes: routesGroup.map((route) => { const { original: originalName, usage: usageName } = route.routeName; @@ -1178,8 +1146,7 @@ class SchemaRoutes { if ( routesGroup.length > 1 && usageName !== originalName && - !lodash.some( - routesGroup, + !routesGroup.some( ({ routeName, id }) => id !== route.id && originalName === routeName.original, ) diff --git a/src/schema-walker.js b/src/schema-walker.js index a9891df0..dfdea275 100644 --- a/src/schema-walker.js +++ b/src/schema-walker.js @@ -24,7 +24,7 @@ class SchemaWalker { * @param schema {Record} */ addSchema = (name, schema) => { - this.schemas.set(name, lodash.cloneDeep(schema)); + this.schemas.set(name, structuredClone(schema)); }; /** diff --git a/src/swagger-schema-resolver.js b/src/swagger-schema-resolver.js index a5dda295..08348f5c 100644 --- a/src/swagger-schema-resolver.js +++ b/src/swagger-schema-resolver.js @@ -67,7 +67,7 @@ class SwaggerSchemaResolver { */ convertSwaggerObject(swaggerSchema, converterOptions) { return new Promise((resolve) => { - const result = lodash.cloneDeep(swaggerSchema); + const result = structuredClone(swaggerSchema); result.info = lodash.merge( { title: "No title", @@ -106,7 +106,7 @@ class SwaggerSchemaResolver { } else { resolve({ usageSchema: result, - originalSchema: lodash.cloneDeep(result), + originalSchema: structuredClone(result), }); } }); @@ -181,8 +181,7 @@ class SwaggerSchemaResolver { } lodash.each(originalRouteParams, (originalRouteParam) => { - const existUsageParam = lodash.find( - usageRouteParams, + const existUsageParam = usageRouteParams.find( (param) => originalRouteParam.in === param.in && originalRouteParam.name === param.name, diff --git a/src/templates-worker.js b/src/templates-worker.js index 10fe50bc..b7eaba3c 100644 --- a/src/templates-worker.js +++ b/src/templates-worker.js @@ -61,8 +61,7 @@ class TemplatesWorker { cropExtension = (path) => this.config.templateExtensions.reduce( - (path, ext) => - lodash.endsWith(path, ext) ? path.replace(ext, "") : path, + (path, ext) => (path.endsWith(ext) ? path.replace(ext, "") : path), path, ); @@ -79,8 +78,7 @@ class TemplatesWorker { requireFnFromTemplate = async (packageOrPath) => { const isPath = - lodash.startsWith(packageOrPath, "./") || - lodash.startsWith(packageOrPath, "../"); + packageOrPath.startsWith("./") || packageOrPath.startsWith("../"); if (isPath) { return await import( @@ -112,7 +110,7 @@ class TemplatesWorker { if (fileContent) { this.logger.log( - `"${lodash.lowerCase(name)}" template found in "${templatePaths.custom}"`, + `"${name.toLowerCase()}" template found in "${templatePaths.custom}"`, ); return fileContent; } @@ -124,16 +122,14 @@ class TemplatesWorker { } else { if (templatePaths.custom) { this.logger.warn( - `"${lodash.lowerCase(name)}" template not found in "${ + `"${name.toLowerCase()}" template not found in "${ templatePaths.custom }"`, "\nCode generator will use the default template", ); } else { this.logger.log( - `Code generator will use the default template for "${lodash.lowerCase( - name, - )}"`, + `Code generator will use the default template for "${name.toLowerCase()}"`, ); } } @@ -178,11 +174,10 @@ class TemplatesWorker { getTemplateContent = (path) => { const foundTemplatePathKey = lodash .keys(this.config.templatePaths) - .find((key) => lodash.startsWith(path, `@${key}`)); + .find((key) => path.startsWith(`@${key}`)); const rawPath = resolve( - lodash.replace( - path, + path.replace( `@${foundTemplatePathKey}`, this.config.templatePaths[foundTemplatePathKey], ), diff --git a/src/type-name-formatter.js b/src/type-name-formatter.js index a96dc087..10114c80 100644 --- a/src/type-name-formatter.js +++ b/src/type-name-formatter.js @@ -59,11 +59,9 @@ class TypeNameFormatter { const fixedModelName = this.fixModelName(name, { type: schemaType }); - const formattedName = lodash.replace( - lodash.startCase(`${typePrefix}_${fixedModelName}_${typeSuffix}`), - /\s/g, - "", - ); + const formattedName = lodash + .startCase(`${typePrefix}_${fixedModelName}_${typeSuffix}`) + .replace(/\s/g, ""); const formattedResultName = this.config.hooks.onFormatTypeName(formattedName, name, schemaType) || formattedName; diff --git a/src/util/file-system.js b/src/util/file-system.js index ea362d4d..8826fa83 100644 --- a/src/util/file-system.js +++ b/src/util/file-system.js @@ -45,7 +45,7 @@ class FileSystem { }; cropExtension = (fileName) => { - const fileNameParts = lodash.split(fileName, "."); + const fileNameParts = fileName.split("."); if (fileNameParts.length > 1) { fileNameParts.pop(); diff --git a/src/util/logger.js b/src/util/logger.js index 0f293a9b..80a3deac 100644 --- a/src/util/logger.js +++ b/src/util/logger.js @@ -43,21 +43,21 @@ class Logger { } logFn( "[message]", - ...lodash.map(messages, (message) => - lodash.startsWith(message, "\n") + ...messages.map((message) => + message.startsWith("\n") ? `\n ${message.replace(/\n/, "")}` : message, ), ); - logFn(trace.join("\n") + "\n---"); + logFn(`${trace.join("\n")}\n---`); return; } console[type]( emoji, " ", - ...lodash.map(messages, (message) => - lodash.startsWith(message, "\n") + ...messages.map((message) => + message.startsWith("\n") ? `\n${emoji} ${message.replace(/\n/, "")}` : message, ), diff --git a/src/util/name-resolver.js b/src/util/name-resolver.js index 03f6503b..06a5110f 100644 --- a/src/util/name-resolver.js +++ b/src/util/name-resolver.js @@ -40,10 +40,7 @@ class NameResolver { } isReserved(name) { - return lodash.some( - this.reservedNames, - (reservedName) => reservedName === name, - ); + return this.reservedNames.some((reservedName) => reservedName === name); } /** @@ -73,15 +70,17 @@ class NameResolver { shouldReserve && this.reserve([usageName]); return usageName; - } else if (Array.isArray(variants)) { + } + + if (Array.isArray(variants)) { let usageName = null; const uniqVariants = lodash.uniq(lodash.compact(variants)); - lodash.forEach(uniqVariants, (variant) => { + for (const variant of uniqVariants) { if (!usageName && (!shouldReserve || !this.isReserved(variant))) { usageName = variant; } - }); + } if (usageName) { shouldReserve && this.reserve([usageName]); diff --git a/src/util/object-assign.js b/src/util/object-assign.js index d008a501..ac261256 100644 --- a/src/util/object-assign.js +++ b/src/util/object-assign.js @@ -8,9 +8,9 @@ const objectAssign = (target, updaterFn) => { .map(update, (value, key) => value === undefined && key) .filter(Boolean); Object.assign(target, lodash.merge(target, update)); - undefinedKeys.forEach((key) => { + for (const key of undefinedKeys) { target[key] = undefined; - }); + } }; export { objectAssign }; diff --git a/src/util/request.js b/src/util/request.js index 326f2736..9a2a1f42 100644 --- a/src/util/request.js +++ b/src/util/request.js @@ -28,7 +28,7 @@ class Request { */ const requestOptions = {}; - if (disableStrictSSL && !lodash.startsWith(url, "http://")) { + if (disableStrictSSL && !url.startsWith("http://")) { const undiciGlobalDispatcher = global[Symbol.for("undici.globalDispatcher.1")]; if (!undiciGlobalDispatcher) {