diff options
| author | Andrej Mihajlov <and@mullvad.net> | 2019-05-02 15:04:30 +0200 |
|---|---|---|
| committer | Andrej Mihajlov <and@mullvad.net> | 2019-05-14 15:00:56 +0200 |
| commit | 38ed8b68dc98be0f160f891ee1f7ad5df4549bce (patch) | |
| tree | 4bd2420876c11d2c87640cb9f350d6d8a53bd155 | |
| parent | c6a8e6ddd7405a5560fee9c9651cc4a48660d460 (diff) | |
| download | mullvadvpn-38ed8b68dc98be0f160f891ee1f7ad5df4549bce.tar.xz mullvadvpn-38ed8b68dc98be0f160f891ee1f7ad5df4549bce.zip | |
Add JsonRpc helpers
| -rw-r--r-- | ios/MullvadVPN/JsonRpc.swift | 70 |
1 files changed, 70 insertions, 0 deletions
diff --git a/ios/MullvadVPN/JsonRpc.swift b/ios/MullvadVPN/JsonRpc.swift new file mode 100644 index 0000000000..887d6b67df --- /dev/null +++ b/ios/MullvadVPN/JsonRpc.swift @@ -0,0 +1,70 @@ +// +// JsonRpc.swift +// MullvadVPN +// +// Created by pronebird on 02/05/2019. +// Copyright © 2019 Amagicom AB. All rights reserved. +// + +import Foundation + +typealias JsonRpcRequestId = String +struct JsonRpcRequest<T: Encodable>: Encodable { + let version = "2.0" + let id: JsonRpcRequestId = UUID().uuidString + let method: String + let params: [T] + + fileprivate enum CodingKeys: String, CodingKey { + case version = "jsonrpc", id, method, params + } +} + +extension JsonRpcRequest where T == NoData { + init(method: String) { + self.init(method: method, params: []) + } +} + +struct NoData: Encodable {} + +class JsonRpcResponseError: Error, Decodable { + let serverErrorMessage: String + + init(serverErrorMessage: String) { + self.serverErrorMessage = serverErrorMessage + } + + var localizedDescription: String? { + return serverErrorMessage + } + + required init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + + serverErrorMessage = try container.decode(String.self) + } +} + +struct JsonRpcResponse<T: Decodable>: Decodable { + let version: String + let id: JsonRpcRequestId + let result: Result<T, JsonRpcResponseError> + + private enum CodingKeys: String, CodingKey { + case version = "jsonrpc", id, result, error + } + + init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.version = try container.decode(String.self, forKey: .version) + self.id = try container.decode(String.self, forKey: .id) + + if container.contains(.result) { + self.result = .success(try container.decode(T.self, forKey: .result)) + } else { + self.result = .failure(try container.decode(JsonRpcResponseError.self, forKey: .error)) + } + } +} |
