MongoView/MongoView/ExtendedJSON.swift

52 lines
1.4 KiB
Swift
Raw Normal View History

//
// ExtendedJSON.swift
// MongoView
//
// Created by Shadowfacts on 4/4/20.
// Copyright © 2020 Shadowfacts. All rights reserved.
//
import Foundation
import JavaScriptCore
2020-04-06 23:31:26 +00:00
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()
}
2020-08-12 23:09:43 +00:00
private static func fromExtJSON(_ string: String) -> BSONDocument? {
2020-04-06 23:31:26 +00:00
do {
2020-08-12 23:09:43 +00:00
let doc = try BSONDocument(fromJSON: string)
2020-04-06 23:31:26 +00:00
return doc
} catch {
print("Unable to create document from extended JSON: \(error)")
return nil
}
}
2020-08-12 23:09:43 +00:00
static func toDocument(_ string: String) -> BSONDocument? {
2020-04-06 23:31:26 +00:00
guard let normalized = normalize(string),
let doc = fromExtJSON(normalized) else {
return nil
}
return doc
}
}