// // MongoEvaluator.swift // MongoView // // Created by Shadowfacts on 1/12/20. // Copyright © 2020 Shadowfacts. All rights reserved. // import Foundation import MongoSwift struct MongoEvaluator { static let decoder = BSONDecoder() static func parse(extendedJSON: String) -> BSON? { guard !extendedJSON.isEmpty else { return nil } do { return try decoder.decode(BSON.self, from: extendedJSON) } catch { print("Unable to parse BSON: \(error)") return nil } } static func eval(command: String, connectingTo connStr: String) -> [BSON] { let realCommand = """ Object.prototype.printExtJSON = function() { print(JSON.stringify(this)); }; Array.prototype.printExtJSON = function() { this.map(JSON.stringify).forEach(it => print(it)); }; \(command).printExtJSON() """ print("Running command \"\(command)\" against \(connStr)") let mongoOutputPipe = Pipe() let mongoProcess = Process() mongoProcess.launchPath = "/usr/local/bin/mongo" mongoProcess.arguments = [connStr, "--quiet", "--norc", "--eval", realCommand] mongoProcess.standardOutput = mongoOutputPipe mongoProcess.launch() let mongoOutputHandle = mongoOutputPipe.fileHandleForReading var strs = [String]() var data: Data! repeat { data = mongoOutputHandle.availableData strs.append(String(data: data, encoding: .utf8)!) } while (data.count > 0) mongoOutputHandle.closeFile() let lines = strs.joined(separator: "").components(separatedBy: "\n") return lines.compactMap(parse(extendedJSON:)) } }