Skip to content

orbstack/SwiftJSONRPC

Repository files navigation

SwiftJSONRPC

CI Status

Usage

Defining a Service

import SwiftJSONRPC
import PromiseKit

class UserService: JSONRPCService {
    func vote(rating: Int) -> Promise<Int> {
        return invoke("vote", params: ["rating": rating])
    }
    
    func create(name: String) -> Promise<UserModel> {
        return invoke("create", params: ["name": name])
    }

    // And other JSON-RPC methods
}

You can define as many services as you want depending on your requirements.

Making a Request

// Init JSON-RPC client
let url = URL(string: "http://example.com/rpc")!
let client = RPCClient(url: url)

// Init JSON-RPC service
let service = MyService(client: client)

// Perform request
service.vote(rating: 5)

Result Handling

SwiftJSONRPC uses PromiseKit to return result.

service.vote(rating: 5)
    .done { newRating in
        // Handle result
    }
    .catch { error in
        // Handle error
    }

Result Serialization

SwiftJSONRPC provides built-in result serialization for Int, String, Bool types.

Parcelable Protocol

To serialize your custom type result from JSON you can implement Parcelable protocol.

protocol Parcelable {
    init(params: [String: Any]) throws
}

For example:

struct UserModel: Parcelable {
    let id: String
    let name: String
    
    required init(params: [String: Any]) throws {
        // Parse params to struct
        // ...
    }
}

You can use libraries like ObjectMapper, MAPPER or other to adapt Parcelable protocol. Or you can adapt Swift 4 Decodable.

After that use this struct as RPCService.Result generic parameter:

class UserService: JSONRPCService {
    func create(name: String) -> Promise<UserModel> {
        return invoke("create", params: ["name": name])
    }
}
service.create(name: "testuser").done { user in
    print("User created with ID = \(user.id)")
}

Using array of Parcelable objects is also supported:

extension UserService {
    func allUsers() -> Promise<[UserModel]> {
        return invoke("all_users")
    }
}

Advanced Usage

Request Executor

Requirements

Installation

CocoaPods

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

pod "SwiftJSONRPC"

Carthage

github "kolyasev/SwiftJSONRPC"

Swift Package Manager

dependencies: [
    .package(url: "https://github.com/kolyasev/SwiftJSONRPC.git", .upToNextMajor(from: "0.7.0"))
]

ToDo

  • Add support for notification request object without an "id" member.
  • Remove Parcelable protocol and use Decodable.

Author

Denis Kolyasev, kolyasev@gmail.com

License

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

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages

  • Swift 97.4%
  • Ruby 1.5%
  • Objective-C 1.1%