Method and device for generating front-end code based on Swagger document and electronic equipment

By analyzing the Swagger document to generate TypeScript type definitions and front-end page code, the problem of automatic generation of front-end page components and deep integration in the existing technology is solved, and efficient and automated front-end code generation is achieved, which improves development efficiency and code quality.

CN120508287APending Publication Date: 2025-08-19CHINA ELECTRONICS CLOUD DIGITAL INTELLIGENCE TECH CO LTD
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202510605490.6
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2025-05-12
Publication Date
2025-08-19

AI Technical Summary

Technical Problem

The existing technology cannot efficiently generate front-end page components automatically, front-end interface definitions are inconsistent, type definition maintenance costs are high, multiple codes need to be manually modified when interface changes, and it is impossible to deeply integrate with front-end engineering processes.

Method used

By analyzing the JSON data of the Swagger document, generating TypeScript type definition and complete front-end page code, using the Vite plug-in to automatically generate code in the development stage, and supporting incremental updates to achieve in-depth integration with the front-end engineering process.

Benefits of technology

Significantly reduce duplicate code writing, ensure front-end consistency, reduce maintenance costs, improve development efficiency and code quality, and adapt to different project needs.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN120508287A_ABST
    Figure CN120508287A_ABST
Patent Text Reader

Abstract

The invention relates to a method and a device for generating a front-end code based on a Swager document. The method comprises the following steps: acquiring JSON (JavaScript Object Notation) data of a Swagger document; analyzing the JSON data to extract interface and data model information; generating a TypeScript type definition and an interface calling method based on the extracted information; generating front-end page codes, such as a list page, a form page and a detail page, according to user configuration; and generating routing configuration and outputting all codes to a specified directory. The method is realized through a Vite plug-in, is seamlessly integrated into a front-end development process, and supports real-time generation and configuration in a development mode. According to the method, full-link code generation from interface definition to a complete page is realized, repeated code writing work is reduced, and the development efficiency is improved; the generated code has deep type support, so that front and rear end definitions are ensured to be completely consistent, and the code quality is improved; when the interface is changed, only codes need to be regenerated, so that the maintenance cost is reduced; the method supports custom templates and generation rules, is flexible and extensible, and can adapt to different project requirements.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] The present application relates to the field of front-end development technology, and in particular to a method, device, computer-readable storage medium, and electronic device for generating front-end code based on a Swagger document. Background Art

[0002] With the increasing popularity of the front-end and back-end separation development model, Swagger (also known as OpenAPI) documents have become widely used as a standardized interface description tool to define and describe the structure and behavior of back-end API interfaces. Front-end developers must manually write interface call code, type definitions, and page logic based on the Swagger documents provided by the back-end. However, in front-end development, there are still many challenges in effectively utilizing Swagger documents to automatically generate front-end code, especially in deeply integrating and automating the front-end engineering process.

[0003] Existing technologies and their limitations Swagger Codegen: This tool generates client SDK code, such as TypeScript interface definitions, based on Swagger documentation. It primarily focuses on generating basic request-layer code. However, it is limited to generating interface call code and cannot automatically generate front-end page components (such as list pages and form pages). This feature doesn't meet the requirements for complete page components in front-end development.

[0004] OpenAPI Generator: This expands its generation scope to include interface definitions and DTO (Data Transfer Object) types. However, its limitations lie in its lack of deep integration with front-end engineering processes. Developers must manually copy the generated code into their front-end projects, increasing development workload and the risk of errors.

[0005] Low-code platforms (such as Alibaba Feibing) support page generation through visual configuration. However, their limitations lie in their reliance on a visual configuration interface and their inability to directly parse JSON data for fully automated code generation. The generated code is poorly coupled with the project architecture, making it difficult to adapt to the engineering requirements of complex projects.

[0006] Traditional tools: Designed to decouple front-end and back-end protocols, they primarily provide code generation for the interface call layer. Limitations include a lack of support for UI code generation, making it impossible to generate front-end components that are strongly tied to interface data. Furthermore, they employ a "one-time generation" model, lacking a dynamic binding relationship between code and Swagger documentation and an incremental update mechanism. Consequently, the generated code cannot be automatically updated when the Swagger documentation is updated or new content is added.

[0007] In summary, the current front-end code generation methods have the following main problems: 1. Manually writing a large amount of repetitive code is inefficient.

[0008] 2. The front-end and back-end interface definitions are prone to inconsistency.

[0009] 3. Type definition maintenance cost is high.

[0010] 4. The page template code is written repeatedly.

[0011] 5. When the interface changes, multiple codes need to be modified simultaneously.

[0012] Although there are some Swagger document parsing tools available, most of them can only generate simple interface definitions and cannot fully generate all the code structures required for front-end projects, nor can they be deeply integrated with front-end build tools. Summary of the Invention

[0013] In order to solve the above problems existing in the prior art, the present invention proposes a new method for generating front-end code based on Swagger documents. The present invention is a technical solution for parsing JSON data through Node.js and automatically generating front-end request interface definition, TypeScript type definition and complete front-end page code (including list page code, form page code and detail page code) on this basis.

