-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathDatabaseDecoder.swift
462 lines (415 loc) · 20.6 KB
/
DatabaseDecoder.swift
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
/**
Copyright IBM Corporation 2018
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import SwiftKuery
import Foundation
import KituraContracts
/// Class used to construct a Model from a row in the database
open class DatabaseDecoder {
fileprivate let decoder = _DatabaseDecoder()
/// Decode from a dictionary [String: Any] to a Decodable type
open func decode<T : Decodable>(_ type: T.Type, _ values: [String : Any?], dateEncodingStrategy: DateEncodingFormat) throws -> T {
decoder.dateEncodingStrategy = dateEncodingStrategy
decoder.values = values
return try T(from: decoder)
}
fileprivate class _DatabaseDecoder : Decoder {
public var codingPath: [CodingKey]
public var userInfo: [CodingUserInfoKey:Any] = [:]
public var values = [String:Any?]()
public var dateEncodingStrategy: DateEncodingFormat = .double
fileprivate init(at codingPath: [CodingKey] = []){
self.codingPath = codingPath
}
public func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> {
return KeyedDecodingContainer<Key>(_DatabaseKeyedDecodingContainer<Key>(decoder: self, codingPath: self.codingPath))
}
public func unkeyedContainer() throws -> UnkeyedDecodingContainer {
return _UnKeyedDecodingContainer(decoder: self)
}
public func singleValueContainer() throws -> SingleValueDecodingContainer {
return _SingleValueDecodingContainer(decoder: self)
}
}
fileprivate struct _DatabaseKeyedDecodingContainer<K : CodingKey> : KeyedDecodingContainerProtocol {
typealias Key = K
private let decoder: _DatabaseDecoder
private let container: [String : Any] = [:]
public var codingPath: [CodingKey]
fileprivate init(decoder: _DatabaseDecoder, codingPath: [CodingKey]){
self.decoder = decoder
self.codingPath = codingPath
}
public var allKeys: [Key] {
return []
}
public func contains(_ key: Key) -> Bool {
return false
}
public func decodeNil(forKey key: Key) throws -> Bool {
return true
}
/// Check that value exists in the data return from the database
private func checkValueExitence(_ key: Key) throws -> Any? {
let keyName = key.stringValue
guard let value = decoder.values[keyName] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(
codingPath: [key],
debugDescription: "No value for property with this key"
))
}
return value
}
/// Unwrap value from database
private func unwrapValue(_ key: Key, _ value: Any?) throws -> Any? {
guard let unwrappedValue = value as Any? else {
throw DecodingError.valueNotFound(Any.self, DecodingError.Context(
codingPath: [key],
debugDescription: "Null value in table for non-optional property"
))
}
return unwrappedValue
}
/// Cast value from database to expect type in the model
private func castedValue<T : Any>(_ value: Any?, _ type: T.Type, _ key: Key) throws -> T {
guard let castedValue = value as? T else {
throw DecodingError.typeMismatch(type, DecodingError.Context(
codingPath: [key],
debugDescription: "Could not cast " + String(describing: value)
))
}
return castedValue
}
/// Special case for integer, no integer type in database
public func decode(_ type: Int.Type, forKey key: Key) throws -> Int {
let unwrappedValue = try unwrapValue(key, checkValueExitence(key))
let returnValue: Int
switch(unwrappedValue) {
case let v as Int16: returnValue = Int(v)
case let v as Int32: returnValue = Int(v)
case let v as Int64: returnValue = Int(v)
default:
throw DecodingError.typeMismatch(type, DecodingError.Context(
codingPath: [key],
debugDescription: "Could not convert " + String(describing: unwrappedValue)
))
}
return returnValue
}
public func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 {
let unwrappedValue = try unwrapValue(key, checkValueExitence(key))
return try castedValue(unwrappedValue, type, key)
}
public func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 {
let unwrappedValue = try unwrapValue(key, checkValueExitence(key))
return try castedValue(unwrappedValue, type, key)
}
public func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 {
let unwrappedValue = try unwrapValue(key, checkValueExitence(key))
return try castedValue(unwrappedValue, type, key)
}
public func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 {
let unwrappedValue = try unwrapValue(key, checkValueExitence(key))
return try castedValue(unwrappedValue, type, key)
}
public func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt {
let unwrappedValue = try unwrapValue(key, checkValueExitence(key))
return try castedValue(unwrappedValue, type, key)
}
public func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 {
let unwrappedValue = try unwrapValue(key, checkValueExitence(key))
return try castedValue(unwrappedValue, type, key)
}
public func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 {
let unwrappedValue = try unwrapValue(key, checkValueExitence(key))
return try castedValue(unwrappedValue, type, key)
}
public func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 {
let unwrappedValue = try unwrapValue(key, checkValueExitence(key))
return try castedValue(unwrappedValue, type, key)
}
public func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 {
let unwrappedValue = try unwrapValue(key, checkValueExitence(key))
return try castedValue(unwrappedValue, type, key)
}
public func decode(_ type: Double.Type, forKey key: Key) throws -> Double {
let unwrappedValue = try unwrapValue(key, checkValueExitence(key))
return try castedValue(unwrappedValue, type, key)
}
public func decode(_ type: Float.Type, forKey key: Key) throws -> Float {
let unwrappedValue = try unwrapValue(key, checkValueExitence(key))
return try castedValue(unwrappedValue, type, key)
}
public func decode(_ type: String.Type, forKey key: Key) throws -> String {
let unwrappedValue = try unwrapValue(key, checkValueExitence(key))
return try castedValue(unwrappedValue, type, key)
}
public func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool {
let unwrappedValue = try unwrapValue(key, checkValueExitence(key))
return try castedValue(unwrappedValue, type, key)
}
public func decode<T : Decodable>(_ type: T.Type, forKey key: Key) throws -> T {
let value = try checkValueExitence(key)
if type is Data.Type && value != nil {
let castValue = try castedValue(value, String.self, key)
guard let data = Data(base64Encoded: castValue) else {
throw RequestError(.ormCodableDecodingError, reason: "Error decoding value of Data Type for Key: \(String(describing: key)) , value: \(String(describing: value)) is not base64encoded")
}
return try castedValue(data, type, key)
} else if type is URL.Type && value != nil {
let castValue = try castedValue(value, String.self, key)
let url = URL(string: castValue)
return try castedValue(url, type, key)
} else if type is UUID.Type && value != nil {
let castValue = try castedValue(value, String.self, key)
let uuid = UUID(uuidString: castValue)
return try castedValue(uuid, type, key)
} else if type is Date.Type && value != nil {
switch decoder.dateEncodingStrategy {
case .double:
let castValue = try castedValue(value, Double.self, key)
let date = Date(timeIntervalSinceReferenceDate: castValue)
return try castedValue(date, type, key)
case .timestamp:
if let dateValue = value as? Date {
return try castedValue(dateValue, type.self, key)
} else {
let castValue = try castedValue(value, String.self, key)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let date = dateFormatter.date(from: castValue)
return try castedValue(date, type.self, key)
}
case .date:
if let dateValue = value as? Date {
return try castedValue(dateValue, type.self, key)
} else {
let castValue = try castedValue(value, String.self, key)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let date = dateFormatter.date(from: castValue)
return try castedValue(date, type.self, key)
}
case .time:
if let dateValue = value as? Date {
return try castedValue(dateValue, type.self, key)
} else {
let castValue = try castedValue(value, String.self, key)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm:ss"
let date = dateFormatter.date(from: castValue)
return try castedValue(date, type.self, key)
}
}
} else {
throw RequestError(.ormDatabaseDecodingError, reason: "Unsupported type: \(String(describing: type)) for value: \(String(describing: value))")
}
}
public func decodeIfPresent(_ type: Int.Type, forKey key: Key) throws -> Int? {
let value = try checkValueExitence(key)
if value == nil { return nil}
let returnValue: Int
switch(value){
case let v as Int16: returnValue = Int(v)
case let v as Int32: returnValue = Int(v)
case let v as Int64: returnValue = Int(v)
default:
throw DecodingError.typeMismatch(type, DecodingError.Context(
codingPath: [key],
debugDescription: "Could not convert " + String(describing: value)
))
}
return returnValue
}
public func decodeIfPresent(_ type: Int8.Type, forKey key: Key) throws -> Int8? {
let value = try checkValueExitence(key)
if value == nil {return nil}
return try castedValue(value, type, key)
}
public func decodeIfPresent(_ type: Int16.Type, forKey key: Key) throws -> Int16? {
let value = try checkValueExitence(key)
if value == nil {return nil}
return try castedValue(value, type, key)
}
public func decodeIfPresent(_ type: Int32.Type, forKey key: Key) throws -> Int32? {
let value = try checkValueExitence(key)
if value == nil {return nil}
return try castedValue(value, type, key)
}
public func decodeIfPresent(_ type: Int64.Type, forKey key: Key) throws -> Int64? {
let value = try checkValueExitence(key)
if value == nil {return nil}
return try castedValue(value, type, key)
}
public func decodeIfPresent(_ type: UInt.Type, forKey key: Key) throws -> UInt? {
let value = try checkValueExitence(key)
if value == nil {return nil}
return try castedValue(value, type, key)
}
public func decodeIfPresent(_ type: UInt8.Type, forKey key: Key) throws -> UInt8? {
let value = try checkValueExitence(key)
if value == nil {return nil}
return try castedValue(value, type, key)
}
public func decodeIfPresent(_ type: UInt16.Type, forKey key: Key) throws -> UInt16? {
let value = try checkValueExitence(key)
if value == nil {return nil}
return try castedValue(value, type, key)
}
public func decodeIfPresent(_ type: UInt32.Type, forKey key: Key) throws -> UInt32? {
let value = try checkValueExitence(key)
if value == nil {return nil}
return try castedValue(value, type, key)
}
public func decodeIfPresent(_ type: UInt64.Type, forKey key: Key) throws -> UInt64? {
let value = try checkValueExitence(key)
if value == nil {return nil}
return try castedValue(value, type, key)
}
public func decodeIfPresent(_ type: Double.Type, forKey key: Key) throws -> Double? {
let value = try checkValueExitence(key)
if value == nil {return nil}
return try castedValue(value, type, key)
}
public func decodeIfPresent(_ type: Float.Type, forKey key: Key) throws -> Float? {
let value = try checkValueExitence(key)
if value == nil {return nil}
return try castedValue(value, type, key)
}
public func decodeIfPresent(_ type: String.Type, forKey key: Key) throws -> String? {
let value = try checkValueExitence(key)
if value == nil {return nil}
return try castedValue(value, type, key)
}
public func decodeIfPresent(_ type: Bool.Type, forKey key: Key) throws -> Bool? {
let value = try checkValueExitence(key)
if value == nil {return nil}
return try castedValue(value, type, key)
}
public func decodeIfPresent<T : Decodable>(_ type: T.Type, forKey key: Key) throws -> T? {
let value = try checkValueExitence(key)
if value == nil {return nil}
if type is Data.Type {
let castValue = try castedValue(value, String.self, key)
guard let data = Data(base64Encoded: castValue) else {
throw RequestError(.ormCodableDecodingError, reason: "Error decoding value of Data Type for Key: \(String(describing: key)) , value: \(String(describing: value)) is not base64encoded")
}
return data as? T
} else if type is URL.Type {
let castValue = try castedValue(value, String.self, key)
let url = URL(string: castValue)
return try castedValue(url, type, key)
} else if type is UUID.Type {
let castValue = try castedValue(value, String.self, key)
let uuid = UUID(uuidString: castValue)
return try castedValue(uuid, type, key)
} else if type is Date.Type {
switch decoder.dateEncodingStrategy {
case .double:
let castValue = try castedValue(value, Double.self, key)
let date = Date(timeIntervalSinceReferenceDate: castValue)
return try castedValue(date, type, key)
case .timestamp:
if let dateValue = value as? Date {
return try castedValue(dateValue, type.self, key)
} else {
let castValue = try castedValue(value, String.self, key)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let date = dateFormatter.date(from: castValue)
return try castedValue(date, type.self, key)
}
case .date:
if let dateValue = value as? Date {
return try castedValue(dateValue, type.self, key)
} else {
let castValue = try castedValue(value, String.self, key)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let date = dateFormatter.date(from: castValue)
return try castedValue(date, type.self, key)
}
case .time:
if let dateValue = value as? Date {
return try castedValue(dateValue, type.self, key)
} else {
let castValue = try castedValue(value, String.self, key)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm:ss"
let date = dateFormatter.date(from: castValue)
return try castedValue(date, type.self, key)
}
}
} else {
throw RequestError(.ormDatabaseDecodingError, reason: "Unsupported type: \(String(describing: type)) for value: \(String(describing: value))")
}
}
public func nestedContainer<NestedKey>(keyedBy: NestedKey.Type, forKey: Key) throws -> KeyedDecodingContainer<NestedKey> {
return KeyedDecodingContainer<NestedKey>(_DatabaseKeyedDecodingContainer<NestedKey>(decoder: decoder, codingPath: codingPath))
}
public func nestedUnkeyedContainer(forKey: Key) throws -> UnkeyedDecodingContainer {
return _UnKeyedDecodingContainer(decoder: decoder)
}
public func superDecoder() throws -> Decoder {
return decoder
}
public func superDecoder(forKey: Key) throws -> Decoder {
return decoder
}
}
fileprivate class _SingleValueDecodingContainer : SingleValueDecodingContainer {
var codingPath: [CodingKey] {
return []
}
var decoder: _DatabaseDecoder
fileprivate init(decoder: _DatabaseDecoder){
self.decoder = decoder
}
public func decodeNil() -> Bool {
return true
}
public func decode<T: Decodable>(_ type: T.Type) throws -> T {
let child = _DatabaseDecoder()
let result = try T(from: child)
return result
}
}
fileprivate class _UnKeyedDecodingContainer: UnkeyedDecodingContainer {
var codingPath: [CodingKey] {
return decoder.codingPath
}
public var count: Int? {
return 1
}
var isAtEnd: Bool = true
public var currentIndex: Int = 0
private let decoder: _DatabaseDecoder
fileprivate init(decoder: _DatabaseDecoder){
self.decoder = decoder
}
public func decodeNil() -> Bool {
return true
}
public func decode<T: Decodable>(_ type: T.Type) throws -> T {
return try T(from: decoder)
}
public func nestedContainer<NestedKey>(keyedBy: NestedKey.Type) throws -> KeyedDecodingContainer<NestedKey> {
return KeyedDecodingContainer<NestedKey>(_DatabaseKeyedDecodingContainer<NestedKey>(decoder: decoder, codingPath: codingPath))
}
public func nestedUnkeyedContainer() throws -> UnkeyedDecodingContainer {
return self
}
public func superDecoder() throws -> Decoder {
return decoder
}
}
}