Home > database >  How add page for pagination in protocol oriented networking
How add page for pagination in protocol oriented networking

Time:12-01

I just learn how to create a protocol oriented networking, but I just don't get how to add page for pagination in protocol. my setup is like this

protocol Endpoint {
    var base: String { get }
    var path: String { get }
}

extension Endpoint {
    var apiKey: String {
        return "api_key=SOME_API_KEY"
    }
    
    var urlComponents: URLComponents {
        var components = URLComponents(string: base)!
        components.path = path
        components.query = apiKey
        return components
    }
    
    var request: URLRequest {
        let url = urlComponents.url!
        return URLRequest(url: url)
    }
}

enum MovieDBResource {
    case popular
    case topRated
    case nowPlaying
    case reviews(id: Int)
}

extension MovieDBResource: Endpoint {
    var base: String {
        return "https://api.themoviedb.org"
    }
    
    var path: String {
        switch self {
        case .popular: return "/3/movie/popular"
        case .topRated: return "/3/movie/top_rated"
        case .nowPlaying: return "/3/movie/now_playing"
        case .reviews(let id): return "/3/movie/\(id)/videos"
        }
    }
}

and this is my network service class method

func getReview(movie resource: MovieDBResource, completion: @escaping (Result<MovieItem, MDBError>) -> Void) {
        print(resource.request)
        fetch(with: resource.request, decode: { (json) -> MovieItem? in
            guard let movieResults = json as? MovieItem else { return nil }
            return movieResults
        }, completion: completion)
    }

How I add page in protocol so I can called and add parameter in viewController, for now my service in my viewController is like this. I need parameter to page

service.getReview(movie: .reviews(id: movie.id)) { [weak self] results in
            guard let self = self else { return }
            switch results {
            case .success(let movies):
                print(movies)
            case .failure(let error):
                print(error)
            }
        }

Thank you

CodePudding user response:

You can add it as a parameter to your enum case like: case popular(queryParameters: [String: Any])

You can create Router class that has buildRequest(_:Endpoint), and here you can get the queryParameters and add it to the url witch will contain page and limit or any other query parameters.

you can also add another parameter for bodyParameters if the request HTTPMethod is POST and you need to send data in the body.

  • Related