121 lines
3.3 KiB
Java

package com.designhub.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.designhub.entity.S3Config;
import com.designhub.mapper.S3ConfigMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* S3配置服务
*/
@Service
public class S3ConfigService {
@Autowired
private S3ConfigMapper s3ConfigMapper;
/**
* 获取激活的S3配置
*/
public S3Config getActiveConfig() {
return s3ConfigMapper.getActiveConfig();
}
/**
* 获取所有S3配置
*/
public List<S3Config> getAllConfigs() {
LambdaQueryWrapper<S3Config> wrapper = new LambdaQueryWrapper<>();
wrapper.orderByDesc(S3Config::getIsActive)
.orderByDesc(S3Config::getCreateTime);
return s3ConfigMapper.selectList(wrapper);
}
/**
* 根据ID获取S3配置
*/
public S3Config getConfigById(Long id) {
return s3ConfigMapper.selectById(id);
}
/**
* 创建S3配置
*/
@Transactional
public S3Config createConfig(S3Config config) {
// 如果新配置设置为激活,则将其他配置设为未激活
if (config.getIsActive() != null && config.getIsActive()) {
deactivateAllConfigs();
}
s3ConfigMapper.insert(config);
return config;
}
/**
* 更新S3配置
*/
@Transactional
public S3Config updateConfig(Long id, S3Config config) {
S3Config existingConfig = s3ConfigMapper.selectById(id);
if (existingConfig == null) {
throw new RuntimeException("S3配置不存在");
}
// 如果新配置设置为激活,则将其他配置设为未激活
if (config.getIsActive() != null && config.getIsActive()) {
deactivateAllConfigs();
}
config.setId(id);
s3ConfigMapper.updateById(config);
return s3ConfigMapper.selectById(id);
}
/**
* 删除S3配置
*/
public void deleteConfig(Long id) {
S3Config config = s3ConfigMapper.selectById(id);
if (config != null && config.getIsActive()) {
throw new RuntimeException("无法删除激活的配置,请先激活其他配置");
}
s3ConfigMapper.deleteById(id);
}
/**
* 激活指定的S3配置
*/
@Transactional
public void activateConfig(Long id) {
S3Config config = s3ConfigMapper.selectById(id);
if (config == null) {
throw new RuntimeException("S3配置不存在");
}
// 将其他配置设为未激活
deactivateAllConfigs();
// 激活当前配置
config.setIsActive(true);
s3ConfigMapper.updateById(config);
}
/**
* 将所有配置设为未激活
*/
private void deactivateAllConfigs() {
LambdaQueryWrapper<S3Config> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(S3Config::getIsActive, true);
List<S3Config> activeConfigs = s3ConfigMapper.selectList(wrapper);
for (S3Config activeConfig : activeConfigs) {
activeConfig.setIsActive(false);
s3ConfigMapper.updateById(activeConfig);
}
}
}