ORM

56 阅读1分钟
// npm i mysql2
// npm i express
// npm i js-yaml
import fs from 'node:fs';
import jsyaml from 'js-yaml';
import mysql2 from 'mysql2/promise';
import express from 'express';

const yaml = fs.readFileSync('./db.config.yaml', 'utf8');
const config = jsyaml.load(yaml);

const sql = await mysql2.createConnection(config.db)
const app = express();
app.use(express.json());

// 查询全部接口
app.get('/', async (req, res) => {
    const [data] = await sql.query('SELECT * FROM user');
    res.send(data);
});

app.get('/user/:id', async (req, res) => {
    const [data] = await sql.query('SELECT * FROM user WHERE id = ?', [req.params.id]);
    res.send(data);
});

// 新增接口
app.post('/create', async (req, res) => {
    const { name, age, address } = req.body;
    await sql.query('INSERT INTO user (name, age, address) VALUES (?, ?, ?)', [name, age, address]);
    res.send({ok: 1});
});

// 修改接口
app.post('/update', async (req, res) => {
    const { name, age, address, id } = req.body;
    await sql.query('UPDATE user SET name = ?, age = ?, address = ? WHERE id = ?', [name, age, address, id]);
    res.send({ok: 1});
})

// 删除接口
app.post('/delete', async (req, res) => {
    const { id } = req.body;
    await sql.query('DELETE FROM user WHERE id =?', [id]);
    res.send({ok: 1});
})


app.listen(3000, () => {
  console.log('Server is running on port 3000');
});