-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathDataSnapshotDecoder.swift
More file actions
596 lines (449 loc) · 23.3 KB
/
DataSnapshotDecoder.swift
File metadata and controls
596 lines (449 loc) · 23.3 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
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
/* DataSnapshotDecoder.swift
Copyright 2018 MindSea Development Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import FirebaseDatabase
import Foundation
/**
Decodes Firebase Realtime Database snapshots into `Swift.Decodable` values.
Example:
````
struct CoolData: Decodable {
let hasBindle: Bool
let interestingItemCount: Int
}
Database.database().reference(withPath: "/cools").observe(.value, with: { snapshot in
do {
let cools = try DataSnapshotDecoder().decode([CoolData].self, from: snapshot)
print("decoded cools! \(cools)")
} catch {
print("couldn't decode snapshot: \(error)")
}
}
````
## Special keys
`DataSnapshotDecoder` has two special keys:
- `.key` maps to the Firebase Realtime Database object's key.
- `.priority` maps to the Firebase Realtime Database object's priority.
The annoying part is we can't rely on the Swift compiler's autogenerated `CodingKey` if we want the key and/or priority to be decoded; you'll have to specify your own `CodingKey`.
Example:
````
struct CoolKeyedData: Decodable {
let coconutCount: Int
let key: String
private enum CodingKeys: String, CodingKey {
case coconutCount
case key = ".key"
}
}
// later, assuming you're in some observe block…
let coolKeyed = try DataSnapshotDecoder().decode(CoolKeyedData.self, from: snapshot)
print("key is \(coolKeyed.key)") // prints something useful
````
Note that Firebase Realtime Database keys are not allowed to contain a period `.`, so you can't set a value in your database that gets shadowed by these special keys.
*/
public final class DataSnapshotDecoder {
// JSONDecoder has this weird interface with a pointless initializer that I don't really understand, so let's blindly copy it!
public init() {}
public func decode<T: Decodable>(_ type: T.Type, from snapshot: DataSnapshot) throws -> T {
return try T.init(from: _DataSnapshotDecoder(snapshot))
}
/**
These are the special keys we support to decode a Firebase Realtime Database object's key and priority.
[Firebase docs](https://firebase.google.com/docs/database/web/structure-data) say: "If you create your own keys, they… cannot contain ., $, #, [, ], /, or ASCII control characters 0-31 or 127." So there's no chance that we accidentally shadow a value set by the database user so long as we pick one of those characters to include in the key.
*/
public enum SpecialKey: String, CodingKey {
case key = ".key"
case priority = ".priority"
}
}
/**
The actual workhorse of the `DataSnapshotDecoder`.
There's a fairly straightforward mapping from `DataSnapshot` to the various decoding containers and their methods:
- `DataSnapshot.exists()` maps to `decodeNil()`
- `DataSnapshot.childSnapshot(forPath:)` (usually followed by a `DataSnapshot.value`) maps to `KeyedDecodingContainer`.
- `DataSnapshot.children` maps to `UnkeyedDecodingContainer`.
- `DataSnapshot.value` maps to `SingleValueDecodingContainer`.
There's a lot of copied code here and a healthy amount of boilerplate, but it starts to make sense after you dive in. Useful references include:
- `Decodable` and its related protocols have documenting comments (command-right click any of them).
- Mike Ash's writeups on [`Swift.Codable`](https://www.mikeash.com/pyblog/friday-qa-2017-07-14-swiftcodable.html) and [A Binary Decoder for Swift](https://www.mikeash.com/pyblog/friday-qa-2017-07-28-a-binary-coder-for-swift.html) (the binary decoder writeup includes sample code).
- [`JSONDecoder`'s implementation](https://github.com/apple/swift/blob/master/stdlib/public/SDK/Foundation/JSONEncoder.swift). Note that, as of writing (2017-12-19), `JSONDecoder` uses a different approach than we use here. Only one instance of `_JSONDecoder` gets created, and it maintains a context stack to keep track of where it is in the JSON object. We create new instnces of `_DataSnapshotDecoder` as needed.
*/
private class _DataSnapshotDecoder: Decoder {
let codingPath: [CodingKey]
private let snapshot: DataSnapshot
var userInfo: [CodingUserInfoKey: Any] { return [:] }
init(_ snapshot: DataSnapshot, codingPath: [CodingKey] = []) {
self.codingPath = codingPath
self.snapshot = snapshot
}
func container<Key: CodingKey>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> {
guard snapshot.exists() else {
throw DecodingError.valueNotFound(KeyedDecodingContainer<Key>.self, DecodingError.Context(codingPath: codingPath, debugDescription: "Cannot get keyed decoding container, found nil instead"))
}
let container = KeyedContainer<Key>(snapshot, codingPath: codingPath)
return KeyedDecodingContainer(container)
}
private struct KeyedContainer<Key: CodingKey>: KeyedDecodingContainerProtocol {
let codingPath: [CodingKey]
let snapshot: DataSnapshot
private let stringKeys: [String]
var allKeys: [Key] {
return stringKeys.flatMap { Key(stringValue: $0) }
}
init(_ snapshot: DataSnapshot, codingPath: [CodingKey]) {
self.snapshot = snapshot
self.codingPath = codingPath
let randoKeys = snapshot
.children
.map { ($0 as! DataSnapshot).key }
var specialKeys = [DataSnapshotDecoder.SpecialKey.key]
if snapshot.hasPriority {
specialKeys.append(.priority)
}
stringKeys = randoKeys + specialKeys.map { $0.stringValue }
}
func contains(_ key: Key) -> Bool {
return stringKeys.contains(key.stringValue)
}
func decodeNil(forKey key: Key) throws -> Bool {
if case .priority? = DataSnapshotDecoder.SpecialKey(stringValue: key.stringValue) {
return !snapshot.hasPriority
}
guard snapshot.hasChild(key.stringValue) else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")"))
}
return !snapshot.childSnapshot(forPath: key.stringValue).exists()
}
private func decodePrimitive<T>(_ type: T.Type, forKey key: Key) throws -> T {
guard snapshot.hasChild(key.stringValue) else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")"))
}
let child = snapshot.childSnapshot(forPath: key.stringValue)
guard child.exists(), let anyValue = child.value else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: codingPath + [key], debugDescription: "Expected \(type) but found nil instead"))
}
guard let value = anyValue as? T else {
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath + [key], debugDescription: "Expected \(type) but found \(Swift.type(of: anyValue))"))
}
return value
}
func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool {
return try decodePrimitive(type, forKey: key)
}
func decode(_ type: Int.Type, forKey key: Key) throws -> Int {
return try decodePrimitive(type, forKey: key)
}
func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 {
return try decodePrimitive(type, forKey: key)
}
func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 {
return try decodePrimitive(type, forKey: key)
}
func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 {
return try decodePrimitive(type, forKey: key)
}
func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 {
return try decodePrimitive(type, forKey: key)
}
func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt {
return try decodePrimitive(type, forKey: key)
}
func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 {
return try decodePrimitive(type, forKey: key)
}
func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 {
return try decodePrimitive(type, forKey: key)
}
func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 {
return try decodePrimitive(type, forKey: key)
}
func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 {
return try decodePrimitive(type, forKey: key)
}
func decode(_ type: Float.Type, forKey key: Key) throws -> Float {
return try decodePrimitive(type, forKey: key)
}
func decode(_ type: Double.Type, forKey key: Key) throws -> Double {
return try decodePrimitive(type, forKey: key)
}
func decode(_ type: String.Type, forKey key: Key) throws -> String {
if let specialKey = DataSnapshotDecoder.SpecialKey(stringValue: key.stringValue) {
switch specialKey {
case .key:
return snapshot.key
case .priority:
guard snapshot.hasPriority else {
throw DecodingError.valueNotFound(String.self, DecodingError.Context(codingPath: codingPath + [key], debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")"))
}
return snapshot.priority as! String
}
}
return try decodePrimitive(type, forKey: key)
}
func decode<T: Decodable>(_ type: T.Type, forKey key: Key) throws -> T {
if DataSnapshotDecoder.SpecialKey(stringValue: key.stringValue) != nil {
let decoder = _DataSnapshotDecoder(snapshot, codingPath: codingPath + [key])
return try T.init(from: decoder)
}
guard snapshot.hasChild(key.stringValue) else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")"))
}
let child = snapshot.childSnapshot(forPath: key.stringValue)
guard child.exists() else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: codingPath + [key], debugDescription: "Expected \(type) but found nil instead"))
}
let decoder = _DataSnapshotDecoder(child, codingPath: codingPath + [key])
return try T.init(from: decoder)
}
func nestedContainer<NestedKey: CodingKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> {
guard snapshot.hasChild(key.stringValue) else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: codingPath, debugDescription: "Cannot get \(KeyedDecodingContainer<NestedKey>.self); no value associated with key \(key) (\"\(key.stringValue)\")"))
}
let child = snapshot.childSnapshot(forPath: key.stringValue)
guard child.exists() else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: codingPath + [key], debugDescription: "Cannot get \(KeyedDecodingContainer<NestedKey>.self); no value found for key \(key) (\"\(key.stringValue)\")"))
}
let container = KeyedContainer<NestedKey>(child, codingPath: codingPath + [key])
return KeyedDecodingContainer(container)
}
func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer {
let child = snapshot.childSnapshot(forPath: key.stringValue)
guard child.exists() else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: codingPath, debugDescription: "Cannot get \(UnkeyedDecodingContainer.self); no value associated with key \(key) (\"\(key.stringValue)\")"))
}
return UnkeyedContainer(child, codingPath: codingPath + [key])
}
func superDecoder() throws -> Decoder {
return _DataSnapshotDecoder(snapshot, codingPath: codingPath)
}
func superDecoder(forKey key: Key) throws -> Decoder {
let child = snapshot.childSnapshot(forPath: key.stringValue)
return _DataSnapshotDecoder(child, codingPath: codingPath + [key])
}
}
func unkeyedContainer() throws -> UnkeyedDecodingContainer {
guard snapshot.exists() else {
throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self, DecodingError.Context(codingPath: codingPath, debugDescription: "Cannot get unkeyed decoding container, found nil instead"))
}
return UnkeyedContainer(snapshot, codingPath: codingPath)
}
private struct IndexKey: CodingKey {
private let index: Int
init?(intValue: Int) {
index = intValue
}
init?(stringValue: String) {
return nil
}
init(index: Int) {
self.index = index
}
var intValue: Int? { return index }
var stringValue: String { return "\(index)" }
}
private struct UnkeyedContainer: UnkeyedDecodingContainer {
let codingPath: [CodingKey]
private let snapshot: DataSnapshot
private var iterator: NSEnumerator.Iterator
private var currentItem: DataSnapshot?
var count: Int? { return Int(snapshot.childrenCount) }
var isAtEnd: Bool { return currentItem == nil }
private(set) var currentIndex: Int
init(_ snapshot: DataSnapshot, codingPath: [CodingKey]) {
self.snapshot = snapshot
self.codingPath = codingPath
iterator = snapshot.children.makeIterator()
currentItem = iterator.next() as! DataSnapshot?
currentIndex = 0
}
private mutating func advanceToNextItem() {
currentItem = iterator.next() as! DataSnapshot?
if currentItem != nil {
currentIndex += 1
}
}
private func ensureCurrentItem() throws -> DataSnapshot {
guard let currentItem = currentItem else {
throw DecodingError.valueNotFound(Any.self, DecodingError.Context(codingPath: codingPath + [IndexKey(index: currentIndex)], debugDescription: "End of unkeyed container"))
}
return currentItem
}
mutating func decodeNil() throws -> Bool {
let isNil = !snapshot.exists()
if isNil {
advanceToNextItem()
}
return isNil
}
private mutating func decodePrimitive<T>(_ type: T.Type) throws -> T {
guard let currentItem = currentItem else {
throw DecodingError.valueNotFound(Any.self, DecodingError.Context(codingPath: codingPath + [IndexKey(index: currentIndex)], debugDescription: "End of unkeyed container"))
}
guard let anyValue = currentItem.value else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: codingPath + [IndexKey(index: currentIndex)], debugDescription: "Expected item of type \(type) but got nil instead"))
}
guard let value = anyValue as? T else {
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath + [IndexKey(index: currentIndex)], debugDescription: "Expected item of type \(type) but got \(Swift.type(of: anyValue)) instead"))
}
advanceToNextItem()
return value
}
mutating func decode(_ type: Bool.Type) throws -> Bool {
return try decodePrimitive(type)
}
mutating func decode(_ type: Int.Type) throws -> Int {
return try decodePrimitive(type)
}
mutating func decode(_ type: Int8.Type) throws -> Int8 {
return try decodePrimitive(type)
}
mutating func decode(_ type: Int16.Type) throws -> Int16 {
return try decodePrimitive(type)
}
mutating func decode(_ type: Int32.Type) throws -> Int32 {
return try decodePrimitive(type)
}
mutating func decode(_ type: Int64.Type) throws -> Int64 {
return try decodePrimitive(type)
}
mutating func decode(_ type: UInt.Type) throws -> UInt {
return try decodePrimitive(type)
}
mutating func decode(_ type: UInt8.Type) throws -> UInt8 {
return try decodePrimitive(type)
}
mutating func decode(_ type: UInt16.Type) throws -> UInt16 {
return try decodePrimitive(type)
}
mutating func decode(_ type: UInt32.Type) throws -> UInt32 {
return try decodePrimitive(type)
}
mutating func decode(_ type: UInt64.Type) throws -> UInt64 {
return try decodePrimitive(type)
}
mutating func decode(_ type: Float.Type) throws -> Float {
return try decodePrimitive(type)
}
mutating func decode(_ type: Double.Type) throws -> Double {
return try decodePrimitive(type)
}
mutating func decode(_ type: String.Type) throws -> String {
return try decodePrimitive(type)
}
mutating func decode<T: Decodable>(_ type: T.Type) throws -> T {
let decoder = try _DataSnapshotDecoder(ensureCurrentItem(), codingPath: codingPath + [IndexKey(index: currentIndex)])
let value = try type.init(from: decoder)
advanceToNextItem()
return value
}
mutating func nestedContainer<NestedKey: CodingKey>(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer<NestedKey> {
let container = try KeyedContainer<NestedKey>(ensureCurrentItem(), codingPath: codingPath + [IndexKey(index: currentIndex)])
advanceToNextItem()
return KeyedDecodingContainer(container)
}
mutating func nestedUnkeyedContainer() throws -> UnkeyedDecodingContainer {
let container = try UnkeyedContainer(ensureCurrentItem(), codingPath: codingPath + [IndexKey(index: currentIndex)])
advanceToNextItem()
return container
}
mutating func superDecoder() throws -> Decoder {
let decoder = try _DataSnapshotDecoder(ensureCurrentItem(), codingPath: codingPath + [IndexKey(index: currentIndex)])
advanceToNextItem()
return decoder
}
}
func singleValueContainer() throws -> SingleValueDecodingContainer {
return self
}
}
extension _DataSnapshotDecoder: SingleValueDecodingContainer {
func decodeNil() -> Bool {
return !snapshot.exists()
}
private var specialLastPathComponent: DataSnapshotDecoder.SpecialKey? {
return codingPath.last.flatMap { DataSnapshotDecoder.SpecialKey(stringValue: $0.stringValue) }
}
private func decodePrimitive<T>(_ type: T.Type) throws -> T {
switch specialLastPathComponent {
case .key?:
guard T.self is String.Type else {
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, debugDescription: "Expected \(type) but got \(String.self) instead"))
}
return snapshot.key as! T
case .priority?:
guard let anyPriority = snapshot.priority else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: codingPath, debugDescription: "Expected \(type) but got nil instead"))
}
guard let priority = anyPriority as? T else {
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, debugDescription: "Expected \(type) but got \(Swift.type(of: anyPriority)) instead"))
}
return priority
case nil:
guard let anyValue = snapshot.value else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: codingPath, debugDescription: "Expected \(type) but got nil instead"))
}
guard let value = anyValue as? T else {
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, debugDescription: "Expected \(type) but got \(Swift.type(of: anyValue)) instead"))
}
return value
}
}
func decode(_ type: Bool.Type) throws -> Bool {
return try decodePrimitive(type)
}
func decode(_ type: Int.Type) throws -> Int {
return try decodePrimitive(type)
}
func decode(_ type: Int8.Type) throws -> Int8 {
return try decodePrimitive(type)
}
func decode(_ type: Int16.Type) throws -> Int16 {
return try decodePrimitive(type)
}
func decode(_ type: Int32.Type) throws -> Int32 {
return try decodePrimitive(type)
}
func decode(_ type: Int64.Type) throws -> Int64 {
return try decodePrimitive(type)
}
func decode(_ type: UInt.Type) throws -> UInt {
return try decodePrimitive(type)
}
func decode(_ type: UInt8.Type) throws -> UInt8 {
return try decodePrimitive(type)
}
func decode(_ type: UInt16.Type) throws -> UInt16 {
return try decodePrimitive(type)
}
func decode(_ type: UInt32.Type) throws -> UInt32 {
return try decodePrimitive(type)
}
func decode(_ type: UInt64.Type) throws -> UInt64 {
return try decodePrimitive(type)
}
func decode(_ type: Float.Type) throws -> Float {
return try decodePrimitive(type)
}
func decode(_ type: Double.Type) throws -> Double {
return try decodePrimitive(type)
}
func decode(_ type: String.Type) throws -> String {
return try decodePrimitive(type)
}
func decode<T>(_ type: T.Type) throws -> T where T : Decodable {
return try type.init(from: self)
}
}
private extension DataSnapshot {
/**
Whether this object has a priority.
This is slightly annoying to determine because `priority` is optional but in the field we tend to see it set to `NSNull.null`.
*/
var hasPriority: Bool {
// Documented to be a `String` if it's set, so we can simplify this check and avoid force unwrapping errors above.
return priority is String
}
}