Skip to content

Commit

Permalink
refactor: move findByUsersId to UserService
Browse files Browse the repository at this point in the history
  • Loading branch information
Handiwork committed Apr 23, 2024
1 parent 88641b1 commit ead5880
Show file tree
Hide file tree
Showing 10 changed files with 83 additions and 46 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package plus.maa.backend.common.utils
package plus.maa.backend.common.extensions

inline fun <T> T?.requireNotNull(lazyMessage: () -> Any): T = requireNotNull(this, lazyMessage)

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package plus.maa.backend.common.extensions

import org.springframework.data.domain.Page
import org.springframework.data.domain.Pageable
import org.springframework.data.mongodb.core.MongoOperations
import org.springframework.data.mongodb.core.count
import org.springframework.data.mongodb.core.find
import org.springframework.data.mongodb.core.query.Criteria
import org.springframework.data.mongodb.core.query.Query
import org.springframework.data.support.PageableExecutionUtils

inline fun <reified T : Any> MongoOperations.findPage(
pageable: Pageable,
query: Query = Query(),
customizer: Query.() -> Unit = {},
): Page<T> {
val q = query.apply(customizer)
check(q.skip == 0L && !q.isLimited) { "query should not be paged" }
val content = find<T>(q.with(pageable))
val total = count<T>(q.skip(0).limit(0))
return PageableExecutionUtils.getPage(content, pageable) { total }
}

fun Query.addAndCriteria(vararg criteria: Criteria) {
addCriteria(Criteria().andOperator(*criteria))
}

fun Query.addOrCriteria(vararg criteria: Criteria) {
addCriteria(Criteria().orOperator(*criteria))
}

fun Query.addNorCriteria(vararg criteria: Criteria) {
addCriteria(Criteria().norOperator(*criteria))
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package plus.maa.backend.common.utils
package plus.maa.backend.common.extensions

import kotlinx.coroutines.reactor.awaitSingle
import org.springframework.core.io.buffer.DataBuffer
Expand Down
2 changes: 0 additions & 2 deletions src/main/kotlin/plus/maa/backend/repository/UserRepository.kt
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,3 @@ interface UserRepository : MongoRepository<MaaUser, String> {

fun findByUserId(userId: String): MaaUser?
}

fun UserRepository.findByUsersId(userId: List<String>): Map<String, MaaUser> = findAllById(userId).associateBy { it.userId!! }
43 changes: 21 additions & 22 deletions src/main/kotlin/plus/maa/backend/service/CommentsAreaService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,14 @@ package plus.maa.backend.service
import org.springframework.data.domain.PageRequest
import org.springframework.data.domain.Pageable
import org.springframework.data.domain.Sort
import org.springframework.data.mongodb.core.MongoTemplate
import org.springframework.data.mongodb.core.query.exists
import org.springframework.data.mongodb.core.query.isEqualTo
import org.springframework.data.repository.findByIdOrNull
import org.springframework.stereotype.Service
import plus.maa.backend.common.utils.requireNotNull
import plus.maa.backend.common.extensions.addAndCriteria
import plus.maa.backend.common.extensions.findPage
import plus.maa.backend.common.extensions.requireNotNull
import plus.maa.backend.controller.request.comments.CommentsAddDTO
import plus.maa.backend.controller.request.comments.CommentsQueriesDTO
import plus.maa.backend.controller.request.comments.CommentsRatingDTO
Expand All @@ -15,7 +20,6 @@ import plus.maa.backend.controller.response.comments.CommentsInfo
import plus.maa.backend.controller.response.comments.SubCommentsInfo
import plus.maa.backend.repository.CommentsAreaRepository
import plus.maa.backend.repository.CopilotRepository
import plus.maa.backend.repository.UserRepository
import plus.maa.backend.repository.entity.CommentsArea
import plus.maa.backend.repository.entity.Copilot
import plus.maa.backend.repository.entity.MaaUser
Expand All @@ -32,9 +36,10 @@ class CommentsAreaService(
private val commentsAreaRepository: CommentsAreaRepository,
private val ratingService: RatingService,
private val copilotRepository: CopilotRepository,
private val userRepository: UserRepository,
private val userService: UserService,
private val emailService: EmailService,
private val sensitiveWordService: SensitiveWordService,
private val mongoTemplate: MongoTemplate,
) {
/**
* 评论
Expand Down Expand Up @@ -70,9 +75,9 @@ class CommentsAreaService(
val receiverId = parentComment?.uploaderId ?: copilot.uploaderId
if (receiverId == null || receiverId == replierId) return

val userMap = userRepository.findAllById(listOf(receiverId, replierId)).associateBy(MaaUser::userId)
val userMap = userService.findByUsersId(listOf(receiverId, replierId))
val receiver = userMap[receiverId] ?: return
val replier = userMap.getOrDefault(replierId, MaaUser.UNKNOWN)
val replier = userMap.getOrDefault(replierId)

val targetMsg = parentComment?.message ?: copilot.doc?.title ?: ""
emailService.sendCommentNotification(receiver.email, receiver.userName, targetMsg, replier.userName, message)
Expand Down Expand Up @@ -160,20 +165,14 @@ class CommentsAreaService(
val pageable: Pageable = PageRequest.of(page, limit, Sort.by(toppingOrder, sortOrder))

// 主评论
val mainCommentsPage = if (!request.justSeeId.isNullOrBlank()) {
commentsAreaRepository.findByCopilotIdAndUploaderIdAndDeleteAndMainCommentIdExists(
request.copilotId,
request.justSeeId,
delete = false,
exists = false,
pageable = pageable,
)
} else {
commentsAreaRepository.findByCopilotIdAndDeleteAndMainCommentIdExists(
request.copilotId,
delete = false,
exists = false,
pageable = pageable,
val mainCommentsPage = mongoTemplate.findPage<CommentsArea>(pageable) {
if (!request.justSeeId.isNullOrBlank()) {
addCriteria(CommentsArea::id isEqualTo request.justSeeId)
}
addAndCriteria(
CommentsArea::copilotId isEqualTo request.copilotId,
CommentsArea::delete isEqualTo false,
CommentsArea::mainCommentId exists false,
)
}

Expand All @@ -186,15 +185,15 @@ class CommentsAreaService(

// 获取所有评论用户
val allUserIds = (mainCommentsPage + subCommentsList).map(CommentsArea::uploaderId).distinct()
val users = userRepository.findAllById(allUserIds).associateBy(MaaUser::userId)
val users = userService.findByUsersId(allUserIds)
val subCommentGroups = subCommentsList.groupBy(CommentsArea::mainCommentId)

// 转换主评论数据并填充用户名
val commentsInfos = mainCommentsPage.toList().map { mainComment ->
val subCommentsInfos = (subCommentGroups[mainComment.id] ?: emptyList()).map { c ->
buildSubCommentsInfo(c, users[c.uploaderId] ?: MaaUser.UNKNOWN)
buildSubCommentsInfo(c, users.getOrDefault(c.uploaderId))
}
buildMainCommentsInfo(mainComment, users[mainComment.uploaderId] ?: MaaUser.UNKNOWN, subCommentsInfos)
buildMainCommentsInfo(mainComment, users.getOrDefault(mainComment.uploaderId), subCommentsInfos)
}

return CommentsAreaInfo(
Expand Down
14 changes: 6 additions & 8 deletions src/main/kotlin/plus/maa/backend/service/CopilotService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ import org.springframework.data.mongodb.core.query.Update
import org.springframework.stereotype.Service
import org.springframework.util.Assert
import org.springframework.util.ObjectUtils
import plus.maa.backend.common.extensions.requireNotNull
import plus.maa.backend.common.utils.IdComponent
import plus.maa.backend.common.utils.converter.CopilotConverter
import plus.maa.backend.common.utils.requireNotNull
import plus.maa.backend.config.external.MaaCopilotProperties
import plus.maa.backend.controller.request.copilot.CopilotCUDRequest
import plus.maa.backend.controller.request.copilot.CopilotDTO
Expand All @@ -29,11 +29,9 @@ import plus.maa.backend.controller.response.copilot.CopilotPageInfo
import plus.maa.backend.repository.CommentsAreaRepository
import plus.maa.backend.repository.CopilotRepository
import plus.maa.backend.repository.RedisCache
import plus.maa.backend.repository.UserRepository
import plus.maa.backend.repository.entity.Copilot
import plus.maa.backend.repository.entity.Copilot.OperationGroup
import plus.maa.backend.repository.entity.Rating
import plus.maa.backend.repository.findByUsersId
import plus.maa.backend.service.level.ArkLevelService
import plus.maa.backend.service.model.RatingCache
import plus.maa.backend.service.model.RatingType
Expand Down Expand Up @@ -65,7 +63,7 @@ class CopilotService(
private val levelService: ArkLevelService,
private val redisCache: RedisCache,
private val idComponent: IdComponent,
private val userRepository: UserRepository,
private val userRepository: UserService,
private val commentsAreaRepository: CommentsAreaRepository,
private val properties: MaaCopilotProperties,
private val copilotConverter: CopilotConverter,
Expand Down Expand Up @@ -188,11 +186,11 @@ class CopilotService(
redisCache.setCache(viewCacheKey, vc, 60, TimeUnit.MINUTES)
}

val maaUser = userRepository.findByUserId(copilot.uploaderId!!)
val maaUser = userRepository.findByUserIdOrDefault(copilot.uploaderId!!)
return formatCopilot(
copilot,
ratingService.findPersonalRatingOfCopilot(userIdOrIpAddress, id),
maaUser!!.userName,
maaUser.userName,
commentsAreaRepository.countByCopilotIdAndDelete(copilot.copilotId!!, false),
)
}
Expand Down Expand Up @@ -325,7 +323,7 @@ class CopilotService(

// 填充前端所需信息
val copilotIds = copilots.map { it.copilotId!! }.toSet()
val maaUsers = userRepository.findByUsersId(copilots.map { it.uploaderId!! }.toList())
val maaUsers = userRepository.findByUsersId(copilots.map { it.uploaderId!! })
val commentsCount = commentsAreaRepository.findByCopilotIdInAndDelete(copilotIds, false).groupBy {
it.copilotId
}.mapValues { it.value.size.toLong() }
Expand All @@ -336,7 +334,7 @@ class CopilotService(
formatCopilot(
copilot,
null,
maaUsers[copilot.uploaderId]!!.userName,
maaUsers.getOrDefault(copilot.uploaderId!!).userName,
commentsCount[copilot.copilotId] ?: 0,
)
}.toList()
Expand Down
14 changes: 5 additions & 9 deletions src/main/kotlin/plus/maa/backend/service/CopilotSetService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -18,16 +18,11 @@ import plus.maa.backend.controller.request.copilotset.CopilotSetUpdateReq
import plus.maa.backend.controller.response.copilotset.CopilotSetPageRes
import plus.maa.backend.controller.response.copilotset.CopilotSetRes
import plus.maa.backend.repository.CopilotSetRepository
import plus.maa.backend.repository.UserRepository
import plus.maa.backend.repository.entity.CopilotSet
import plus.maa.backend.repository.entity.MaaUser
import plus.maa.backend.repository.findByUsersId
import plus.maa.backend.service.model.CopilotSetStatus
import java.time.LocalDateTime
import java.util.regex.Pattern

private val log = KotlinLogging.logger { }

/**
* @author dragove
* create on 2024-01-01
Expand All @@ -37,9 +32,10 @@ class CopilotSetService(
private val idComponent: IdComponent,
private val converter: CopilotSetConverter,
private val repository: CopilotSetRepository,
private val userRepository: UserRepository,
private val userService: UserService,
private val mongoTemplate: MongoTemplate,
) {
private val log = KotlinLogging.logger { }
private val defaultSort: Sort = Sort.by("id").descending()

/**
Expand Down Expand Up @@ -140,20 +136,20 @@ class CopilotSetService(
)
}
val userIds = copilotSets.map { obj: CopilotSet -> obj.creatorId }.distinct().toList()
val userById = userRepository.findByUsersId(userIds)
val userById = userService.findByUsersId(userIds)
return CopilotSetPageRes(
copilotSets.hasNext(),
copilotSets.totalPages,
copilotSets.totalElements,
copilotSets.map { cs: CopilotSet ->
val user = userById.getOrDefault(cs.creatorId, MaaUser.UNKNOWN)
val user = userById.getOrDefault(cs.creatorId)
converter.convert(cs, user.userName)
}.toList(),
)
}

fun get(id: Long): CopilotSetRes = repository.findById(id).map { copilotSet: CopilotSet ->
val userName = (userRepository.findByUserId(copilotSet.creatorId) ?: MaaUser.UNKNOWN).userName
val userName = userService.findByUserIdOrDefault(copilotSet.creatorId).userName
converter.convertDetail(copilotSet, userName)
}.orElseThrow { IllegalArgumentException("作业不存在") }
}
12 changes: 12 additions & 0 deletions src/main/kotlin/plus/maa/backend/service/UserService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -212,4 +212,16 @@ class UserService(
// 发送验证码
emailService.sendVCode(regDTO.email)
}

fun findByUserIdOrDefault(id: String) = userRepository.findByUserId(id) ?: MaaUser.UNKNOWN

fun findByUsersId(ids: Iterable<String>): UserDict {
return userRepository.findAllById(ids).let(::UserDict)
}

class UserDict(users: List<MaaUser>) {
private val userMap = users.associateBy { it.userId }
operator fun get(id: String): MaaUser? = userMap[id]
fun getOrDefault(id: String) = get(id) ?: MaaUser.UNKNOWN
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import io.github.oshai.kotlinlogging.KotlinLogging
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import org.springframework.web.reactive.function.client.WebClient
import plus.maa.backend.common.utils.awaitString
import plus.maa.backend.common.extensions.awaitString
import plus.maa.backend.repository.entity.gamedata.ArkActivity
import plus.maa.backend.repository.entity.gamedata.ArkCharacter
import plus.maa.backend.repository.entity.gamedata.ArkCrisisV2Info
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ import org.springframework.data.domain.Pageable
import org.springframework.stereotype.Service
import org.springframework.web.reactive.function.client.WebClient
import org.springframework.web.util.DefaultUriBuilderFactory
import plus.maa.backend.common.utils.awaitString
import plus.maa.backend.common.extensions.awaitString
import plus.maa.backend.common.extensions.lazySuspend
import plus.maa.backend.common.utils.converter.ArkLevelConverter
import plus.maa.backend.common.utils.lazySuspend
import plus.maa.backend.config.external.MaaCopilotProperties
import plus.maa.backend.controller.response.copilot.ArkLevelInfo
import plus.maa.backend.repository.ArkLevelRepository
Expand Down

0 comments on commit ead5880

Please sign in to comment.