Skip to content

Commit e75f950

Browse files
committed
chore: add server with sqlite
1 parent ba6b90f commit e75f950

File tree

8 files changed

+2004
-132
lines changed

8 files changed

+2004
-132
lines changed

.idea/jsLibraryMappings.xml

+6
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

server/app.js

+3-25
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
const express = require('express');
2-
const mongoose = require('mongoose');
32
const bodyParser = require('body-parser');
43
const cors = require('cors');
4+
const notesRouter = require('./routes/notes');
55

66
const app = express();
77
const PORT = process.env.PORT || 9999;
@@ -10,32 +10,10 @@ const PORT = process.env.PORT || 9999;
1010
app.use(cors());
1111
app.use(bodyParser.json());
1212

13-
// 连接 MongoDB
14-
mongoose.connect('mongodb://localhost:27017/flomo', {
15-
useNewUrlParser: true,
16-
useUnifiedTopology: true,
17-
});
18-
19-
// 定义笔记模型
20-
const NoteSchema = new mongoose.Schema({
21-
content: String,
22-
createdAt: { type: Date, default: Date.now },
23-
});
24-
25-
const Note = mongoose.model('Note', NoteSchema);
26-
2713
// API 路由
28-
app.get('/api/notes', async (req, res) => {
29-
const notes = await Note.find().sort({ createdAt: -1 });
30-
res.json(notes);
31-
});
32-
33-
app.post('/api/notes', async (req, res) => {
34-
const newNote = new Note({ content: req.body.content });
35-
await newNote.save();
36-
res.json(newNote);
37-
});
14+
app.use('/api/notes', notesRouter);
3815

16+
// 启动服务器
3917
app.listen(PORT, () => {
4018
console.log(`Server is running on port ${PORT}`);
4119
});

server/db/init.sql

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
-- server/db/init.sql
2+
CREATE TABLE IF NOT EXISTS notes (
3+
id INTEGER PRIMARY KEY AUTOINCREMENT,
4+
title TEXT NOT NULL,
5+
content TEXT NOT NULL,
6+
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
7+
);

server/db/notes.db

12 KB
Binary file not shown.

server/models/Note.js

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
const sqlite3 = require('sqlite3').verbose();
2+
const db = new sqlite3.Database('./db/notes.db');
3+
4+
class Note {
5+
// 获取所有笔记
6+
static getAll(callback) {
7+
db.all('SELECT * FROM notes ORDER BY created_at DESC', callback);
8+
}
9+
10+
// 创建笔记
11+
static create(title, content, callback) {
12+
db.run(
13+
'INSERT INTO notes (title, content) VALUES (?, ?)',
14+
[title, content],
15+
function (err) {
16+
if (err) return callback(err);
17+
callback(null, this.lastID);
18+
}
19+
);
20+
}
21+
22+
// 删除笔记
23+
static delete(id, callback) {
24+
db.run('DELETE FROM notes WHERE id = ?', [id], callback);
25+
}
26+
}
27+
28+
module.exports = Note;

0 commit comments

Comments
 (0)