Skip to content

Commit

Permalink
Add UUIDCodec
Browse files Browse the repository at this point in the history
  • Loading branch information
srnyx committed Oct 13, 2024
1 parent fa41f91 commit 3fe1225
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
10 changes: 9 additions & 1 deletion src/main/java/xyz/srnyx/magicmongo/MagicMongo.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import xyz.srnyx.magicmongo.codecs.UUIDCodec;

import java.util.HashMap;
import java.util.Map;

Expand Down Expand Up @@ -136,13 +138,19 @@ public MagicDatabase getMagicDatabase(@NotNull String name) {
}

/**
* Gets the default {@link CodecRegistry} with the {@link PojoCodecProvider} enabled
* Gets the default {@link CodecRegistry}
* <ul>
* <li>{@link UUIDCodec}</li>
* <li>{@link MongoClientSettings#getDefaultCodecRegistry()}</li>
* <li>{@link PojoCodecProvider#builder() PojoCodecProvider.builder().automatic(true).build()}</li>
* </ul>
*
* @return the default {@link CodecRegistry}
*/
@NotNull
public static CodecRegistry getDefaultCodecRegistry() {
return CodecRegistries.fromRegistries(
CodecRegistries.fromCodecs(new UUIDCodec()),
MongoClientSettings.getDefaultCodecRegistry(),
CodecRegistries.fromProviders(PojoCodecProvider.builder().automatic(true).build()));
}
Expand Down
32 changes: 32 additions & 0 deletions src/main/java/xyz/srnyx/magicmongo/codecs/UUIDCodec.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package xyz.srnyx.magicmongo.codecs;

import org.bson.BsonReader;
import org.bson.BsonWriter;
import org.bson.codecs.Codec;
import org.bson.codecs.DecoderContext;
import org.bson.codecs.EncoderContext;

import org.jetbrains.annotations.NotNull;

import java.util.UUID;


/**
* A {@link Codec} for encoding and decoding {@link UUID UUIDs} to and from {@link String Strings}
*/
public class UUIDCodec implements Codec<UUID> {
@Override
public void encode(@NotNull BsonWriter writer, @NotNull UUID value, EncoderContext encoderContext) {
writer.writeString(value.toString());
}

@Override @NotNull
public UUID decode(@NotNull BsonReader reader, DecoderContext decoderContext) {
return UUID.fromString(reader.readString());
}

@Override
public Class<UUID> getEncoderClass() {
return UUID.class;
}
}

0 comments on commit 3fe1225

Please sign in to comment.