[0014] Explanation of terms: Swagger / OpenAPI specification: Standardized interface description format, providing a machine-readable JSON data structure for defining and describing the structure and behavior of HTTP API interfaces.

[0015] Front-end engineering and build tool (Vite): Vite is a modern front-end build tool that supports injecting custom logic into the build process and extending functionality through a plug-in mechanism.

[0016] TypeScript type system: TypeScript uses a type inference mechanism to automatically infer the types of variables and functions based on the context, thereby achieving conversion from the Schema in the Swagger document to the TypeScript type definition.

[0017] This application aims to provide a front-end code generation method that is efficient, automated, and deeply integrated with the front-end engineering process to address the shortcomings of existing technologies and improve development efficiency and code quality. To achieve the above objectives, the present invention adopts the following technical strategies: (1) Expanding the scope of code generation Parse the paths and components fields of JSON data and automatically generate interface call layer code, TypeScript type definitions, and associated page components (such as list pages, form pages, detail pages, etc.).

[0018] By parsing the Schema in the JSON data and using TypeScript's type inference mechanism, the Schema is converted into a TypeScript type definition, ensuring that the generated code is type-safe and maintainable.

[0019] (2) Deep integration of front-end engineering processes It is implemented as a Vite plugin and automatically generates code during the development phase (dev).

[0020] It supports interface generation configuration and page generation configuration, allowing developers to flexibly customize the generated code according to project requirements.

[0021] Utilize Vite's plug-in mechanism to inject custom logic into the build process, ensuring that the generated code is tightly integrated with the front-end engineering architecture.

[0022] (3) Improve maintainability and scalability When the Swagger document is updated or added, you can configure it to generate the updated or added parts to achieve incremental updates.

[0023] Provides interface field definition standards used by page code templates, allowing developers to customize generation logic by modifying template files, enhancing the flexibility and scalability of code generation.

[0024] In general, the core processing flow of the present invention is as follows: Get the JSON data of the Swagger document; Parse the document structure and extract interface information through Swagger document intelligent parsing methods (such as multi-level JSON parsing algorithm, interface parameter automatic classification technology, nested type recursive parsing method, etc.); Generate interface TS type definitions through TypeScript type inference algorithms (including interface method template generation, parameter and return value type mapping); Generate API call method; Generate complete page code according to configuration; Output to the specified directory structure.

[0025] Specifically, this application provides the following technical solutions: A first aspect of the present application provides a method for generating front-end code based on a Swagger document, the method comprising: Get the JSON data of the Swagger document; Parse the JSON data of the Swagger document and extract the interface information and data model information; Generate the corresponding TypeScript type definition based on the parsed data model information; Generate interface calling method based on the parsed interface information; Generate front-end page code based on user configuration and generated TypeScript type definitions and interface calling methods; Generate routing configuration based on the generated front-end page code and user-configured routing rules; Output all generated code files to the specified directory structure.

[0026] Furthermore, in the present application method, obtaining the JSON data of the Swagger document includes: The front-end developer enters the URL address of the Swagger document JSON through the configuration interface; The backend service of the Vite plugin receives the URL and uses the node-fetch module to initiate an HTTP GET request to the URL to obtain the JSON data of the Swagger document.

[0027] Furthermore, in the present application method, the parsing of the JSON data of the Swagger document includes: Parse the paths field and extract each interface path, supported HTTP methods, operation ID, parameters, request body, and response; Parse the components or definitions field, extract all defined data models, and store them in a lookup table.

[0028] Furthermore, in the method of the present application, generating the corresponding TypeScript type definition includes: Use the nested type recursive parsing algorithm and TypeScript type inference algorithm to traverse the parsed Schema definition; For basic types, they are directly mapped to TypeScript basic types; For object types, a TypeScript interface is generated, its properties fields are iterated over, and the type generation logic is recursively called for each property; For array types, parse its items field and recursively call the type generation logic on the items' Schema to generate the type of the array elements. For ref references, parse the Schema definition pointed to by the ref and generate the corresponding TypeScript type.

[0029] Furthermore, in the method of the present application, the method for generating an interface call includes: Traverse the parsed interface information, identify and classify the parameters of each interface; Generate an asynchronous TypeScript function for each interface. The function name is generated based on operationId or path + method name. The function parameters are generated according to the interface parameter definition, and the function body uses the preset HTTP request library call template; According to the interface definition, build a request configuration object, including url, method, params, data and headers; The return value type of the function is the response body type wrapped by Promise.

[0030] Furthermore, in the method of the present application, generating the front-end page code includes: Users can select the API interface for list query, detail query, add / edit submission, and delete operations through the configuration interface; For the list page, specify which interface response fields are displayed as table columns, the table query items, set these fields to be displayed / removed, the field labels, and the corresponding UI component types; For form pages and detail pages, specify which fields to display / remove, field labels, corresponding UI component types, validation rules, and whether they are required. Use predefined, configurable page templates, combined with user configuration, generated type definitions and interface methods to generate complete Vue page component code.

[0031] Furthermore, in the method of the present application, generating a routing configuration includes: Create routing records for list pages, form pages, and detail pages, specifying the routing path, name, and corresponding components; Use dynamic import to reference the generated page file.

[0032] Furthermore, the method of the present application is implemented through a Vite plug-in, which is activated during the startup or build process of the front-end development server and contains a Swagger document parser, a code generator, and a configuration management module.

[0033] A second aspect of the present application provides a device for generating front-end code based on a Swagger document, the device comprising: Get module, used to get JSON data of Swagger document; A parsing module, used to parse the JSON data of the Swagger document and extract interface information and data model information; The type definition generation module is used to generate the corresponding TypeScript type definition based on the parsed data model information; The interface calling method generation module is used to generate the interface calling method according to the parsed interface information; The page code generation module is used to generate the front-end page code based on the user configuration and generated TypeScript type definition and interface call method; The routing configuration generation module is used to generate routing configuration based on the generated front-end page code and the routing rules configured by the user; The output module is used to output all generated code files to the specified directory structure.

[0034] The device implements the steps of the aforementioned method for generating front-end code based on the Swagger document at runtime.

[0035] A third aspect of the present application provides an electronic device, comprising: a memory and a processor; Memory: used to store computer programs; Processor: used to execute the computer program to implement the steps of the aforementioned method for generating front-end code based on the Swagger document.

[0036] A fourth aspect of the present application provides a computer-readable storage medium having a computer program stored thereon. When the computer program is executed by a processor, the steps of the aforementioned method for generating front-end code based on a Swagger document are implemented.

[0037] In summary, this application method has the following advantages: Full-link code generation: It has the ability to generate full-link code from interface definition to complete page components (such as list pages, form pages, detail pages, etc.), covering the entire development process from front-end to back-end.

[0038] Deep type support: Provides complete TypeScript type inference and generation to ensure that the generated code is type-safe and consistent.

[0039] Build tool integration: Seamlessly integrated into the front-end development process as a Vite plug-in, it supports automatic code generation during the development phase and is closely integrated with the front-end engineering process.

[0040] Configurable templates: Supports custom code templates and generation rules, allowing developers to flexibly adjust the generated code according to project requirements.

[0041] The beneficial effects of the present invention include: Improve development efficiency: Significantly reduce repetitive code writing, and it is expected to reduce manual coding workload by more than 80%.

[0042] Ensure consistency: Ensure that the front-end and back-end interface definitions are completely consistent to avoid inconsistencies caused by manually written code.

[0043] Reduce maintenance costs: When the interface changes, only the relevant code needs to be regenerated without manual modification, which reduces maintenance difficulty and cost.

[0044] Improve code quality: Automatically generate TypeScript type definitions that comply with specifications to improve code readability and maintainability.

[0045] Flexible and scalable: Supports custom templates and generation rules to adapt to the needs of different projects and enhance the flexibility and scalability of the solution.

[0046] The present invention can be widely applied to the following scenarios: Enterprise-level front-end development projects: suitable for large-scale enterprise applications, improving development efficiency and code quality.

[0047] Development of mid- and back-end management systems: quickly generate page components and interface call codes for the management system to speed up the development process.

[0048] Rapid prototyping project: supports rapid generation of prototype code and shortens project cycle.

[0049] TypeScript projects: Particularly suitable for TypeScript projects that require strict type checking to ensure type safety.

[0050] Front-end and back-end separation architecture project: seamlessly integrate into the front-end and back-end separation development model to improve development efficiency and reduce maintenance costs.

[0051] Furthermore, the implementation source code of this invention has been validated in real-world projects, demonstrating its ability to significantly improve development efficiency and reduce maintenance costs. Through integration as a Vite plugin, this solution can be seamlessly integrated into modern front-end development workflows, demonstrating its high practicality and promotional value.

[0052] Other features and advantages of this application will be described in detail in the following description, or will be understood through the implementation of the relevant technical solutions of this application. The objectives and other advantages of this application can be achieved through the technical features and technical means clearly indicated in the description, claims, and drawings, and obtained through the implementation of these technical contents. BRIEF DESCRIPTION OF THE DRAWINGS

[0053] To more clearly illustrate the technical solutions of the embodiments of the present application, the following briefly introduces the drawings involved in the description of the embodiments. It should be noted that the drawings only illustrate some embodiments of the present application. Those skilled in the art can deduce other relevant drawings based on these drawings without engaging in creative work.

[0054] Figure 1 The figure is a flow chart of the overall implementation of the method of the present invention.

[0055] Figure 2 4 is a linear flow chart of the method of the present invention.

[0056] Figure 3 Schematic diagram of the interaction mode of the Vite plug-in in the method of the present invention.

[0057] Figure 4 This is an example diagram of the code generated in step 4 of the embodiment of this application.

[0058] Figure 5 This is an example diagram of the interface code generation configuration page in the method of the present invention.

[0059] Figure 6 This is an example diagram of the configuration page generated by the page code in the method of the present invention.

[0060] Figure 7 This is an example diagram of the routing configuration generated in step six of the embodiment of this application.

[0061] Figure 8 This is an example diagram of Vite plug-in integration and configuration in step seven of the embodiment of this application.

[0062] Figure 9 This is a schematic diagram of the code structure generated by the method of the present invention.

[0063] Figure 10 Generate an API method code example diagram for the method of the present invention.

[0064] Figure 11 An example diagram of a routing configuration code generated by the method of the present invention.

[0065] Figure 12 This is the overall design architecture diagram of the front-end code automatic generation system of the present invention.

[0066] Figure 13 This is a structural diagram of the device that generates front-end code based on the Swagger document for this application.

[0067] Figure 14 A schematic diagram of the structure of an electronic device provided in an embodiment of the present application. DETAILED DESCRIPTION

[0068] In order to make the purpose, technical solutions and advantages of the embodiments of the present application clearer, the technical solutions in the embodiments of the present application will be clearly and completely described below in conjunction with the drawings in the embodiments of the present application. It should be understood that the described embodiments are only some embodiments of the present application, not all embodiments. Based on the embodiments in the present application, all other embodiments obtained by ordinary technicians in this field without creative work are within the scope of protection of this application.

[0069] In this document, the term "including" and any variations thereof (such as "including," "comprising," etc.) are open-ended expressions and should be understood as meaning "including but not limited to," meaning that the listed contents are not exhaustive and may include other contents not explicitly mentioned. The term "based on" should be understood as meaning "based at least in part on," meaning that the basis or condition referred to may not be the only factor and may also involve other relevant factors. The term "one embodiment" should be understood as meaning "at least one embodiment," meaning that the described embodiment is not the only possible implementation method and that other similar embodiments may exist.

[0070] In this application, the terms "a" and "a plurality" are used to modify related elements or features in an illustrative, non-restrictive manner. Unless the context clearly indicates otherwise, "a" should be understood as meaning "at least one," and "a plurality" should be understood as meaning "at least two." Those skilled in the art should interpret these terms appropriately based on the semantics and logical relationships of the context to ensure that they encompass the possibility of "one or more."

[0071] Figure 1 The following is the overall implementation process of the method for generating front-end code based on Swagger documents provided by this application, including the following steps: S1. Get the JSON data of the Swagger document; S2 parses the JSON data of the Swagger document to extract interface information and data model information; S3. Generate the corresponding TypeScript type definition based on the parsed data model information; S4. Generate an interface call method based on the parsed interface information; S5. Generate front-end page code based on user configuration and generated TypeScript type definitions and interface call methods; S6. Generate routing configuration based on the generated front-end page code and user-configured routing rules; S7. Output all generated code files to the specified directory structure.

[0072] In order to more clearly illustrate the technical solution of the present application, the specific implementation steps of the present invention will be described in detail below with reference to an example (for example, generating a user list page, a user details page, and a user edit / add form page based on the "User Management" API defined by Swagger).

[0073] This paper aims to provide a method for automatically generating front-end code based on Swagger / OpenAPI documents. By parsing JSON data and combining it with user configuration, it automatically generates front-end request interface definitions, TypeScript type definitions, and complete page code (such as list pages, form pages, and detail pages). The entire process is integrated into the front-end engineering process and implemented as a Vite plugin, supporting real-time generation and configuration in development mode.

[0074] The core component of this invention is a Vite plug-in, which is activated when the front-end development server is started or built. The plug-in contains a Swagger document parser (SchemaParser), a code generator (TempGenerator), and a configuration management module.

[0075] Figure 2 The linear flow chart of the method of the present invention is shown, illustrating the main steps of the method from input to output. The process begins by obtaining the JSON data of the Swagger document as the data source for code generation. After obtaining the JSON data of the Swagger document, the process enters the Swagger JSON parsing step, which is completed by SchemaParser, and its output is structured interface and model information. Based on this parsed information, the process enters the critical generation phase, generating the interface TS type definition and API call method, and displaying the interface fields and types on the configuration page for user configuration. After the user configuration is completed, the system will obtain the user's configuration. Based on the type definition and API method generation, the process enters the page code generation step. The TempGenerator combines the user configuration, previously generated API methods and types, and page templates to generate complete page component code (such as list, form, and details). Finally, the generated routing configuration is executed based on the generated page components and the user-configured routing rules. All generated code files are ultimately output to the specified directory structure for use in the front-end project.

[0076] Figure 3The diagram illustrates the interaction of the Vite plugin in the present invention's method, focusing on the interaction mode within the front-end ViteDev Server development environment, specifically how users trigger code generation through the plugin. The core of this invention is the integration of the Vite plugin into the Vite Dev Server to serve front-end projects. In development mode, the Vite plugin exposes specific HTTP interfaces ( / STC / getConfig and / STC / create-page in the diagram are example interface paths) through a registered middleware. Users can initiate request routes to these interfaces through the configuration interface (which runs in the front-end project and communicates with the plugin through these interfaces). For example, the request route: / STC / getConfig triggers the plugin to initialize its internal configuration and read the existing configuration; the request route: / STC / create-page is a key trigger, receiving user configuration information about the page to be generated (e.g., the type of page to be generated, the associated API, etc.), then driving the plugin to execute the page generation process, and all generated code files are written to the file system.

[0077] The detailed implementation steps of the method of the present invention are as follows: Step 1: Get the JSON data of the Swagger document Operation: After starting the Vite development server in the project development environment, the front-end developer enters the URL of the Swagger document JSON provided by the backend (for example, http: / / backend-api.com / v2 / api-docs or http: / / backend-api.com / v3 / api-docs) through the configuration interface (which is injected into the development server by the Vite plugin via a specific URL). The Vite plugin's back-end service (a middleware) receives this URL and uses the node-fetch module to initiate an HTTP GET request to the URL to retrieve the JSON data of the Swagger document.

[0078] Example: When a user enters http: / / your-backend / v2 / api-docs?group=user-management on the configuration interface, the plug-in's backend service initiates a request to obtain the JSON content.

[0079] Step 2: Parsing JSON data Operation: After obtaining the Swagger JSON data, the Swagger document parser (SchemaParser) deeply parses the JSON data to extract interface (paths) and data model (components / definitions) information.

[0080] Implementation details: Parse the paths field: traverse the paths object and extract each interface path (such as / users), supported HTTP methods (GET, POST, PUT, DELETE, etc.), operation ID (operationId, used to generate function names), parameters (parameters, including path, query, header, cookie parameters and their schema), request body (requestBody and its content / schema), and response (responses and their content / schema).

[0081] Parse components or definitions fields: traverse these fields, extract all defined data models (Schema), and store them in a lookup table for subsequent parsing through $ref references.

[0082] Key algorithm: A multi-level JSON parsing algorithm is used, which needs to be able to recursively traverse the JSON structure, identify $ref references, and parse the referenced Schema.

[0083] For example, the parser identifies the GET method for / users / {id} and extracts the path parameter id (type integer). The response body schema is $ref: '# / components / schemas / UserDetail'. The parser also processes the GET method for / users, extracting query parameters (pageNum, pageSize, etc.) and the response body schema $ref: '# / components / schemas / UserListResult'. The parser also finds the specific definitions of # / components / schemas / UserDetail and # / components / schemas / UserListResult, including their properties and types.

[0084] Step 3: Generate TypeScript type definitions Operation: Based on the parsed data model (Schema) information, the code generator (TempGenerator) automatically generates the corresponding TypeScript interface (interface) or type alias (type alias).

[0085] Implementation details: Use the nested type recursive parsing algorithm and the TypeScript type inference algorithm to traverse the parsed Schema definition.

[0086] For basic types (string, number, boolean, integer, null), they are directly mapped to TypeScript basic types (string, number, boolean, null). Swagger integer is usually mapped to number.

[0087] For object types (type: 'object'): Generate a TypeScript interface, iterate over its properties field, recursively call the type generation logic for each property, and use the Swagger property name and the generated TypeScript type as members of the interface. Then process optional properties.

[0088] For array types (type: 'array'): parse its items field, recursively call the type generation logic for the items' Schema, generate the type of the array elements, and then use the [] symbol to represent the array type (for example, User[ ]).

[0089] For $ref references: parse the Schema definition pointed to by $ref and generate the corresponding TypeScript type, then use the type name in the reference. In addition, you need to maintain a list of generated types to avoid duplicate generation.

[0090] Organize the generated type definitions into TypeScript files, either per module (e.g. api / user-management_apiTypes.ts ) or generate a global typings file ( api / apiTypes.ts ).

[0091] Example: Based on the schema of # / components / schemas / UserDetail (for example, containing id:integer, username: string, email: string, roles: [ { id: integer, name:string} ] ), the following TypeScript code is generated: export interface Role { id?: number; name?: string; } export interface UserDetail { id?: number; username?: string; email?: string; roles?: Role [ ]; / / Handles arrays and nested objects } According to the schema of # / components / schemas / UserListResult (for example, containing total:integer, records: [ { id: integer, username: string} ]), generate: interface UserListItem { id?: number; username?: string; } export interface UserListResult { total?: number; records?: UserListItem[]; } Generate type definitions for request parameters and request body, such as parameters for user list query: export interface UserListQuery { pageNum?: number; pageSize?: number; username?: string; / / corresponds to the query field specified in the configuration } Step 4: Generate interface calling method Operation: Based on the parsed interface (paths) information, the code generator generates a TypeScript function for each generative interface to encapsulate the HTTP request logic.

[0092] Implementation details: Traverse the parsed interface information. Key algorithm: Interface parameter automatic classification technology. For each interface, identify and classify its parameters: path parameters, query parameters, request header parameters, request body. Generate an asynchronous TypeScript function for each interface. The function name can be generated based on operationId or path + method name (for example, getUserDetail, getUserList). The function parameters are generated according to the interface parameter definition. If there are many parameters or a request body, a parameter object type is usually defined (using the type generated in step three). The function body uses a preset HTTP request library (such as axios) to call the template. According to the interface definition, build a request configuration object: (url: concatenate the baseURL and the interface path. If a path parameter is included (such as / users / {id}), get the corresponding value from the function parameter to replace the {id} placeholder. method: Use the HTTP method of the interface ('get', 'post', 'put', 'delete').

[0093] params: Pass the query parameter object to the params field of axios. data: Pass the request body object to the data field of axios (mainly used for POST, PUT, and PATCH methods). headers: Process the request header parameters as needed. The return value type of the function is the response body type wrapped by the Promise (the type generated in step 3), such as Promise <userdetail>、Promise <userlistresult>. Organize the generated interface methods into TypeScript files, which can be divided into modules (for example, api / user-management.ts).

[0094] Example: Based on the definitions of / users / {id} (GET) and / users (GET), generate Figure 4 The code shown (assuming the request function encapsulated by axios is used).

[0095] Figure 5 This section shows a portion of the user-friendly visual configuration interface provided by the present invention, used to configure basic settings related to interface code generation. Interface elements include an input box for entering the API address in the Swagger document's JSON format, as well as multiple configuration options, such as whether to generate types, whether to generate the request interface TS type and definition, and whether to generate page code. Further configuration options are provided below, such as configuring the generated interface file header import, setting the request root path, selecting the request return type (Promise or Axios native type), and specifying which interfaces to include or exclude using filtering criteria (interface category or path).

[0096] Step 5: Generate front-end page code Operation: The code generator generates complete Vue page component code based on the API, page type (list, form, details), and field configuration selected by the user in the configuration interface.

[0097] Implementation details: Users select the API interface for operations such as list query, detail query, add / edit submission, and delete through the configuration interface.

[0098] For list pages, specify which interface response fields to display as table columns, the table's query items, set these fields to display / remove, field labels, and corresponding UI component types (text boxes, drop-down boxes, date pickers, etc.). For form pages and detail pages, specify which fields to display / remove, field labels, corresponding UI component types (text boxes, drop-down boxes, date pickers, etc.), validation rules, and whether fields are required.

[0099] Key algorithm: Dynamic template combination algorithm. The code generator uses predefined, configurable page templates, which are code skeletons containing placeholders. The generator reads the user configuration, combines the type definitions and interface methods generated in steps 3 and 4, and uses template function methods to populate the template with configuration data and API / type information.

[0100] List page generation: fill in table column definitions (according to the configured fields and types), bind parameters and events of the paging component, search form elements (according to the configured search fields), call the getUserList interface to obtain data, process data binding to the table, process deletion (call the deleteUser interface), and jump to the details / edit page.

[0101] Form page generation: fill in form items (according to the configured fields, component types, and validation rules), define the data model (using the UserSaveBody type generated in step 3), call the getUserDetail interface to load data (in edit mode), and call the saveUser interface to submit the form data.

[0102] Detail page generation: fill in the detail display items (according to the configured fields and types), call the getUserDetail interface to obtain data, and process the data display.

[0103] Save the generated page component code to the specified directory (for example, codes / pages / user-management / index.vue, codes / pages / user-management / form / index.vue, codes / pages / user-management / detail / index.vue) to form a modular page structure (see Figure 9 ), generate the front-end page code.

[0104] Figure 6 Another part of the configuration interface of the present invention is shown, focusing on the detailed configuration of page code generation. The interface allows users to set basic information such as page name, page route, and select key API interfaces for the page (such as query list interface, query details interface, update interface, delete interface, etc.). The core configuration of the page lies in the mapping and property setting of page fields. The figure shows four areas: "List Search Field Settings", "List Field Settings", "Form Page Field Settings" and "Details Page Field Settings". In each area, users can specify the name of the backend data field, configure whether it is displayed on the page, the type of UI component used (input box, selection box, etc.), whether it is required (for forms), and other properties specific to the list or details page.

[0105] Step 6: Generate routing configuration Operation: Automatically generate the corresponding routing configuration code based on the generated page file.

[0106] Implementation details: Create routing records for the list page, form page, and detail page. Specify the routing path, name, and corresponding component (using dynamic import to reference the generated page file).

[0107] Example: Generate user management related routing configuration in codes / router / system.ts as follows Figure 7 shown.

[0108] Step 7: Vite plugin integration and configuration Operation: Encapsulate the above parsing, generation, and configuration management logic into a Vite plug-in to seamlessly integrate it into the front-end development process.

[0109] Implementation Details: Implement the plugin function of the Vite plugin and define the necessary hook function (configureServer) within it. In the configureServer hook, register a custom HTTP middleware to receive configuration data and trigger generation requests in the development server. For example, render the configuration page when accessing / s2c, and execute code generation when a POST request is made to / stc / generate. Implement file writing functionality to write the generated code file to the specified directory. Plugin users import and use the plugin in the Vite configuration file.

[0110] Example: The implementation process in vite.config.ts is as follows Figure 8 shown.

[0111] Figure 9 This figure shows the directory and file organization of the automatically generated front-end code in the project. In this example, all generated code is concentrated in the codes / directory. The api / subdirectory stores interface-related code, such as apiTypes.ts (global types), system_apiTypes.ts (types divided by module), and system.ts (API method encapsulation). The pages / subdirectory organizes pages by business module, such as the user-management / module, which contains index.vue (list page), form.vue (form page), and detail.vue (details page). The router / subdirectory stores routing configuration, such as system.ts.

[0112] Figure 10 An example of API method code generation using the method of the present invention is shown.

[0113] Figure 11 An example of generating routing configuration code using the method of the present invention is shown.

[0114] On the other hand, the present invention provides a system for automatically generating front-end code based on Swagger / OpenAPI documents. Figure 12 The figure shows the top-level architecture of the present invention as a holistic system. The core component is a Vite plugin, which is embedded in the front-end project's development environment. The Vite plugin contains a core module, which is further broken down into SchemaParser and TempGenerator. The SchemaParser receives an external Swagger JSON document as input, which then processes and passes the parsed information to the TempGenerator. The TempGenerator also receives configuration from the user interface and generates code based on predefined templates. Its output specifically includes structured front-end code, broken down into API type definitions, page components, and routing configuration. This entire process runs on the Vite Dev Server.

[0115] Figure 13 The present invention provides a device for generating front-end code based on a Swagger document, comprising: Get module, used to get JSON data of Swagger document; A parsing module, used to parse the JSON data of the Swagger document and extract interface information and data model information; The type definition generation module is used to generate the corresponding TypeScript type definition based on the parsed data model information; The interface calling method generation module is used to generate the interface calling method according to the parsed interface information; The page code generation module is used to generate the front-end page code based on the user configuration and generated TypeScript type definition and interface call method; The routing configuration generation module is used to generate routing configuration based on the generated front-end page code and the routing rules configured by the user; The output module is used to output all generated code files to the specified directory structure.

[0116] When the above device is running, the steps of the method for generating front-end code based on Swagger document disclosed in this application are implemented.

[0117] The flowcharts and block diagrams in the accompanying drawings illustrate possible implementations of the apparatus, methods, and computer program products according to various embodiments of the present application, including architecture, functions, and operations. In these figures, each box may represent a module, a program segment, or a portion of a code, which contains one or more executable instructions for implementing a specified logical function. It should be noted that each box in the block diagram and / or flowchart, and the combination of these boxes, can be implemented using a dedicated hardware-based system to implement the specified function or operation, or can be implemented by a combination of dedicated hardware and computer instructions.

[0118] like Figure 14 As shown, an embodiment of the present application further discloses an electronic device, comprising: a processor 310, a communication interface 320, a memory 330 for storing a computer program executable by the processor, and a communication bus 340. The processor 310, the communication interface 320, and the memory 330 communicate with each other via the communication bus 340. The processor 310 executes the executable computer program to implement the steps of the above-mentioned method for generating front-end code based on a Swagger document.

[0119] It is understood that, in addition to the memory and processor, the electronic device may also include an input device (e.g., a keyboard), an output device (e.g., a display), and other communication modules. These input devices, output devices, and other communication modules all communicate with the processor via an I / O interface (i.e., an input / output interface).

[0120] The operation of the present application can be implemented by writing computer program code using one or more programming languages or a combination thereof. The programming languages include but are not limited to the following types: Object-oriented programming languages, such as Java, Smalltalk, C++, etc.; A conventional procedural programming language, such as "C" or a similar programming language.

[0121] The execution methods of the program code include but are not limited to: Executes entirely on the user's computer; Partially executed on the user's computer and partially on a remote computer; Executed as a standalone software package; Executes entirely on the remote computer or server.

[0122] In scenarios involving a remote computer, the remote computer can be connected to the user's computer via any type of network, including but not limited to a local area network (LAN) or a wide area network (WAN). Additionally, the remote computer can be connected to an external computer via an Internet service provider, such as the Internet.

[0123] Furthermore, the present application also discloses a computer-readable storage medium. When the instructions in the computer-readable storage medium are executed by a processor of an electronic device, the electronic device is enabled to perform the various steps of the method for generating front-end code based on a Swagger document disclosed in the present application.

[0124] In the context of this application, computer-readable storage media refers to tangible media that can store computer program code and related data. Specific examples include, but are not limited to, the following: (1) Portable computer disk: A removable magnetic storage medium such as a floppy disk.

[0125] (2) Hard disk: includes fixed storage devices such as mechanical hard disks and solid-state hard disks.

[0126] (3) Random Access Memory (RAM): Volatile storage medium used for temporary storage of data and program code.

[0127] (4) Read-only memory (ROM): A non-volatile storage medium used to store fixed programs and data.

[0128] (5) Erasable Programmable Read-Only Memory (EPROM) or Flash Memory: A non-volatile storage medium that supports multiple erasing and programming.

[0129] (6) Fiber optic storage device: storage medium based on fiber optic technology.

[0130] (7) Compact disk read-only memory (CD-ROM): A read-only medium that stores data in the form of an optical disc.

[0131] (8) Optical storage devices: storage media based on optical principles, such as DVDs and Blu-ray discs.

[0132] (9) Magnetic storage devices: storage media based on magnetic principles, such as magnetic tapes and disks.

[0133] (10) Any suitable combination of the above: for example, combining multiple storage media to meet different storage requirements.

[0134] These computer-readable storage media can be used to store the program code and related data described in this application to support the operation of the program and the persistent storage of data.

[0135] In particular, according to an embodiment of the present application, the process described in the flowchart can be implemented as a computer software program. For example, an embodiment of the present application relates to a computer program product, which includes a computer program carried on a non-transitory computer-readable medium. The computer program includes program code for executing the method for generating front-end code based on a Swagger document disclosed in the present application. When the computer program is executed by a processing device, the above-mentioned functions defined in the embodiments of the present application can be implemented.

[0136] Although the above discussion contains several specific implementation details, these details should not be interpreted as limiting the scope of this application. The above description is only a preferred embodiment of the present application and an illustration of the technical principles used. Those skilled in the art should understand that the scope of disclosure involved in this application is not limited to the technical solutions formed by the specific combination of the above technical features. At the same time, this application should also cover other technical solutions formed by any combination of the above technical features or their equivalent features without departing from the above disclosed concepts.

[0137] Those skilled in the art should also understand that they may modify the technical solutions described in the aforementioned embodiments, or replace some of the technical features therein with equivalents, without departing from the spirit and scope of the technical solutions of the embodiments of the present application. Such modifications or replacements will not cause the essence of the corresponding technical solutions to deviate from the core spirit and scope of the technical solutions of the embodiments of the present application.< / userlistresult> < / userdetail>

Claims

1. A method for generating front-end code based on Swagger document, characterized in that: The method comprises: Get the JSON data of the Swagger document; Parse the JSON data of the Swagger document and extract the interface information and data model information; Generate the corresponding TypeScript type definition based on the parsed data model information; Generate interface calling method based on the parsed interface information; Generate front-end page code based on user configuration and generated TypeScript type definitions and interface calling methods; Generate routing configuration based on the generated front-end page code and user-configured routing rules; Output all generated code files to the specified directory structure.

2. The method according to claim 1, characterized in that The JSON data of the Swagger document is obtained, including: The front-end developer enters the URL address of the Swagger document JSON through the configuration interface; The backend service of the Vite plugin receives the URL and uses the node-fetch module to initiate an HTTP GET request to the URL to obtain the JSON data of the Swagger document.

3. The method according to claim 1, characterized in that The JSON data of the Swagger document is parsed, including: Parse the paths field and extract each interface path, supported HTTP methods, operation ID, parameters, request body, and response; Parse the components or definitions field, extract all defined data models, and store them in a lookup table.

4. The method according to claim 1, wherein The generation of the corresponding TypeScript type definition includes: Use the nested type recursive parsing algorithm and TypeScript type inference algorithm to traverse the parsed Schema definition; For basic types, they are directly mapped to TypeScript basic types; For object types, a TypeScript interface is generated, its properties fields are iterated over, and the type generation logic is recursively called for each property; For array types, parse its items field and recursively call the type generation logic on the items' Schema to generate the type of the array elements. For ref references, parse the Schema definition pointed to by the ref and generate the corresponding TypeScript type.

5. The method according to claim 1, wherein The method for generating an interface call includes: Traverse the parsed interface information, identify and classify the parameters of each interface; Generate an asynchronous TypeScript function for each interface. The function name is generated based on operationId or path + method name. The function parameters are generated according to the interface parameter definition, and the function body uses the preset HTTP request library call template; According to the interface definition, build a request configuration object, including url, method, params, data and headers; The return value type of the function is the response body type wrapped by Promise.

6. The method according to claim 1, characterized in that The generating of the front-end page code includes: Users can select the API interface for list query, detail query, add / edit submission, and delete operations through the configuration interface; For the list page, specify which interface response fields are displayed as table columns, the table query items, set these fields to be displayed / removed, the field labels, and the corresponding UI component types; For form pages and detail pages, specify which fields to display / remove, field labels, corresponding UI component types, validation rules, and whether they are required. Use predefined, configurable page templates, combined with user configuration, generated type definitions and interface methods to generate complete Vue page component code.

7. The method according to claim 1, characterized in that The generating of the routing configuration includes: Create routing records for list pages, form pages, and detail pages, specifying the routing path, name, and corresponding components; Use dynamic import to reference the generated page file.

8. The method according to claim 1, characterized in that The method is implemented through a Vite plug-in, which is activated during the startup or build process of the front-end development server and contains a Swagger document parser, a code generator, and a configuration management module.

9. A device for generating front-end code based on Swagger document, characterized in that: The device comprises: Get module, used to get JSON data of Swagger document; A parsing module, used to parse the JSON data of the Swagger document and extract interface information and data model information; The type definition generation module is used to generate the corresponding TypeScript type definition based on the parsed data model information; The interface calling method generation module is used to generate the interface calling method according to the parsed interface information; The page code generation module is used to generate front-end page code based on user configuration and generated TypeScript type definitions and interface call methods; The routing configuration generation module is used to generate routing configuration based on the generated front-end page code and the routing rules configured by the user; The output module is used to output all generated code files to the specified directory structure.

10. An electronic device, characterized in that: include: memory and processor; Memory: used to store computer programs; Processor: used to execute the computer program to implement the steps of the method for generating front-end code based on a Swagger document as described in any one of claims 1 to 8.