Giter Site home page Giter Site logo

rxrestclient's Introduction

RxRestClient

CI Status Version License Platform

Example

To run the example project, clone the repo, and run pod install from the Example directory first.

Requirements

  • iOS 10.0+
  • Swift 5.1+
  • Xcode 11+

Migration Guides

Installation

RxRestClient is available through CocoaPods. To install it, simply add the following line to your Podfile:

pod 'RxRestClient'

Features

  • Simple way to do requests
  • Simple way to have response state in reactive way
  • Ability to customization
  • Retry on any error
  • Handle network reachability status
  • Retry on become reachable
  • Ability to use absolute and relative urls
  • Swift Codable protocol support
  • Use custom SessionManager
  • Pagination support
  • more coming soon

How to use

First of all you need to create struct of your response state and implement ResponseState protocol.

struct RepositoriesState: ResponseState {

    typealias Body = Data

    var state: BaseState?
    var data: [Repository]?

    private init() {
        state = nil
    }

    init(state: BaseState) {
        self.state = state
    }

    init(response: (HTTPURLResponse, Data?)) {
        if response.0.statusCode == 200, let body = response.1 {
            self.data = try? JSONDecoder().decode(RepositoryResponse.self, from: body).items
        }
    }

    static let empty = RepositoriesState()
}

It is required to mention expected Body type (String or Data).

After that you need to create request model:

struct RepositoryQuery: Encodable {
    let q: String
}

Then you can do the request to get repositories:

import RxSwift
import RxRestClient

protocol RepositoriesServiceProtocol {
    func get(query: RepositoryQuery) -> Observable<RepositoriesState>
}

final class RepositoriesService: RepositoriesServiceProtocol {

    private let client = RxRestClient()

    func get(query: RepositoryQuery) -> Observable<RepositoriesState> {
        return client.get("https://api.github.com/search/repositories", query: query)
    }
}

In order to customize client you can use RxRestClientOptions:

var options = RxRestClientOptions.default
options.addHeader(key: "x-apikey", value: "<API_KEY>")
client = RxRestClient(baseUrl: <BASE _URL>), options: options)

Relative vs absolute url

In order to use relative url you need to give <BASE_URL> when initializing client object.

let client = RxRestClient(baseURL: <BASE_URL>)

When calling any request you can provide either String endpoint or absolute URL. If you will String it will be appended to baseURL.

client.get("rest/contacts")

If baseURL is nil then it will try to convert provided String to URL.

In order to use absolute url even when your client has baseURL you can provide URL like this:

if let url = URL(string: "https://api.github.com/search/repositories") {
    client.get(url: url, query: ["q": search])
}

Pagination

Pagination support is working only for GET requests. In order to have pagination (or infinite scrolling) feature you need to implement following protocols for query and response models:

For query model you need to implement PagingQueryProtocol:

struct RepositoryQuery: PagingQueryProtocol {

    let q: String
    var page: Int

    init(q: String) {
        self.q = q
        self.page = 1
    }

    func nextPage() -> RepositoryQuery {
        var new = self
        new.page += 1
        return new
    }
}

For response model you need to implement PagingResponseProtocol:

struct RepositoryResponse: PagingResponseProtocol {
    let totalCount: Int
    var repositories: [Repository]

    private enum CodingKeys: String, CodingKey {
        case totalCount = "total_count"
        case repositories = "items"
    }

    // MARK: - PagingResponseProtocol
    typealias Item = Repository

    static var decoder: JSONDecoder {
        return .init()
    }

    var canLoadMore: Bool {
        return totalCount > items.count
    }

    var items: [Repository] {
        get {
            return repositories
        }
        set(newValue) {
            repositories = newValue
        }
    }

}

For response states you need to use PagingState class or custom subclass:

final class RepositoriesState: PagingState<RepositoryResponse> {
    ...
}

After having all necessary models you can do your request:

client.get("https://api.github.com/search/repositories", query: query, loadNextPageTrigger: loadNextPageTrigger)

loadNextPageTrigger is an Observable with Void type in order to trigger client to do request for next page using new query model generated using nextPage() function.

Author

Tigran Hambardzumyan, [email protected]

Support

Feel free to open issues with any suggestions, bug reports, feature requests, questions.

Let us know!

We’d be really happy if you sent us links to your projects where you use our component. Just send an email to [email protected] and do let us know if you have any questions or suggestion.

License

RxRestClient is available under the MIT license. See the LICENSE file for more info.

rxrestclient's People

Contributors

aramsemerjyan avatar hamtiko avatar hovaks avatar mobilebugcreator avatar stdevteam avatar tigran-stdev avatar yersar avatar yervandsar avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.