Add extract utilities to PersistenceId (#30881)
* extract entityTypeHint and entityId from persistence id String
This commit is contained in:
parent
20b684f04f
commit
596a2a463f
2 changed files with 47 additions and 0 deletions
|
|
@ -124,6 +124,29 @@ object PersistenceId {
|
|||
*/
|
||||
def ofUniqueId(id: String): PersistenceId =
|
||||
new PersistenceId(id)
|
||||
|
||||
/**
|
||||
* Extract the `entityTypeHint` from a persistence id String with the default separator `|`.
|
||||
* If the separator `|` is not found it return the empty String (`""`).
|
||||
*/
|
||||
def extractEntityType(id: String): String = {
|
||||
val i = id.indexOf(PersistenceId.DefaultSeparator)
|
||||
if (i == -1) ""
|
||||
else id.substring(0, i)
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract the `entityId` from a persistence id String with the default separator `|`.
|
||||
* If the separator `|` is not found it return the `id`.
|
||||
*/
|
||||
def extractEntityId(id: String): String = {
|
||||
val i = id.indexOf(PersistenceId.DefaultSeparator)
|
||||
if (i == -1) id
|
||||
else id.substring(i + 1)
|
||||
}
|
||||
|
||||
def unapply(persistenceId: PersistenceId): Option[(String, String)] =
|
||||
Some((persistenceId.entityTypeHint, persistenceId.entityId))
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -137,6 +160,9 @@ final class PersistenceId private (val id: String) {
|
|||
if (id.trim.isEmpty)
|
||||
throw new IllegalArgumentException("persistenceId must not be empty")
|
||||
|
||||
def entityTypeHint: String = PersistenceId.extractEntityType(id)
|
||||
def entityId: String = PersistenceId.extractEntityId(id)
|
||||
|
||||
override def toString: String = s"PersistenceId($id)"
|
||||
|
||||
override def hashCode(): Int = id.hashCode
|
||||
|
|
|
|||
|
|
@ -47,6 +47,27 @@ class PersistenceIdSpec extends AnyWordSpec with Matchers with LogCapturing {
|
|||
PersistenceId("SomeType", "A#B", "#")
|
||||
}
|
||||
}
|
||||
|
||||
"be able to extract entityTypeHint" in {
|
||||
PersistenceId.extractEntityType("SomeType|abc") should ===("SomeType")
|
||||
PersistenceId.extractEntityType("abc") should ===("")
|
||||
PersistenceId("SomeType", "abc").entityTypeHint should ===("SomeType")
|
||||
}
|
||||
|
||||
"be able to extract entityId" in {
|
||||
PersistenceId.extractEntityId("SomeType|abc") should ===("abc")
|
||||
PersistenceId.extractEntityId("abc") should ===("abc")
|
||||
PersistenceId("SomeType", "abc").entityId should ===("abc")
|
||||
}
|
||||
|
||||
"extract entityTypeHint and entityId via unapply" in {
|
||||
PersistenceId("SomeType", "abc") match {
|
||||
case PersistenceId(entityTypeHint, entityId) =>
|
||||
entityTypeHint should ===("SomeType")
|
||||
entityId should ===("abc")
|
||||
case _ => fail()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue