Git Product home page Git Product logo

requestkit's Introduction

RequestKit

Build Status codecov.io

The base of octokit.swift, TanukiKit, TrashCanKit and VloggerKit.

Installation

Carthage

# Cartfile
github "nerdishbynature/RequestKit"

CocoaPods

# Podfile
pod "NBNRequestKit"

Usage

To make a request using RequestKit you will need three parts: a Router, a Configuration and usually an object that know both and connects them. See OctoKit.

Defining a Router

Router are defined by the Router protocol. It is recommended to define them as Enumerations having a case for every route.

This is what a basic router looks like:

enum MyRouter: Router {
    case getMyself(Configuration)

    var configuration: Configuration {
        switch self {
        case .getMyself(let config): return config
        }
    }

    var method: HTTPMethod {
        switch self {
        case .getMyself:
            return .GET
        }
    }

    var encoding: HTTPEncoding {
        switch self {
        case .getMyself:
            return .url
        }
    }

    var path: String {
        switch self {
        case .getMyself:
            return "myself"
        }
    }

    var params: [String: Any] {
        switch self {
        case .getMyself(_):
            return ["key1": "value1", "key2": "value2"]
        }
    }
}

Defining a Configuration

As RequestKit was designed to handle OAuth requests we needed something to store user credentials. This is where Configurations come into play. Configurations are defined in the Configuration protocol.

public struct TokenConfiguration: Configuration {
    public let accessToken: String?
    public let apiEndpoint = "https://my.webservice.example/api/2.0/"
    public let accessTokenFieldName = "access_token"
    public let errorDomain = "com.my.customErrorDomain"
    
    public init(_ accessToken: String? = nil) {
        self.accessToken = accessToken
    }
}

In the above Configuration the accessToken will be passed as a URL parameter named access_token with each request. Alternatively you can have the accessToken passed in an HTTP Authorization header by setting the authorizationHeader property to the desired token type. As an example the following Configuration passes it as a Bearer token.

public struct TokenConfiguration: Configuration {
    public let accessToken: String?
    public let apiEndpoint = "https://my.webservice.example/api/2.0/"
    public let authorizationHeader: String? = "Bearer"
    public let errorDomain = "com.my.customErrorDomain"
        
    public init(_ accessToken: String? = nil) {
        self.accessToken = accessToken
    }
}

Defining the binding object

We will need something that connects the router and the configuration to make provide a convenient interface. The common way of doing this is to use a struct or a class that does it for you.

struct User : Codable {
}

struct MyWebservice {
    var configuration: Configuration

    init(configuration: Configuration) {
        self.configuration = configuration
    }

    func getMyself(session: RequestKitURLSession = URLSession.shared, completion: @escaping (_ response: Response<User>) -> Void) -> URLSessionDataTaskProtocol? {
        let router = MyRouter.getMyself(self.configuration)
        return router.load(session, expectedResultType: User.self) { user, error in
            if let error = error {
                completion(Response.failure(error))
            } else if let user = user {
                completion(Response.success(user))
            }
        }
    }
}

Making a request

All your user has to do is call your MyWebservice:

let config = TokenConfiguration("123456")
MyWebservice(configuration:config).getMyself { response in
    switch response {
        case .success(let user):
            print(user)
        case .failure(let error):
            print(error)
        }
    }
}

requestkit's People

Contributors

pietbrauer avatar mpvosseller avatar nwest avatar tiferrei avatar 1ec5 avatar

Watchers

James Cloos avatar BTX avatar  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.