UNPKG

@lonu/stc

Version:

A tool for converting OpenApi/Swagger/Apifox into code.

3 lines (2 loc) 9.52 kB
// this file is auto generated. export default { "APIClient": "import Foundation\nimport Alamofire\n\n/// A client for making API requests using Alamofire.\npublic class APIClient {\n /// The shared singleton instance of the API client.\n public static let shared = APIClient()\n \n private var session: Session!\n private var baseURL: String = \"\"\n private var onError: ((String) -> Void)?\n private var onLogin: (() -> Void)?\n \n private init() {}\n \n /// Configures the API client with the specified settings.\n /// - Parameter config: The configuration object containing the settings.\n public func configure(_ config: APICreateConfig) {\n let configuration = URLSessionConfiguration.default\n configuration.timeoutIntervalForRequest = config.connectTimeout\n configuration.timeoutIntervalForResource = config.receiveTimeout\n \n session = Session(configuration: configuration)\n baseURL = config.baseURL\n onError = config.onError\n onLogin = config.onLogin\n \n addInterceptors()\n }\n \n /// Adds request and response interceptors to the session.\n private func addInterceptors() {\n let interceptor = Interceptor(adapters: [], retriers: [], interceptors: [\n CustomRequestInterceptor(),\n CustomResponseInterceptor(onError: onError, onLogin: onLogin)\n ])\n session = session.session(interceptor: interceptor)\n }\n \n /// Makes an API request with the specified configuration.\n /// - Parameters:\n /// - config: The configuration for this specific request.\n /// - type: The expected type of the response data.\n /// - Returns: A decoded instance of the specified type.\n /// - Throws: An error if the request fails or the response cannot be decoded.\n public func request<T: Decodable>(\n _ config: APIClientConfig,\n type: T.Type\n ) async throws -> T {\n let url = (config.baseURL ?? baseURL) + config.url\n let method = HTTPMethod(rawValue: config.method)\n let parameters = config.params\n let encoding: ParameterEncoding = method == .get ? URLEncoding.default : JSONEncoding.default\n \n let request = session.request(\n url,\n method: method,\n parameters: parameters,\n encoding: encoding\n )\n \n if let timeout = config.timeout {\n request.authenticate(timeout: timeout)\n }\n \n return try await withCheckedThrowingContinuation { continuation in\n request\n .validate()\n .responseDecodable(of: T.self) { response in\n switch response.result {\n case .success(let value):\n continuation.resume(returning: value)\n case .failure(let error):\n if let data = response.data,\n let errorResponse = try? JSONDecoder().decode(APIError.self, from: data) {\n self.onError?(errorResponse.message)\n } else {\n self.onError?(error.localizedDescription)\n }\n continuation.resume(throwing: error)\n }\n }\n }\n }\n}\n\n/// An interceptor that modifies outgoing requests.\nclass CustomRequestInterceptor: RequestInterceptor {\n /// Adapts the URL request before it is sent.\n /// - Parameters:\n /// - urlRequest: The request to be modified.\n /// - session: The session that created the request.\n /// - completion: A closure that takes the modified request or an error.\n func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result<URLRequest, Error>) -> Void) {\n var urlRequest = urlRequest\n // Add common headers or other request processing logic here\n completion(.success(urlRequest))\n }\n}\n\n/// An interceptor that handles responses and errors.\nclass CustomResponseInterceptor: RequestInterceptor {\n private let onError: ((String) -> Void)?\n private let onLogin: (() -> Void)?\n \n /// Creates a new response interceptor.\n /// - Parameters:\n /// - onError: A closure to handle errors.\n /// - onLogin: A closure to handle authentication requirements.\n init(onError: ((String) -> Void)? = nil, onLogin: (() -> Void)? = nil) {\n self.onError = onError\n self.onLogin = onLogin\n }\n \n /// Determines whether a failed request should be retried.\n /// - Parameters:\n /// - request: The request that failed.\n /// - session: The session that created the request.\n /// - error: The error that caused the failure.\n /// - completion: A closure that takes the retry decision.\n func retry(_ request: Request, for session: Session, dueTo error: Error, completion: @escaping (RetryResult) -> Void) {\n if let response = request.task?.response as? HTTPURLResponse {\n switch response.statusCode {\n case 401:\n onLogin?()\n default:\n break\n }\n }\n completion(.doNotRetry)\n }\n}\n\n/// A model representing an API error response.\nstruct APIError: Codable {\n /// The error message describing what went wrong.\n let message: String\n}\n", "APIClientBase": "import Foundation\n\n/// A configuration object that defines the base settings for the API client.\npublic struct APICreateConfig {\n /// The base URL for all API requests.\n let baseURL: String\n \n /// The maximum amount of time (in seconds) to wait for a connection to be established.\n let connectTimeout: TimeInterval\n \n /// The maximum amount of time (in seconds) to wait for the request to complete.\n let receiveTimeout: TimeInterval\n \n /// A closure that will be called when an error occurs.\n /// - Parameter message: The error message describing what went wrong.\n let onError: ((String) -> Void)?\n \n /// A closure that will be called when authentication is required.\n let onLogin: (() -> Void)?\n \n /// Creates a new API client configuration.\n /// - Parameters:\n /// - baseURL: The base URL for all API requests.\n /// - connectTimeout: The connection timeout in seconds. Defaults to 5 seconds.\n /// - receiveTimeout: The receive timeout in seconds. Defaults to 3 seconds.\n /// - onError: A closure to handle errors. Defaults to nil.\n /// - onLogin: A closure to handle authentication. Defaults to nil.\n public init(\n baseURL: String,\n connectTimeout: TimeInterval = 5,\n receiveTimeout: TimeInterval = 3,\n onError: ((String) -> Void)? = nil,\n onLogin: (() -> Void)? = nil\n ) {\n self.baseURL = baseURL\n self.connectTimeout = connectTimeout\n self.receiveTimeout = receiveTimeout\n self.onError = onError\n self.onLogin = onLogin\n }\n}\n\n/// A configuration object that defines the settings for a single API request.\npublic struct APIClientConfig {\n /// Optional base URL that overrides the default base URL.\n let baseURL: String?\n \n /// The endpoint path for the request.\n let url: String\n \n /// The HTTP method for the request.\n let method: String\n \n /// Optional parameters to be included in the request.\n let params: [String: Any]?\n \n /// Optional timeout that overrides the default timeout.\n let timeout: TimeInterval?\n \n /// Creates a new API request configuration.\n /// - Parameters:\n /// - baseURL: Optional base URL that overrides the default base URL.\n /// - url: The endpoint path for the request.\n /// - method: The HTTP method for the request.\n /// - params: Optional parameters to be included in the request.\n /// - timeout: Optional timeout that overrides the default timeout.\n public init(\n baseURL: String? = nil,\n url: String,\n method: String,\n params: [String: Any]? = nil,\n timeout: TimeInterval? = nil\n ) {\n self.baseURL = baseURL\n self.url = url\n self.method = method\n self.params = params\n self.timeout = timeout\n }\n}\n\n/// Extension to provide URL path parameter parsing functionality.\nextension String {\n /// Replaces path parameters in the URL string with their corresponding values.\n /// - Parameter pathParams: A dictionary of path parameter names and their values.\n /// - Returns: A URL string with all path parameters replaced with their values.\n func parsePathParams(_ pathParams: [String: String]) -> String {\n guard !pathParams.isEmpty else { return self }\n \n var result = self\n for (key, value) in pathParams {\n let pattern = \"\\\\{\" + key + \"\\\\}|:\" + key\n result = result.replacingOccurrences(\n of: pattern,\n with: value,\n options: .regularExpression\n )\n }\n return result\n }\n}\n\n/// Extension to provide HTTP status code validation.\nextension Int {\n /// Indicates whether the status code represents a successful response (2xx).\n var isOk: Bool {\n return (200...299).contains(self)\n }\n}\n" };