DEV Community

Harsh Prajapat
Harsh Prajapat

Posted on

aync call

import Foundation
import SwiftUI
import Combine

struct Post: Codable, Identifiable {
    let id: Int
    let msg: String
}

enum APIError: LocalizedError {
    case invalidURL
    case invalidResponse
    case decodingFailed

    var errorMsg: String? {
        switch self {
        case .invalidURL:
            return ""
        case .invalidResponse:
            return ""
        case .decodingFailed:
            return ""
        }
    }
}

protocol APIServiceProtocol {
    func fetchPost() async throws -> [Post]
}

final class APIService: APIServiceProtocol {

    func fetchPost() async throws -> [Post] {

        guard let url = URL(string: "") else {
            throw APIError.invalidURL
        }

        let (data, res) = try await URLSession.shared.data(from: url)

        guard let res = res as? HTTPURLResponse, res.statusCode == 200 else {
            throw APIError.invalidResponse
        }

        do {
            return try JSONDecoder().decode([Post].self, from: data)
        } catch {
            throw APIError.decodingFailed
        }
    }
}

protocol PostRepositoryProtocol {
    func fetchPost() async throws -> [Post]
}

final class PostRepository: PostRepositoryProtocol {

    private let apiService: APIServiceProtocol

    init(apiService: APIServiceProtocol) {
        self.apiService = apiService
    }

    func fetchPost() async throws -> [Post] {
        try await apiService.fetchPost()
    }
}

// test

protocol Storage {
    func save(_ item: String)
}

struct UserStorage: Storage {
    func save(_ item: String) {

    }
}

protocol Work {

    associatedtype Item

    func save(_ item: Item)
}

struct WorkStorage: Work {
    func save(_ item: User) {

    }
    typealias Item = User
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)