forked from kolyasev/SwiftJSONRPC
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCoder.swift
More file actions
58 lines (44 loc) · 1.59 KB
/
Coder.swift
File metadata and controls
58 lines (44 loc) · 1.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
//
// Coder.swift
//
//
// Created by Denis Kolyasev on 09.07.2022.
//
import Foundation
public struct Coder {
// MARK: - Initialization
public init(paramsEncoder: JSONEncoder = JSONEncoder(),
resultDecoder: JSONDecoder = JSONDecoder()) {
self.paramsEncoder = paramsEncoder
self.resultDecoder = resultDecoder
}
// MARK: - Properties
public var paramsEncoder: JSONEncoder
public var resultDecoder: JSONDecoder
// MARK: - Functions
func encode<Params: InvocationParams>(_ params: Params) throws -> Request.Params? {
guard Params.self != VoidInvocationParams.self else {
return nil
}
do {
let data = try paramsEncoder.encode(params)
return try JSONSerialization.jsonObject(with: data, options: .allowFragments)
} catch {
throw ParamsEncodingError(cause: error)
}
}
func decode<Result: InvocationResult>(_ type: Result.Type, from result: Response.Result) throws -> Result {
guard Result.self != VoidInvocationResult.self else {
return VoidInvocationResult() as! Result // swiftlint:disable:this force_cast
}
do {
let data = try JSONSerialization.data(withJSONObject: result, options: .fragmentsAllowed)
return try resultDecoder.decode(Result.self, from: data)
} catch {
throw ResultDecodingError(cause: error)
}
}
// MARK: - Inner Types
final class ParamsEncodingError: NestedError<Error> { }
final class ResultDecodingError: NestedError<Error> { }
}