// app.js
const express = require('express');
const mongoose = require('mongoose');
const asyncHandler = require('./utils/asyncHandler');
const {
NotFoundError,
BadRequestError,
ValidationError,
} = require('./utils/errors');
const errorHandler = require('./middleware/errorHandler');
const app = express();
// 中间件
app.use(express.json());
// 用户模型(示例)
const User = mongoose.model('User', {
name: String,
email: String,
age: Number,
});
// 路由示例
app.get('/api/users', asyncHandler(async (req, res) => {
const users = await User.find();
res.json({
success: true,
data: users,
});
}));
app.get('/api/users/:id', asyncHandler(async (req, res) => {
const user = await User.findById(req.params.id);
if (!user) {
throw new NotFoundError('User not found');
}
res.json({
success: true,
data: user,
});
}));
app.post('/api/users', asyncHandler(async (req, res) => {
const { name, email, age } = req.body;
// 验证
if (!name || !email) {
throw new ValidationError('Name and email are required');
}
if (age && (age < 0 || age > 150)) {
throw new ValidationError('Age must be between 0 and 150');
}
const user = await User.create({ name, email, age });
res.status(201).json({
success: true,
data: user,
});
}));
app.put('/api/users/:id', asyncHandler(async (req, res) => {
const { name, email, age } = req.body;
const user = await User.findByIdAndUpdate(
req.params.id,
{ name, email, age },
{ new: true, runValidators: true }
);
if (!user) {
throw new NotFoundError('User not found');
}
res.json({
success: true,
data: user,
});
}));
app.delete('/api/users/:id', asyncHandler(async (req, res) => {
const user = await User.findByIdAndDelete(req.params.id);
if (!user) {
throw new NotFoundError('User not found');
}
res.json({
success: true,
message: 'User deleted successfully',
});
}));
// 404处理
app.use('*', (req, res) => {
throw new NotFoundError(`Route ${req.originalUrl} not found`);
});
// 全局错误处理(必须在最后)
app.use(errorHandler);
// 启动服务器
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});