Skip to content

Commit b33b985

Browse files
committed
0.7.1: Circe-converted decoders handle nulls, better errors
2 parents 83aab51 + edfda6f commit b33b985

File tree

3 files changed

+53
-4
lines changed

3 files changed

+53
-4
lines changed

circe/src/main/scala/mongo4cats/circe.scala

+4-3
Original file line numberDiff line numberDiff line change
@@ -50,10 +50,11 @@ object circe extends JsonCodecs {
5050

5151
implicit def circeDecoderToDecoder[A: Decoder] = new BsonDecoder[A] {
5252
def apply(b: BsonValue) = {
53-
val doc = BsonDocument(RootTag -> b).toJson()
53+
val doc = BsonDocument(RootTag -> (if (b == null) new BsonNull else b)).toJson()
5454
val json = parser.parse(doc)
55-
val decoder = Decoder.instance[A](_.get[A](RootTag))
56-
json
55+
val jsonWithoutRoot = json.flatMap(_.hcursor.get[Json](RootTag))
56+
val decoder = Decoder.instance[A](_.as[A])
57+
jsonWithoutRoot
5758
.flatMap(decoder.decodeJson(_))
5859
.leftMap(x =>
5960
BsonDecodeError {
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/*
2+
* Copyright 2020 Kirill5k
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package mongo4cats
18+
19+
import org.scalatest.wordspec.AnyWordSpec
20+
import org.scalatest.matchers.should.Matchers
21+
import org.bson.BsonString
22+
import io.circe.Decoder
23+
import org.scalatest.EitherValues
24+
import io.circe.DecodingFailure
25+
26+
class CirceSpec extends AnyWordSpec with Matchers with EitherValues {
27+
28+
"circe conversions" should {
29+
"decode null as if it was Json.null" in {
30+
circe.implicits.circeDecoderToDecoder[Unit](Decoder.instance { c =>
31+
c.value.asNull.toRight(DecodingFailure("wasn't null!", Nil))
32+
}).apply(null) shouldBe Right(())
33+
}
34+
35+
"not report the internal root tag in history when reporting errors" in {
36+
37+
val deco = Decoder.instance(h => {
38+
h.get[String]("hek")(Decoder.failedWithMessage("Bad!"))
39+
})
40+
41+
val res = circe.implicits.circeDecoderToDecoder[String](deco).apply(new BsonString("hek"))
42+
43+
res.left.value.msg shouldBe "An error occured during decoding BsonValue BsonString{value='hek'}: DecodingFailure(Attempt to decode value on failed cursor, List(DownField(hek)))"
44+
45+
}
46+
}
47+
48+
}

version.sbt

+1-1
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
version in ThisBuild := "0.7.0"
1+
version in ThisBuild := "0.7.1"

0 commit comments

Comments
 (0)