Browse Source

Improve Mongo output handling

master
Shadowfacts 5 months ago
parent
commit
e507817b84
Signed by: Shadowfacts <me@shadowfacts.net> GPG Key ID: 94A5AB95422746E5

+ 14
- 40
MongoView/MongoEvaluator.swift View File

@@ -7,63 +7,37 @@
7 7
 //
8 8
 
9 9
 import Foundation
10
-import JavaScriptCore
11 10
 import MongoSwift
12 11
 
13 12
 struct MongoEvaluator {
14 13
     
15
-    static let context: JSContext = {
16
-        let context = JSContext()!
17
-        let date: @convention(block) (JSValue) -> Dictionary<String, Any> = { (input) in
18
-            ["$date": input]
19
-        }
20
-        let functions: [NSString: @convention(block) (JSValue) -> Dictionary<String, Any>] = [
21
-            "ObjectId": { (input) in
22
-                ["$oid": input]
23
-            },
24
-            "NumberLong": { (input) in
25
-                ["$numberLong": input]
26
-            },
27
-            "NumberInt": { (input) in
28
-                ["$numberInt": input]
29
-            },
30
-            "NumberDecimal": { (input) in
31
-                ["$numberDecimal": input]
32
-            },
33
-            "Date": date,
34
-            "ISODate": date,
35
-        ]
36
-        functions.forEach { (key, value) in
37
-            context.setObject(value, forKeyedSubscript: key)
38
-        }
39
-        let dbRef: @convention(block) (String, String) -> Dictionary<String, Any> = { (ref, id) in
40
-            ["$ref": ref, "$id": ["$oid": id]]
41
-        }
42
-        context.setObject(dbRef, forKeyedSubscript: "DBRef" as NSString)
43
-        return context
44
-    }()
14
+    static let decoder = BSONDecoder()
45 15
 
46
-    static func parse(shellJSON: String) -> Document? {
47
-        guard !shellJSON.isEmpty,
48
-            let result = context.evaluateScript("JSON.stringify(\(shellJSON))") else {
49
-                return nil
16
+    static func parse(extendedJSON: String) -> BSON? {
17
+        guard !extendedJSON.isEmpty else {
18
+            return nil
50 19
         }
51 20
         do {
52
-            return try Document(fromJSON: result.toString())
21
+            return try decoder.decode(BSON.self, from: extendedJSON)
53 22
         } catch {
54
-            print("Unable to parse Document: \(error)")
23
+            print("Unable to parse BSON: \(error)")
55 24
             return nil
56 25
         }
57 26
     }
58 27
     
59
-    static func eval(command: String, connectingTo connStr: String) -> [Document] {
28
+    static func eval(command: String, connectingTo connStr: String) -> [BSON] {
29
+        let realCommand = """
30
+Object.prototype.printExtJSON = function() { print(JSON.stringify(this)); };
31
+Array.prototype.printExtJSON = function() { this.map(JSON.stringify).forEach(it => print(it)); };
32
+\(command).printExtJSON()
33
+"""
60 34
         print("Running command \"\(command)\" against \(connStr)")
61 35
         
62 36
         let mongoOutputPipe = Pipe()
63 37
 
64 38
         let mongoProcess = Process()
65 39
         mongoProcess.launchPath = "/usr/local/bin/mongo"
66
-        mongoProcess.arguments = [connStr, "--quiet", "--norc", "--eval", command]
40
+        mongoProcess.arguments = [connStr, "--quiet", "--norc", "--eval", realCommand]
67 41
         mongoProcess.standardOutput = mongoOutputPipe
68 42
         mongoProcess.launch()
69 43
         
@@ -78,7 +52,7 @@ struct MongoEvaluator {
78 52
         mongoOutputHandle.closeFile()
79 53
         
80 54
         let lines = strs.joined(separator: "").components(separatedBy: "\n")
81
-        return lines.compactMap(parse(shellJSON:))
55
+        return lines.compactMap(parse(extendedJSON:))
82 56
     }
83 57
     
84 58
 }

+ 8
- 1
MongoView/Node.swift View File

@@ -37,8 +37,15 @@ class Node {
37 37
     }
38 38
 
39 39
     init(key: Key? = nil, value: BSON) {
40
-        self.key = key
41 40
         self.value = value
41
+        
42
+        if key == nil,
43
+            case let .document(doc) = value,
44
+            case let .objectId(id) = doc["_id"] {
45
+            self.key = .objectId(id)
46
+        } else {
47
+            self.key = key
48
+        }
42 49
     }
43 50
     
44 51
     convenience init(document: Document) {

+ 1
- 1
MongoView/View Controllers/QueryViewController.swift View File

@@ -20,7 +20,7 @@ class QueryViewController: NSViewController {
20 20
     let collection: DatabaseCollection
21 21
     
22 22
     var defaultQuery: String {
23
-        "db.getCollection('\(collection.name)').find({})"
23
+        "db.getCollection('\(collection.name)').find({}).toArray()"
24 24
     }
25 25
     
26 26
     var hasQueryChanged: Bool {

Loading…
Cancel
Save