Created
June 21, 2019 13:30
-
-
Save danslapman/5fe0b0523afa63cf1dfa03236b099fe6 to your computer and use it in GitHub Desktop.
dropNulls from BSONDocument
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import cats.free.Trampoline | |
import cats.instances.stream._ | |
import cats.instances.try_._ | |
import cats.syntax.nested._ | |
import cats.syntax.traverse._ | |
import reactivemongo.bson._ | |
import scala.util.{Failure, Success, Try} | |
implicit class BSONValueOps(private val bv: BSONValue) extends AnyVal { | |
def arrayOrDocument[X]( | |
or: => X, | |
bsonArray: Stream[Try[BSONValue]] => X, | |
bsonDocument: Stream[Try[BSONElement]] => X | |
): X = bv match { | |
case BSONArray(stream) => bsonArray(stream) | |
case BSONDocument(stream) => bsonDocument(stream) | |
case _ => or | |
} | |
def dropNulls: Trampoline[BSONValue] = | |
bv.arrayOrDocument( | |
Trampoline.done(bv), | |
arr => arr.nested.traverse(v => Trampoline.defer(v.dropNulls)).map(ns => BSONArray(ns.value)), | |
vals => vals | |
.collect { case Success(value) => value } | |
.filter(_.value.code != BSONNull.code) | |
.traverse(el => Trampoline.defer(el.value.dropNulls.map(v => Try(BSONElement(el.name, v))))) | |
.map(BSONDocument.apply) | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment