/// 基础使用示例 /// 演示如何使用 Swagger Generator Flutter 生成基础的 API 代码 library; import 'dart:convert'; import 'dart:io'; import 'package:swagger_generator_flutter/swagger_generator_flutter.dart'; void main() async { print('🚀 基础使用示例'); print('=' * 50); try { // 1. 读取 OpenAPI 文档 print('📖 读取 OpenAPI 文档...'); final jsonString = await File('swagger.json').readAsString(); print('✅ 文档大小: ${(jsonString.length / 1024).toStringAsFixed(2)}KB'); // 2. 解析文档 print('\n🔍 解析文档...'); final document = SwaggerDocument.fromJson(jsonDecode(jsonString)); print('✅ 解析完成'); print(' - 标题: ${document.title}'); print(' - 版本: ${document.version}'); print(' - 路径数: ${document.paths.length}'); print(' - 模型数: ${document.models.length}'); // 3. 验证文档 print('\n✅ 验证文档...'); final validator = EnhancedValidator( includeWarnings: true, ); final isValid = validator.validateDocument(document); final errors = validator.errorReporter.getErrorsBySeverity(ErrorSeverity.error); final warnings = validator.errorReporter.getErrorsBySeverity(ErrorSeverity.warning); print(' - 验证结果: ${isValid ? "通过" : "失败"}'); print(' - 错误数: ${errors.length}'); print(' - 警告数: ${warnings.length}'); if (errors.isNotEmpty) { print('\n❌ 发现错误:'); for (final error in errors.take(3)) { print(' - ${error.title}: ${error.description}'); } } // 4. 生成基础 API 代码 print('\n🔧 生成基础 API 代码...'); final generator = RetrofitApiGenerator( className: 'BasicApiService', splitByTags: true, // 使用拆分模式 useRetrofit: true, generateModels: true, ); final generatedCode = generator.generateFromDocument(document); print('✅ 代码生成完成'); print(' - 代码大小: ${(generatedCode.length / 1024).toStringAsFixed(2)}KB'); print(' - 代码行数: ${generatedCode.split('\n').length}'); // 5. 保存生成的代码 print('\n💾 保存生成的代码...'); final outputDir = Directory('example/generated'); if (!outputDir.existsSync()) { outputDir.createSync(recursive: true); } final outputFile = File('example/generated/basic_api_service.dart'); await outputFile.writeAsString(generatedCode); print('✅ 代码已保存到: ${outputFile.path}'); // 6. 显示生成的代码片段 print('\n📄 生成的代码片段:'); print('-' * 30); final lines = generatedCode.split('\n'); for (int i = 0; i < 20 && i < lines.length; i++) { print('${(i + 1).toString().padLeft(2)}: ${lines[i]}'); } if (lines.length > 20) { print('... (还有 ${lines.length - 20} 行)'); } print('\n🎉 基础使用示例完成!'); } catch (e, stackTrace) { print('❌ 发生错误: $e'); print('堆栈跟踪: $stackTrace'); } } /// 创建示例 OpenAPI 文档 Future createSampleDocument() async { final sampleDoc = { 'openapi': '3.0.3', 'info': { 'title': 'Sample API', 'version': '1.0.0', 'description': 'A sample API for demonstration', }, 'servers': [ { 'url': 'https://api.example.com', 'description': 'Production server', }, ], 'paths': { '/users': { 'get': { 'summary': 'Get all users', 'operationId': 'getUsers', 'tags': ['users'], 'parameters': [ { 'name': 'page', 'in': 'query', 'required': false, 'schema': {'type': 'integer', 'default': 1}, 'description': 'Page number', }, ], 'responses': { '200': { 'description': 'Success', 'content': { 'application/json': { 'schema': { 'type': 'array', 'items': { '\$ref': '#/components/schemas/User', }, }, }, }, }, }, }, 'post': { 'summary': 'Create user', 'operationId': 'createUser', 'tags': ['users'], 'requestBody': { 'required': true, 'content': { 'application/json': { 'schema': { '\$ref': '#/components/schemas/CreateUserRequest', }, }, }, }, 'responses': { '201': { 'description': 'User created', 'content': { 'application/json': { 'schema': { '\$ref': '#/components/schemas/User', }, }, }, }, }, }, }, '/users/{id}': { 'get': { 'summary': 'Get user by ID', 'operationId': 'getUserById', 'tags': ['users'], 'parameters': [ { 'name': 'id', 'in': 'path', 'required': true, 'schema': {'type': 'integer'}, 'description': 'User ID', }, ], 'responses': { '200': { 'description': 'User found', 'content': { 'application/json': { 'schema': { '\$ref': '#/components/schemas/User', }, }, }, }, '404': { 'description': 'User not found', }, }, }, }, }, 'components': { 'schemas': { 'User': { 'type': 'object', 'properties': { 'id': {'type': 'integer', 'format': 'int64'}, 'name': {'type': 'string'}, 'email': {'type': 'string', 'format': 'email'}, 'createdAt': {'type': 'string', 'format': 'date-time'}, }, 'required': ['id', 'name', 'email'], }, 'CreateUserRequest': { 'type': 'object', 'properties': { 'name': {'type': 'string'}, 'email': {'type': 'string', 'format': 'email'}, }, 'required': ['name', 'email'], }, }, }, }; final jsonString = const JsonEncoder.withIndent(' ').convert(sampleDoc); await File('example/sample_swagger.json').writeAsString(jsonString); print('✅ 示例文档已创建: example/sample_swagger.json'); } /// 运行示例 /// /// 使用方法: /// ```bash /// dart run example/basic_usage.dart /// ``` /// /// 或者创建示例文档: /// ```dart /// await createSampleDocument(); /// ```