rentease-backend/controllers/regionController.js

102 lines
2.6 KiB
JavaScript
Raw Normal View History

2026-03-02 12:36:41 +00:00
const { Region } = require('../models');
// 格式化时间(考虑时区,转换为北京时间)
const formatDate = (date) => {
if (!date) return null;
// 创建一个新的Date对象加上8小时的时区偏移
const beijingDate = new Date(date.getTime() + 8 * 60 * 60 * 1000);
return beijingDate.toISOString().split('T')[0];
};
// 格式化区域数据
const formatRegionData = (region) => {
return {
...region.toJSON(),
2026-03-03 15:36:48 +00:00
createTime: formatDate(region.createTime),
updateTime: formatDate(region.updateTime)
2026-03-02 12:36:41 +00:00
};
};
// 获取所有区域
const getAllRegions = async (req, res) => {
try {
2026-03-03 15:36:48 +00:00
const regions = await Region.findAll({
where: { isDeleted: 0 }
});
2026-03-02 12:36:41 +00:00
const formattedRegions = regions.map(formatRegionData);
res.status(200).json(formattedRegions);
} catch (error) {
res.status(500).json({ error: error.message });
}
};
// 获取单个区域
const getRegionById = async (req, res) => {
try {
const { id } = req.params;
2026-03-03 15:36:48 +00:00
const region = await Region.findOne({
where: { id, isDeleted: 0 }
});
2026-03-02 12:36:41 +00:00
if (!region) {
return res.status(404).json({ error: '区域不存在' });
}
const formattedRegion = formatRegionData(region);
res.status(200).json(formattedRegion);
} catch (error) {
res.status(500).json({ error: error.message });
}
};
// 创建区域
const createRegion = async (req, res) => {
try {
const { name, description } = req.body;
const region = await Region.create({ name, description });
res.status(201).json(region);
} catch (error) {
res.status(500).json({ error: error.message });
}
};
// 更新区域
const updateRegion = async (req, res) => {
try {
const { id } = req.params;
const { name, description } = req.body;
2026-03-03 15:36:48 +00:00
const region = await Region.findOne({
where: { id, isDeleted: 0 }
});
2026-03-02 12:36:41 +00:00
if (!region) {
return res.status(404).json({ error: '区域不存在' });
}
await region.update({ name, description });
res.status(200).json(region);
} catch (error) {
res.status(500).json({ error: error.message });
}
};
2026-03-03 15:36:48 +00:00
// 删除区域(软删除)
2026-03-02 12:36:41 +00:00
const deleteRegion = async (req, res) => {
try {
const { id } = req.params;
2026-03-03 15:36:48 +00:00
const region = await Region.findOne({
where: { id, isDeleted: 0 }
});
2026-03-02 12:36:41 +00:00
if (!region) {
return res.status(404).json({ error: '区域不存在' });
}
2026-03-03 15:36:48 +00:00
await region.update({ isDeleted: 1 });
2026-03-02 12:36:41 +00:00
res.status(200).json({ message: '区域删除成功' });
} catch (error) {
res.status(500).json({ error: error.message });
}
};
module.exports = {
getAllRegions,
getRegionById,
createRegion,
updateRegion,
deleteRegion
};