Pages: Repositories

Repositories

Repository is a small storage interface with two of every method: a Blocking one you call when you're already off the main thread, and a suspend one that hops off it for you.

val user = userRepository.findBlocking(id)   // blocking, off-thread callers

SporeCoroutines.launch {
    val user = userRepository.find(id)       // suspends, runs off the main thread
}

MongoRepository implements it against a Mongo collection - you supply the document mapping:

object UserRepository : MongoRepository<User>("users") {
    override fun idOf(value: User) = value.uuid.toString()
    override fun toDocument(value: User) = Document("_id", idOf(value)).append("name", value.name)
    override fun fromDocument(document: Document) = User(
        UUID.fromString(document.getString("_id")),
        document.getString("name")
    )
}

Point SporeMongo at your database once during enable and every repository can resolve its collection:

SporeMongo.init(myMongoDatabase)

Your plugin still owns the client and its lifetime - SporeAPI never opens or closes the connection.

YamlRepository is the same interface backed by a folder of .yml files, with write/read instead of toDocument/fromDocument.

Every blocking call in both goes through the main-thread IO guard, so calling one on the server thread shows up in debugging.