doc2ts
v1.4.4
Published
根据接口文档生成ts接口文件
Downloads
318
Maintainers
Readme
doc2ts - Build API Request Tools
📖 中文文档 | English Documentation
😉 Generate request tools from Swagger documentation (TypeScript or JavaScript)
😉 Achieve interface definitions, parameter descriptions, parameter organization, and return data type definitions with just one command - freeing your hands and increasing productivity
😉 Flexible configuration without interfering with the request process
😉 Use git to manage generated code without fear of modifications
Quick Start
Installation
npm i -D doc2ts
npm i qsModule Support
doc2ts supports both CommonJS and ES Modules:
- CommonJS (default):
const { Doc2Ts } = require('doc2ts') - ES Modules:
import { Doc2Ts } from 'doc2ts'
The package automatically detects the module system and provides the appropriate format.
Configure Project Scripts
Add the following script commands to package.json:
{
"scripts": {
// ...
"api": "doc2ts start",
"api-git": "doc2ts start --git",
}
}Initialize Configuration
# Follow the prompts to select your configuration
npx doc2ts init- After entering the command, press Enter for all prompts to generate a sample configuration.
- If you select
Generate base class file, a.tsfile will be generated at the corresponding location. This file must export a base class that implements theIApiClientinterface. - After completing this command, a
doc2ts-config.tsfile will be generated in the project root directory. This file must export aDoc2TsConfigtype object. For detailed configuration information, please see Doc2TsConfig Configuration.
Generate Files
npm run apiUsing Git to Manage Generated Code
Valid for version v0.9.1 and above
Each time code is generated, it will overwrite the previous code. Often, you need to manually modify the generated code (interface documentation is not 100% accurate), and you can use git branches to manage this. Automatic workflow: Copy current branch configuration file (doc2ts-config.ts) -> Switch to doc2ts branch -> Update doc2ts branch code -> Generate code -> Commit -> Submit doc2ts branch code -> Switch back to original branch -> Merge doc2ts branch.
npm run api-gitBase Class File Description
The base class file must export a
data request class. Thisclassmust implement theIApiClientinterface, which means adding arequestmethod. Each interface will pass organized parameters to therequestmethod, so you need to implement the request process (axios, fetch, ajax...) in therequestmethod yourself.
request Method Parameter Description
The request method receives a DocReqConfig type object. Detailed description is as follows:
| Key | Type | Required | Description | | -------- | ------------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------- | | url | String | Yes | Interface request address (without BaseURL) | | method | Method | Yes | Request method | | body | Object | No | Request body, defined according to interface input parameters | | formData | FormData | No | Packaged FormData request parameters, defined according to interface input parameters | | headers | Object | No | Headers request parameters, defined according to interface input parameters | | config | Object | No | Custom interface parameters, see Custom Interface Configuration Parameters for details |
Doc2TsConfig Configuration
By modifying the configuration information in doc2ts-config.ts, you can control the content of the final generated files. This configuration file must export a Doc2TsConfig type object.
Usage suggestion: Do not modify the content in generated files. Try to control the generation of new file content by modifying configuration information, as each generation will overwrite the old file content.
Interface Documentation Address (origins)
- Parameter:
origins - Required:
Yes - Type:
(Origin | ApifoxConfig)[] - Default:
- - Description: Configure Swagger/Apifox interface information address
Origin Type Description:
| Key | Type | Required | Description | | ----- | ----- | ----- | ----- | | url | String | Yes | Swagger interface information address, consistent with example address, can also be JS file address | | version | String | No | Swagger version | | name | String | No | Module name | | requestName | String | No | Interface request method (default: request) | | downloadName | String | No | File download method (default: download) |
ApifoxConfig Type Description:
| Key | Type | Required | Description | | ----- | ----- | ----- | ----- | | sharedId | String | Yes | Apifox shared ID | | name | String | No | Module name | | requestName | String | No | Interface request method (default: request) | | downloadName | String | No | File download method (default: download) |
export default {
origins: [
{ name: 'swagger-api', url: 'https://petstore.swagger.io/v2/swagger.json' },
{ name: 'apifox-api', sharedId: 'shared-xxxxx', requestName: 'fetch' }
]
} as Doc2TsConfigSwagger Authentication Headers (swaggerHeaders)
- Parameter:
swaggerHeaders - Required:
No - Type:
Record<string, any> - Default:
- - Description: If Swagger documentation requires authentication, you can add headers information when requesting documentation data
export default {
swaggerHeaders: {
Authorization: 'Bearer token',
cookie: 'session=xxx'
}
} as Doc2TsConfigCustom Swagger Data Request Method (fetchSwaggerDataMethod)
- Parameter:
fetchSwaggerDataMethod - Required:
No - Type:
(url: string) => Promise<string> - Default:
- - Description: Custom method to get Swagger data, suitable for scenarios requiring special authentication
export default {
async fetchSwaggerDataMethod(url) {
const response = await fetch(url, {
headers: { Authorization: 'Bearer token' }
})
return response.text()
}
} as Doc2TsConfigModule Filter (filterModule)
- Parameter:
filterModule - Required:
No - Type:
(i: PathInfo) => boolean - Default:
- - Description: Filter out modules that don't need to be generated
export default {
filterModule(item) {
// Only generate user and order modules
return ['user', 'order'].includes(item.moduleName)
}
} as Doc2TsConfigGit Configuration (gitConfig)
- Parameter:
gitConfig - Required:
No - Type:
GitConfig - Default:
- - Description: Automatic git management configuration
export default {
gitConfig: {
remote: 'origin',
branchname: 'doc2ts'
}
} as Doc2TsConfigUse operationId as Method Name (useOperationId)
- Parameter:
useOperationId - Required:
No - Type:
boolean - Default:
true - Description: Whether to use operationId as method name, use request path as method name when false
export default {
useOperationId: false // Use request path as method name
} as Doc2TsConfigFile Output Directory (outDir)
- Parameter:
outDir - Required:
Yes - Type:
string - Default:
- - Description: Output directory for generated files
export default {
outDir: './src/services'
} as Doc2TsConfigBase Class Name (baseClassName)
- Parameter:
baseClassName - Required:
No - Type:
string - Default:
ApiClient - Description: Base class name that each module inherits from, the base class must implement the
IApiClientinterface
export default {
baseClassName: 'MyApiClient' // Or {MyApiClient} if using export
} as Doc2TsConfigLanguage Type (languageType)
- Parameter:
languageType - Required:
No - Type:
'typeScript' | 'javaScript' | 'typescript' | 'javascript' | 'ts' | 'js' - Default:
'typeScript' - Description: Generate TypeScript or JavaScript files
export default {
languageType: 'typeScript' // Or 'js', 'javascript', etc.
} as Doc2TsConfigTranslation Type (translateType)
- Parameter:
translateType - Required:
No - Type:
TranslateType - Default:
TranslateType.none - Description: Translation type configuration for controlling code generation translation behavior
export default {
translateType: TranslateType.none // TranslateType.pinyin, TranslateType.english
} as Doc2TsConfigArrow Function Mode (arrowFunc)
- Parameter:
arrowFunc - Required:
No - Type:
boolean - Default:
false - Description: Whether to use arrow function mode to generate interface methods
export default {
arrowFunc: true // Use arrow functions: method = () => {}
} as Doc2TsConfigKeep TS Files (emitTs)
- Parameter:
emitTs - Required:
No - Type:
boolean - Default:
false - Description: Whether to keep TypeScript source files in JavaScript mode
export default {
emitTs: true // Only valid when languageType is 'js'
} as Doc2TsConfigGenerate Declaration Files (declaration)
- Parameter:
declaration - Required:
No - Type:
boolean - Default:
true - Description: Whether to generate
.d.tsdeclaration files in JavaScript mode
export default {
declaration: true // Generate corresponding .d.ts files
} as Doc2TsConfigBase Class Path (baseClassPath)
- Parameter:
baseClassPath - Required:
Yes - Type:
string - Default:
- - Description: Path to the base class file
export default {
baseClassPath: './src/services/client.ts'
} as Doc2TsConfigPrettier Configuration Path (prettierPath)
- Parameter:
prettierPath - Required:
No - Type:
string - Default:
- - Description: Prettier configuration file path (deprecated)
export default {
prettierPath: './.prettierrc.js'
} as Doc2TsConfigDisable Parameters (disableParams)
- Parameter:
disableParams - Required:
No - Type:
DisableParams[] - Default:
- - Description: Remove prompts for certain globally configured input parameters
export default {
disableParams: [
{ paramType: 'header', keys: ['token', 'Authorization'] }
]
} as Doc2TsConfigReturn Type Rendering (resultTypeRender)
- Parameter:
resultTypeRender - Required:
No - Type:
string | ((funcName: string, typeInfo?: TypeInfoBase) => string) - Default:
- - Description: Customize interface return data type
// Function approach
export default {
resultTypeRender(funcName, typeInfo) {
if (typeInfo) return `Promise<[any, ${typeInfo.typeName}['data'], ${typeInfo.typeName}]>`
return 'Promise<any>'
}
} as Doc2TsConfig
// String template approach
export default {
resultTypeRender: '[any, {typeName}["data"], {typeName}]'
} as Doc2TsConfigHook Before Generating Interface Files (render)
- Parameter:
render - Required:
No - Type:
(content: string, moduleName?: string) => string - Default:
- - Description: Hook before generating interface files, used to modify generated content
export default {
render(content, moduleName) {
// Custom processing of generated file content
return content.replace(/somePattern/g, 'replacement')
}
} as Doc2TsConfigHook Before Generating Interface Type Files (typeFileRender)
- Parameter:
typeFileRender - Required:
No - Type:
(content: string, modelName: string) => string - Default:
- - Description: Hook before generating interface type files, used to modify generated content
export default {
typeFileRender(content, modelName) {
// Custom processing of generated type file content
return content + '\n// Custom comment'
}
} as Doc2TsConfigCallback Function Before Generating Types (generateTypeRender)
- Parameter:
generateTypeRender - Required:
No - Type:
(typeName: string, typeInfo: TypeInfoBase) => TypeInfoBase - Default:
- - Description: Callback function before generating types, used to modify type definitions
export default {
generateTypeRender(typeName, typeInfo) {
// Make all fields of a type required
if (typeName === 'User') {
typeInfo.typeItems.forEach(item => {
item.required = true
})
}
return typeInfo
}
} as Doc2TsConfigPost-Generation Script (postRender)
- Parameter:
postRender - Required:
No - Type:
string - Default:
- - Description: Script to execute after code generation, useful for formatting code or other post-processing tasks
export default {
postRender: 'npm run format && npm run lint'
} as Doc2TsConfig