rentease-backend/controllers/regionController.js

93 lines
2.4 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(),
createTime: formatDate(region.createTime)
};
};
// 获取所有区域
const getAllRegions = async (req, res) => {
try {
const regions = await Region.findAll();
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;
const region = await Region.findByPk(id);
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;
const region = await Region.findByPk(id);
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 });
}
};
// 删除区域
const deleteRegion = async (req, res) => {
try {
const { id } = req.params;
const region = await Region.findByPk(id);
if (!region) {
return res.status(404).json({ error: '区域不存在' });
}
await region.destroy();
res.status(200).json({ message: '区域删除成功' });
} catch (error) {
res.status(500).json({ error: error.message });
}
};
module.exports = {
getAllRegions,
getRegionById,
createRegion,
updateRegion,
deleteRegion
};