impl mongo module

This commit is contained in:
tursom 2020-02-19 03:09:37 +08:00
parent fc8cd49841
commit 79ed71efae
3 changed files with 8 additions and 4 deletions

View File

@ -20,6 +20,7 @@ class MongoOperator<T : Any>(
constructor(clazz: Class<T>, database: MongoDatabase) : this(database.getCollection(MongoUtil.collectionName(clazz), clazz), clazz)
private val fields = clazz.declaredFields.filter {
it.isAccessible = true
!it.isTransient() && it.getAnnotation(Ignore::class.java) == null
}
@ -49,17 +50,17 @@ class MongoOperator<T : Any>(
@Suppress("SpellCheckingInspection")
fun upsert(update: Bson, where: Bson, options: UpdateOptions = UpdateOptions()): UpdateResult {
return update(convertToBson(update), where, options.upsert(true))
return update(update, where, options.upsert(true))
}
fun add(field: KProperty1<T, Number>, value: Number, where: Bson, options: UpdateOptions = UpdateOptions()): UpdateResult {
fun add(field: KProperty1<T, Number?>, value: Number, where: Bson, options: UpdateOptions = UpdateOptions()): UpdateResult {
return upsert(
Update { field inc value },
where, options
)
}
fun inc(field: KProperty1<T, Number>, where: Bson): UpdateResult {
fun inc(field: KProperty1<T, Number?>, where: Bson): UpdateResult {
return add(field, 1, where)
}

View File

@ -28,10 +28,11 @@ object MongoUtil {
fun convertToBson(entity: Any): Bson {
val bson = Document()
entity.javaClass.declaredFields.filter {
it.isAccessible = true
!it.isTransient() && it.getAnnotation(Ignore::class.java) == null
}.forEach {
val value = it.get(entity) ?: return@forEach
bson[MongoUtil.fieldName(it)] = value
bson[fieldName(it)] = value
}
return bson
}

View File

@ -7,6 +7,8 @@ import kotlin.reflect.KProperty
object Update {
operator fun invoke(action: Update.() -> Bson) = this.action()
infix fun Bson.and(update: Bson): Bson = Updates.combine(this, update)
fun combine(vararg updates: Bson): Bson = Updates.combine(*updates)
infix fun KProperty<*>.set(value: Any): Bson = Updates.set(MongoUtil.fieldName(this), value)
fun KProperty<*>.unset(): Bson = Updates.unset(MongoUtil.fieldName(this))