Skip to content

Commit f936b06

Browse files
authored
SWIFT-921 Implement extended json decoder methods (#27)
1 parent 05b7156 commit f936b06

File tree

2 files changed

+21
-6
lines changed

2 files changed

+21
-6
lines changed

Sources/BSON/ExtendedJSONDecoder.swift

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,7 @@ public class ExtendedJSONDecoder {
88
}()
99

1010
/// Initialize an `ExtendedJSONDecoder`.
11-
public init() {
12-
fatalError("unimplemented")
13-
}
11+
public init() {}
1412

1513
/// Decodes an instance of the requested type `T` from the provided extended JSON data.
1614
/// - SeeAlso: https://docs.mongodb.com/manual/reference/mongodb-extended-json/
@@ -21,10 +19,14 @@ public class ExtendedJSONDecoder {
2119
/// - Returns: Decoded representation of the JSON input as an instance of `T`.
2220
/// - Throws: `DecodingError` if the JSON data is corrupt or if any value throws an error during decoding.
2321
public func decode<T: Decodable>(_ type: T.Type, from data: Data) throws -> T {
22+
// Data --> JSON --> BSON --> T
2423
// Takes in JSON as `Data` encoded with `.utf8` and runs it through a `JSONDecoder` to get an
25-
// instance of the `JSON` enum. Then a `BSON` enum instance is created via the `JSON`.
24+
// instance of the `JSON` enum.
25+
let wrappedData = "[".utf8 + data + "]".utf8
26+
let json = try JSONDecoder().decode([JSON].self, from: wrappedData)[0]
27+
// Then a `BSON` enum instance is created via the `JSON`.
28+
let bson = try BSON(fromExtJSON: json, keyPath: [])
2629
// The `BSON` is then passed through a `BSONDecoder` where it is outputted as a `T`
27-
// Data --> JSON --> BSON --> T
28-
fatalError("unimplemented")
30+
return try BSONDecoder().decode(T.self, fromBSON: bson)
2931
}
3032
}

Tests/BSONTests/ExtendedJSONConversionTests.swift

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,19 @@ open class ExtendedJSONConversionTestCase: BSONTestCase {
1414
expect(document.documentValue!["extra"]).to(equal(.int32(1)))
1515
}
1616

17+
func testExtendedJSONDecoder() throws {
18+
struct Foo: Decodable, Equatable {
19+
let x: Bool
20+
let y: Int
21+
let z: BSONRegularExpression
22+
}
23+
let regexStr = "{\"$regularExpression\": {\"pattern\": \"p\", \"options\": \"i\"}}"
24+
let regexObj = BSONRegularExpression(pattern: "p", options: "i")
25+
let data = "{ \"x\": true, \"y\": { \"$numberInt\": \"5\" }, \"z\": \(regexStr) }".data(using: .utf8)!
26+
let decoder = ExtendedJSONDecoder()
27+
expect(try decoder.decode(Foo.self, from: data)).to(equal(Foo(x: true, y: 5, z: regexObj)))
28+
}
29+
1730
func testObjectId() throws {
1831
let oid = "5F07445CFBBBBBBBBBFAAAAA"
1932

0 commit comments

Comments
 (0)