feat: 实现成绩管理系统核心功能
添加响应工具、错误处理中间件和数据库模型 创建用户、学生、课程和成绩相关服务 实现管理员、教师和学生控制器的基本功能 重构路由处理并优化数据库查询
This commit is contained in:
60
backend/services/adminService.js
Normal file
60
backend/services/adminService.js
Normal file
@@ -0,0 +1,60 @@
|
||||
const db = require('../config/database');
|
||||
const bcrypt = require('bcryptjs');
|
||||
const User = require('../models/User');
|
||||
|
||||
class AdminService {
|
||||
static async getUsers(params) {
|
||||
const { page = 1, limit = 10, search = '', role = '' } = params;
|
||||
const offset = (page - 1) * limit;
|
||||
|
||||
let queryStr = 'SELECT id, name, role, class, created_at FROM users WHERE 1=1';
|
||||
let queryParams = [];
|
||||
|
||||
if (search) {
|
||||
queryStr += ' AND (id LIKE ? OR name LIKE ? OR class LIKE ?)';
|
||||
const searchTerm = `%${search}%`;
|
||||
queryParams.push(searchTerm, searchTerm, searchTerm);
|
||||
}
|
||||
|
||||
if (role) {
|
||||
queryStr += ' AND role = ?';
|
||||
queryParams.push(role);
|
||||
}
|
||||
|
||||
// Count
|
||||
const countSql = queryStr.replace('SELECT id, name, role, class, created_at', 'SELECT COUNT(*) as total');
|
||||
const countRows = await db.query(countSql, queryParams);
|
||||
const total = countRows[0].total;
|
||||
|
||||
// Data
|
||||
queryStr += ' ORDER BY created_at DESC LIMIT ? OFFSET ?';
|
||||
queryParams.push(parseInt(limit), parseInt(offset));
|
||||
|
||||
const users = await db.query(queryStr, queryParams);
|
||||
|
||||
return {
|
||||
data: users,
|
||||
pagination: {
|
||||
page: parseInt(page),
|
||||
limit: parseInt(limit),
|
||||
total,
|
||||
pages: Math.ceil(total / limit)
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
static async createUser(userData) {
|
||||
const { id } = userData;
|
||||
|
||||
// 检查 ID
|
||||
const existingUser = await User.findById(id);
|
||||
if (existingUser) {
|
||||
throw new Error('用户ID已存在');
|
||||
}
|
||||
|
||||
// 创建用户
|
||||
return await User.create(userData);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = AdminService;
|
||||
Reference in New Issue
Block a user