MongoView/MongoView/ExtendedJSON.swift

52 lines
1.4 KiB
Swift

//
// ExtendedJSON.swift
// MongoView
//
// Created by Shadowfacts on 4/4/20.
// Copyright © 2020 Shadowfacts. All rights reserved.
//
import Foundation
import JavaScriptCore
import MongoSwift
struct ExtendedJSON {
private init() {}
private static let context: JSContext = {
let context = JSContext()!
let objectId: @convention(block) (String) -> [String: String] = { (id) in
return ["$oid": id]
}
context.setObject(objectId, forKeyedSubscript: "ObjectId" as NSString)
let date: @convention(block) (String) -> [String: String] = { (date) in
return ["$date": date]
}
context.setObject(date, forKeyedSubscript: "Date" as NSString)
return context
}()
static func normalize(_ string: String) -> String? {
return context.evaluateScript("JSON.stringify(\(string))")?.toString()
}
private static func fromExtJSON(_ string: String) -> BSONDocument? {
do {
let doc = try BSONDocument(fromJSON: string)
return doc
} catch {
print("Unable to create document from extended JSON: \(error)")
return nil
}
}
static func toDocument(_ string: String) -> BSONDocument? {
guard let normalized = normalize(string),
let doc = fromExtJSON(normalized) else {
return nil
}
return doc
}
}