2

I am using http://mongodb.github.io/mongo-scala-driver/

I am defining codec for one CC.

 lazy val userInfoCodec: Codec[UserInfo] = new Codec[UserInfo] {

    override def encode(writer: BsonWriter, value: UserInfo, encoderContext: EncoderContext): Unit = ???
    override def decode(reader: BsonReader, decoderContext: DecoderContext): UserInfo = ???
}

Inside I am doing encryption, so fields instead of being Strings are Array[Byte]. Do you know how to use BsonWriter to write bytes array there ? I saw some stuff like writeStartArray, but I dont get how to use it.

Thanks for help!

1
  • I don't think you need to write a real BSON Array, but instead you may give a look to the BsonBinary type which takes a byte[] as its data argument. (the BsonWriter API exposes a method for writing BinaryData). - Other option would be to encode the byte[] as a Base64 String after doing the encryption. Commented Jan 15, 2019 at 21:23

1 Answer 1

3
case class UserInfo(ab: Array[Byte])

val userInfoCodec: Codec[UserInfo] = new Codec[UserInfo] {
  override def getEncoderClass: Class[UserInfo] = classOf[UserInfo]

  override def encode(writer: BsonWriter, value: UserInfo, encoderContext: EncoderContext): Unit = {
    val bsonBinary = new BsonBinary(value.ab)
    writer.writeBinaryData(bsonBinary)
  }



  override def decode(reader: BsonReader, decoderContext: DecoderContext): UserInfo = {
    val bsonBinary = reader.readBinaryData()
    UserInfo(bsonBinary.getData)
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.