-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathMapHelper.swift
90 lines (81 loc) · 3.18 KB
/
MapHelper.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
//
// QueryHelper.swift
// CbliteSwiftJsLib
import Foundation
import CouchbaseLiteSwift
public struct MapHelper {
public static func documentToMap(_ document: Document) ->
[String: Any] {
var docMap = [String: Any]()
let documentAsMap = document.toDictionary()
for (key, value) in documentAsMap {
if let blobEntry = value as? Blob {
var properties = blobEntry.properties
if let data = blobEntry.content {
var content: [Int] = []
data.regions.forEach { region in
for byte in region {
content.append(Int(byte))
}
}
docMap[key] = properties.merging(["raw": content]) { (_, new) in new }
}
} else {
docMap[key] = value
}
}
return docMap
}
public static func resultToMap(_ result: Result,
databaseName: String) ->
[String: Any] {
var docMap = result.toDictionary()
if let idValue = docMap["_id"] {
docMap["id"] = idValue
docMap.removeValue(forKey: "_id")
}
if let docValue = docMap["_doc"] {
docMap[databaseName] = docValue
docMap.removeValue(forKey: "_doc")
}
return self.resultDictionaryToMap(docMap, databaseName: databaseName)
}
public static func resultDictionaryToMap(_
dictionary: [String: Any],
databaseName: String) -> [String: Any] {
var docMap = [String: Any]()
for (key, value) in dictionary {
let finalKey = key == "*" ? databaseName : key
if let blobEntry = value as? Blob {
docMap[finalKey] = blobEntry.properties
} else if let nestedDictionary = value as? [String: Any] {
docMap[finalKey] = resultDictionaryToMap(nestedDictionary, databaseName: databaseName)
} else {
docMap[finalKey] = value
}
}
return docMap
}
public static func toMap(_ map: [String: Any]) -> [String: Any] {
var document = [String: Any]()
for (key, value) in map {
if let object = value as? [String: Any],
let type = object["_type"] as? String, type == "blob" {
if let blobData = object["data"] as? [String: Any],
let contentType = blobData["contentType"] as? String,
let bytes = blobData["data"] as? [NSNumber] {
var bytesCArray = [UInt8](repeating: 0, count: bytes.count)
for (index, byte) in bytes.enumerated() {
bytesCArray[index] = byte.uint8Value
}
let data = Data(bytesCArray)
let blob = Blob(contentType: contentType, data: data)
document[key] = blob
continue
}
}
document[key] = value
}
return document
}
}