A Mac app for working with Mongo databases.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

MongoEvaluator.swift 1.7KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. //
  2. // MongoEvaluator.swift
  3. // MongoView
  4. //
  5. // Created by Shadowfacts on 1/12/20.
  6. // Copyright © 2020 Shadowfacts. All rights reserved.
  7. //
  8. import Foundation
  9. import MongoSwift
  10. struct MongoEvaluator {
  11. static let decoder = BSONDecoder()
  12. static func parse(extendedJSON: String) -> BSON? {
  13. guard !extendedJSON.isEmpty else {
  14. return nil
  15. }
  16. do {
  17. return try decoder.decode(BSON.self, from: extendedJSON)
  18. } catch {
  19. print("Unable to parse BSON: \(error)")
  20. return nil
  21. }
  22. }
  23. static func eval(command: String, connectingTo connStr: String) -> [BSON] {
  24. let realCommand = """
  25. Object.prototype.printExtJSON = function() { print(JSON.stringify(this)); };
  26. Array.prototype.printExtJSON = function() { this.map(JSON.stringify).forEach(it => print(it)); };
  27. \(command).printExtJSON()
  28. """
  29. print("Running command \"\(command)\" against \(connStr)")
  30. let mongoOutputPipe = Pipe()
  31. let mongoProcess = Process()
  32. mongoProcess.launchPath = "/usr/local/bin/mongo"
  33. mongoProcess.arguments = [connStr, "--quiet", "--norc", "--eval", realCommand]
  34. mongoProcess.standardOutput = mongoOutputPipe
  35. mongoProcess.launch()
  36. let mongoOutputHandle = mongoOutputPipe.fileHandleForReading
  37. var strs = [String]()
  38. var data: Data!
  39. repeat {
  40. data = mongoOutputHandle.availableData
  41. strs.append(String(data: data, encoding: .utf8)!)
  42. } while (data.count > 0)
  43. mongoOutputHandle.closeFile()
  44. let lines = strs.joined(separator: "").components(separatedBy: "\n")
  45. return lines.compactMap(parse(extendedJSON:))
  46. }
  47. }