javascript 代碼實現CRUD, 业务需求 user表, gamelist表, 賽局表,MySQL用于持久化数据,Redis用于缓存和JWT。
时间: 2024-09-09 22:07:57 浏览: 44
一个简单好用的redis缓存图形化管理工具,包含redis的5种数据类型的CRUD操作
在JavaScript中,尤其是Node.js环境中,我们可以使用Express框架和一些数据库操作库(如mysql2和redis)来实现CRUD操作。以下是简化的示例:
首先,安装必要的依赖:
```bash
npm install express mysql2 redis jsonwebtoken body-parser cors
```
然后创建Express应用,并连接MySQL和Redis:
```javascript
const express = require('express');
const mysql = require('mysql2/promise');
const redis = require('redis');
const jwt = require('jsonwebtoken');
const bodyParser = require('body-parser');
// MySQL配置
const mysqlConfig = {
host: 'your_host',
user: 'your_user',
password: 'your_password',
database: 'your_database'
};
// Redis配置
const redisClient = redis.createClient({
host: 'your_redis_host',
port: your_redis_port
});
app.use(bodyParser.json());
app.use(cors());
// 连接MySQL
async function connectToDB() {
try {
await mysql.createPool(mysqlConfig);
} catch (error) {
console.error('Error connecting to MySQL:', error);
}
}
connectToDB();
// CRUD操作示例
// 创建用户 (Create)
app.post('/api/users', async (req, res) => {
// 数据验证
const { name, email } = req.body;
if (!name || !email) return res.status(400).json({ error: 'Missing required fields' });
const sql = 'INSERT INTO users (name, email) VALUES (?, ?)';
const [result] = await pool.query(sql, [name, email]);
// 如果成功,返回新用户的ID或JWT
res.status(201).json(result.insertId);
});
// 查询用户列表 (Read - All)
app.get('/api/users', async (req, res) => {
const sql = 'SELECT * FROM users';
const [data] = await pool.query(sql);
res.json(data);
});
// 更新用户 (Update)
app.put('/api/users/:id', async (req, res) => {
const { id } = req.params;
const { name, email } = req.body;
if (!id || !name || !email) return res.status(400).json({ error: 'Invalid request data' });
const sql = 'UPDATE users SET name = ?, email = ? WHERE id = ?';
const result = await pool.query(sql, [name, email, id]);
res.json({ message: 'User updated', affectedRows: result.affectedRows });
});
// 删除用户 (Delete)
app.delete('/api/users/:id', async (req, res) => {
const { id } = req.params;
if (!id) return res.status(400).json({ error: 'Missing user ID' });
const sql = 'DELETE FROM users WHERE id = ?';
const result = await pool.query(sql, [id]);
res.json({ message: 'User deleted', affectedRows: result.affectedRows });
});
// 使用Redis作为JWT缓存
const cache = {};
app.get('/api/auth/token', async (req, res) => {
const token = req.query.token;
if (!token) return res.status(400).json({ error: 'Token not provided' });
if (cache[token]) {
return res.json(cache[token]);
}
// 实际上从数据库验证JWT并获取数据,这里仅作示例
const jwtData = { username: 'John Doe' }; // Assume validated JWT has this data
const decoded = jwt.verify(token, 'secret_key');
cache[token] = decoded; // Cache the JWT for some time
res.json(decoded);
});
```
阅读全文