@lonu/stc
Version:
A tool for converting OpenApi/Swagger/Apifox into code.
3 lines (2 loc) • 5.21 kB
JavaScript
// this file is auto generated.
export default { "api_client_base": "class ApiCreateConfig {\n /// The base URL of the API endpoint.\n String baseURL;\n\n /// The timeout in milliseconds for the connection.\n Duration connectTimeout = const Duration(seconds: 5);\n\n /// The timeout in milliseconds for the response.\n Duration receiveTimeout = const Duration(seconds: 3);\n\n /// The function to call when an error occurs.\n Function(String)? onError;\n\n /// The function to call when a login is required.\n Function()? onLogin;\n\n ApiCreateConfig({required this.baseURL, this.onError, this.onLogin});\n}\n\nclass ApiClientConfig {\n /// The base URL of the API endpoint.\n String? baseURL;\n\n /// The URL of the API endpoint.\n String url;\n\n /// The HTTP method to use.\n String method;\n\n /// The parameters to send with the request.\n Map<String, dynamic>? params;\n\n /// The timeout in milliseconds for the request.\n Duration? timeout;\n\n ApiClientConfig(\n {this.baseURL,\n required this.url,\n required this.method,\n this.params,\n this.timeout});\n}\n", "dio": "import 'package:dio/dio.dart';\n\nimport '../api_client_base.dart';\n\nDio dio = Dio();\n\nvar onError;\nvar onLogin;\n\n/// 添加拦截器\nvoid addInterceptor() {\n dio.interceptors.add(InterceptorsWrapper(\n onRequest: (RequestOptions options, RequestInterceptorHandler handler) {\n /// 如果你想完成请求并返回一些自定义数据,你可以使用 `handler.resolve(response)`。\n /// 如果你想终止请求并触发一个错误,你可以使用 `handler.reject(error)`。\n return handler.next(options);\n },\n onResponse: (Response response, ResponseInterceptorHandler handler) {\n /// 如果你想终止请求并触发一个错误,你可以使用 `handler.reject(error)`。\n return handler.next(response);\n },\n onError: (DioException error, ErrorInterceptorHandler handler) {\n /// 如果你想完成请求并返回一些自定义数据,你可以使用 `handler.resolve(response)`。\n return handler.next(error);\n },\n ));\n}\n\n/// 创建一个 Dio 实例\nvoid createDio(ApiCreateConfig options) {\n dio = Dio(BaseOptions(\n baseUrl: options.baseURL,\n connectTimeout: options.connectTimeout,\n receiveTimeout: options.receiveTimeout));\n\n onError = options.onError;\n onLogin = options.onLogin;\n\n addInterceptor();\n}\n\n/// Parses the given [url] by replacing the path parameters with their corresponding values from the [pathParams] map.\n///\n/// The [url] parameter is the original URL string that may contain path parameters enclosed in curly braces.\n/// The [pathParams] parameter is a map where the keys are the path parameter names and the values are the corresponding replacement values.\n///\n/// Returns the parsed URL string with the path parameters replaced by their corresponding values.\nString parseUrl(String url, Map<String, String> pathParams) {\n if (pathParams.isEmpty) return url;\n\n var newUrl = url.replaceAllMapped(RegExp(r'[\\{|:](\\w+)[\\}]?'), (m) {\n return pathParams[m[1]] ?? '';\n });\n\n return newUrl;\n}\n\n/// Makes a request using the provided [ApiClientConfig] instance.\n///\n/// The [instance] parameter is the configuration for the request. It includes the URL, parameters, method, and callbacks.\n///\n/// Returns a [Future] that resolves to the response data of type [T].\n///\n/// Throws a [DioException] if the request fails. The exception contains the response data if available.\nFuture<T> request<T>(ApiClientConfig instance,\n [T Function(Map<String, dynamic>)? fromJson]) async {\n // Parse the URL by replacing path parameters with their corresponding values\n var url = parseUrl(instance.url, (instance.params?['path']) ?? {});\n\n if (instance.baseURL != null) {\n url = '${instance.baseURL!}$url';\n }\n\n print(url);\n\n try {\n // Make the request using Dio\n final response = await dio.request(\n url,\n queryParameters: instance.params?['query'] ?? {},\n data: instance.params?['body'] ?? {},\n options: Options(\n method: instance.method,\n headers: instance.params?['headers'] ?? {},\n receiveTimeout: instance.timeout,\n ),\n );\n\n // If the response status code is 401, call the onLogin callback\n if (response.statusCode == 401) {\n onLogin?.call();\n }\n\n // Return the response data as type T\n return fromJson != null ? fromJson(response.data) : response.data;\n } on DioException catch (e) {\n var _message = e.response?.statusMessage ?? e.message.toString();\n\n // If the response is not null and the status code is not ok, call the onError callback with the status message\n if (e.response != null && !e.response!.statusCode!.isOk) {\n onError?.call(_message);\n\n if (e.response!.statusCode == 401) {\n onLogin?.call();\n }\n }\n\n return fromJson != null\n ? fromJson({'success': false, 'message': _message})\n : {'success': false, 'message': _message} as T;\n }\n}\n\nextension on int {\n bool get isOk => this >= 200 && this < 300;\n}\n" };