• This repository has been archived on 01/Oct/2020
  • Stars
    star
    177
  • Rank 215,985 (Top 5 %)
  • Language
    Swift
  • License
    MIT License
  • Created about 9 years ago
  • Updated about 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A type-safe JSON-RPC 2.0 library purely written in Swift

JSONRPCKit

Build Status Carthage compatible CocoaPods

JSONRPCKit is a type-safe JSON-RPC 2.0 library purely written in Swift.

// Generating request JSON
let batchFactory = BatchFactory(version: "2.0", idGenerator: NumberIdGenerator())
let request = Subtract(minuend: 42, subtrahend: 23)
let batch = batchFactory.create(request)
batch.requestObject // ["jsonrpc": "2.0", "method": "subtract", "params": [42, 23], "id": 1]

// Parsing response JSON
let responseObject: Any = ["jsonrpc": "2.0", "result": 19, "id": 1]
let response = try! batch.responses(from: responseObject)
response // 19 (type of response is inferred from SubtractRequest.Response)

Requirements

  • Swift 4.0 / Xcode 9.0 or later
    • If you use Swift 3.1 (Xcode 8.3), you can use 2.0.3 instead.
  • iOS 8.0 or later
  • macOS 10.9 or later
  • watchOS 2.0 or later
  • tvOS 9.0 or later
  • Linux is also supported

Basic usage

  1. Define request type
  2. Generate request JSON
  3. Parse response JSON

Defining request type

First of all, define a request type that conforms to Request.

struct Subtract: JSONRPCKit.Request {
    typealias Response = Int

    let minuend: Int
    let subtrahend: Int

    var method: String {
        return "subtract"
    }

    var parameters: Any? {
        return [minuend, subtrahend]
    }

    func response(from resultObject: Any) throws -> Response {
        if let response = resultObject as? Response {
            return response
        } else {
            throw CastError(actualValue: resultObject, expectedType: Response.self)
        }
    }
}

Generating request JSON

To generate request JSON, pass Request instances to BatchFactory instance, which has common JSON-RPC version and identifier generator. When BatchFactory instance receives request(s), it generates identifier(s) for the request(s) and request JSON by combining id, version, method and parameters.

let batchFactory = BatchFactory(version: "2.0", idGenerator: NumberIdGenerator())
let request1 = Subtract(minuend: 42, subtrahend: 23)
let request2 = Subtract(minuend: 23, subtrahend: 42)
let batch = batchFactory.create(request1, request2)

The request JSON is available in batch.requestObject. It looks like below:

[
  {
    "method" : "subtract",
    "jsonrpc" : "2.0",
    "id" : 1,
    "params" : [
      42,
      23
    ]
  },
  {
    "method" : "subtract",
    "jsonrpc" : "2.0",
    "id" : 2,
    "params" : [
      23,
      42
    ]
  }
]

Parsing response JSON

Suppose that following JSON is returned from server:

[
  {
    "result" : 19,
    "jsonrpc" : "2.0",
    "id" : 1,
    "status" : 0
  },
  {
    "result" : -19,
    "jsonrpc" : "2.0",
    "id" : 2,
    "status" : 0
  }
]

To parse response object, execute responses(from:) of Batch instance. When responses(from:) is called, Batch finds corresponding response object by comparing request id and response id. After it find the response object, it executes responses(from:) of Response to get Request.Response from the response object.

let responseObject = ...
let (response1, response2) = try! batch.responses(from: responseObject)
print(response1) // 19
print(response2) // -19

JSON-RPC over HTTP by APIKit

APIKit is a type-safe networking abstraction layer.

Defining HTTP request type

APIKit also has RequestType that represents HTTP request.

import APIKit

struct MyServiceRequest<Batch: JSONRPCKit.Batch>: APIKit.Request {
    let batch: Batch

    typealias Response = Batch.Responses

    var baseURL: URL {
        return URL(string: "https://api.example.com/")!
    }

    var method: HTTPMethod {
        return .post
    }

    var path: String {
        return "/"
    }

    var parameters: Any? {
        return batch.requestObject
    }

    func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Response {
        return try batch.responses(from: object)
    }
}

Sending HTTP/HTTPS request

let batchFactory = BatchFactory(version: "2.0", idGenerator: NumberIdGenerator())
let request1 = Subtract(minuend: 42, subtrahend: 23)
let request2 = Subtract(minuend: 23, subtrahend: 42)
let batch = batchFactory.create(request1, request2)
let httpRequest = MyServiceRequest(batch: batch)

Session.sendRequest(httpRequest) { result in
    switch result {
    case .Success(let response1, let response2):
        print(response1.count) // CountCharactersResponse
        print(response2.count) // CountCharactersResponse

    case .Failure(let error):
        print(error)
    }
}

License

JSONRPCKit is released under the MIT License.

More Repositories

1

LEGO-Mario-Reveng

Reverse Engineering of LEGO Mario, Luigi, and Peach
113
star
2

BoostRemote

Remote Control iOS app for LEGO® BOOST
Swift
66
star
3

scratch-lego-bluetooth-extensions

Scratch 3.0 extensions for LEGO Bluetooth devices.
JavaScript
48
star
4

BoostBLEKit

Bluetooth LE protocols for LEGO® Boost in Swift
Swift
25
star
5

Scrub

Web browser app for Scratch 3.0 and Bluetooth devices
Swift
22
star
6

PresentationControllerSample

a sample of UIPresentationController
Objective-C
18
star
7

ReactKit-APIKit-Himotoki-sample

Incremental search sample created using ReactKit, APIKit and Himotoki
Swift
15
star
8

TwitterLikeProfileViewSample

a sample of Twitter-like profile view
Objective-C
15
star
9

LEGO-Hub2Hub-Communication-Hacks

LEGO MINDSTORMS Robot Inventor's Hub to Hub Communication Hacks
Python
14
star
10

Minesweeper360

Minesweeper 360 for visionOS
Swift
14
star
11

ImagePipDemo

A demonstration of Picture In Picture with generated images
Swift
13
star
12

RxTableViewSample

Reactive UITableView sample created using RxSwift and RxCocoa
Swift
11
star
13

AmiiboReader

Reading data from amiibo by using Core NFC
Swift
9
star
14

PowerFunctionPlaygroundBook

Swift Playground Book for LEGO WeDo 2.0, BOOST, and Powered Up
Swift
7
star
15

DicSample

a sample of extracting HTML string from UIReferenceLibraryViewController
7
star
16

BoostBLEKit-Showcase

Showcase of BoostBLEKit
Swift
6
star
17

HelloBeacon

iBeacon で入退室のログをとってみるテスト
Objective-C
6
star
18

SpikePlaygrounds-Swift

LEGO Education SPIKE Prime Playgrounds in Swift
Swift
5
star
19

MicrobitScratchKit

micro:bit simulation library to communicate with Scratch 3.0
Swift
4
star
20

LWPKit

Swift Package for LEGO Wireless Protocol
Swift
4
star
21

WeDoSimulator

WeDo 2.0 BLE Simulator
Swift
3
star
22

M5Stack-LEGO-BLE-Remote

LEGO BLE Remote app for M5Stack
C++
2
star
23

Joy-Con-Programming-Samples

Joy-Con programming samples in Swift
Swift
2
star
24

HBFavAction

unofficial Action extension for HBFav
Swift
2
star
25

MIDI-Servo-Control

MIDIメッセージでサーボを制御できるUSB MIDIデバイスと操作アプリ
Swift
2
star
26

DummyPlaygroundBluetooth

Dummy framework of PlaygroundBluetooth framework
Swift
2
star
27

SimpleCoreMIDIApps

Simple Core MIDI Apps
Swift
1
star
28

ScratchBrowser

Web Browser for Scratch 3.0 and BLE devices
Swift
1
star
29

SwiftWasm-WebMIDIKeyboard

Web MIDI API Keyboard built with SwiftWasm
Swift
1
star
30

LEGO-Remote-Playgrounds

Swift Playgrounds 4で動くレゴ用Bluetoothリモコン
Swift
1
star
31

lumines-js

lumines.js is a JavaScript library for programming about LUMINES
JavaScript
1
star
32

BLEDump

Swift
1
star
33

DiskSpaceEater

Swift
1
star
34

MineSweeperVR

C#
1
star
35

ScratchExtensionTest

1
star