Revision control

1
/* This Source Code Form is subject to the terms of the Mozilla Public
2
* License, v. 2.0. If a copy of the MPL was not distributed with this
3
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5
import Foundation
6
import Shared
7
import SwiftyJSON
8
9
open class EnvelopeJSON {
10
fileprivate let json: JSON
11
12
public init(_ jsonString: String) {
13
self.json = JSON(parseJSON: jsonString)
14
}
15
16
public init(_ json: JSON) {
17
self.json = json
18
}
19
20
open func isValid() -> Bool {
21
return !self.json.isError() &&
22
self.json["id"].isString() &&
23
//self["collection"].isString &&
24
self.json["payload"].isString()
25
}
26
27
open var id: String {
28
return self.json["id"].string!
29
}
30
31
open var collection: String {
32
return self.json["collection"].string ?? ""
33
}
34
35
open var payload: String {
36
return self.json["payload"].string!
37
}
38
39
open var sortindex: Int {
40
let s = self.json["sortindex"]
41
return s.int ?? 0
42
}
43
44
open var modified: Timestamp {
45
// if let intValue = self.json["modified"].int64 {
46
// return Timestamp(intValue) * 1000
47
// }
48
49
if let doubleValue = self.json["modified"].double {
50
return Timestamp(1000 * (doubleValue))
51
}
52
53
return 0
54
}
55
56
open func stringify() -> String {
57
return self.json.stringify()!
58
}
59
60
open func withModified(_ now: Timestamp) -> EnvelopeJSON {
61
if var d = self.json.dictionary {
62
d["modified"] = JSON(Double(now) / 1000)
63
return EnvelopeJSON(JSON(d))
64
}
65
return EnvelopeJSON(JSON(parseJSON: "!")) // Intentionally bad JSON.
66
}
67
}
68
69
extension EnvelopeJSON {
70
func asJSON() -> JSON {
71
return self.json
72
}
73
}