Created
January 21, 2020 23:35
-
-
Save ghahramani/4c2e5ce4ae879a50a48e1873306f7d51 to your computer and use it in GitHub Desktop.
Spring data default methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SimpleBaseGenericReactiveMongoRepository<ENTITY>( | |
private val entityInformation: MappingMongoEntityInformation<ENTITY, String>, | |
private val template: ReactiveMongoTemplate | |
) : SimpleReactiveMongoRepository<ENTITY, String>(entityInformation, template), | |
BaseGenericReactiveMongoRepository<ENTITY> { | |
private val eventPublisher: ApplicationEventPublisher? | |
init { | |
val context = template.converter.mappingContext as MongoMappingContext | |
val indexCreator = MongoPersistentEntityIndexCreator(context) { collectionName -> | |
IndexOperationsAdapter.blocking(template.indexOps(collectionName)) | |
} | |
eventPublisher = MongoMappingEventPublisher(indexCreator) | |
} | |
override fun patch(id: String, fields: Map<String, Any>): Mono<ENTITY> { | |
val collection = entityInformation.collectionName | |
val query = Query(Criteria.where("_id").`is`(id)) | |
val document = Document() | |
return findById(id) | |
.flatMap { entity -> | |
maybeEmitEvent(BeforeConvertEvent<ENTITY>(entity, collection)) | |
document.putAll(fields) | |
val update = Update() | |
fields | |
.filter { entry -> | |
!hashSetOf("_id", "createdAt", "createdBy", "modifiedAt", "modifiedBy").contains(entry.key) | |
} | |
.forEach { entry -> update.set(entry.key, entry.value) } | |
maybeEmitEvent(BeforeSaveEvent<ENTITY>(entity, document, collection)) | |
template.updateFirst(query, update, collection) | |
} | |
.then(findById(id)).map { entity -> | |
maybeEmitEvent(AfterSaveEvent<ENTITY>(entity, document, collection)) | |
entity | |
} | |
} | |
private fun <T> maybeEmitEvent(event: MongoMappingEvent<T>) { | |
eventPublisher?.publishEvent(event) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment