|
@@ -0,0 +1,50 @@
|
|
|
|
|
+package com.ylx.moment.service.impl;
|
|
|
|
|
+
|
|
|
|
|
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
|
|
|
|
+import com.ylx.base.BaseServiceImpl;
|
|
|
|
|
+import com.ylx.moment.domain.MomentCollect;
|
|
|
|
|
+import com.ylx.moment.domain.dto.CustomerMomentDTO;
|
|
|
|
|
+import com.ylx.moment.mapper.MomentCollectMapper;
|
|
|
|
|
+import com.ylx.moment.service.MomentCollectService;
|
|
|
|
|
+import lombok.extern.slf4j.Slf4j;
|
|
|
|
|
+import org.springframework.dao.DuplicateKeyException;
|
|
|
|
|
+import org.springframework.stereotype.Service;
|
|
|
|
|
+import org.springframework.transaction.annotation.Transactional;
|
|
|
|
|
+
|
|
|
|
|
+@Slf4j
|
|
|
|
|
+@Service
|
|
|
|
|
+public class MomentCollectServiceImpl extends BaseServiceImpl<MomentCollectMapper, MomentCollect>
|
|
|
|
|
+ implements MomentCollectService {
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+ @Override
|
|
|
|
|
+ @Transactional(rollbackFor = Exception.class)
|
|
|
|
|
+ public boolean toggleCollect(CustomerMomentDTO dto) {
|
|
|
|
|
+ Long userId = this.getCurrentUserId();
|
|
|
|
|
+ Long momentId = dto.getMomentId();
|
|
|
|
|
+
|
|
|
|
|
+ try {
|
|
|
|
|
+ // 1. 尝试插入收藏记录
|
|
|
|
|
+ MomentCollect collect = new MomentCollect();
|
|
|
|
|
+ collect.setUserId(userId);
|
|
|
|
|
+ collect.setMomentId(momentId);
|
|
|
|
|
+ this.save(collect);
|
|
|
|
|
+
|
|
|
|
|
+ // 2. 插入成功,说明是【新增收藏】,主表收藏数 +1
|
|
|
|
|
+ this.baseMapper.incrementSaveCount(momentId, 1);
|
|
|
|
|
+ return true;
|
|
|
|
|
+
|
|
|
|
|
+ } catch (DuplicateKeyException e) {
|
|
|
|
|
+ // 3. 触发唯一索引冲突,说明【已经收藏过】,执行取消收藏
|
|
|
|
|
+ LambdaQueryWrapper<MomentCollect> wrapper = new LambdaQueryWrapper<>();
|
|
|
|
|
+ wrapper.eq(MomentCollect::getUserId, userId)
|
|
|
|
|
+ .eq(MomentCollect::getMomentId, momentId);
|
|
|
|
|
+ this.remove(wrapper);
|
|
|
|
|
+
|
|
|
|
|
+ // 4. 主表收藏数 -1
|
|
|
|
|
+ this.baseMapper.incrementSaveCount(momentId, -1);
|
|
|
|
|
+ return false;
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+}
|