| 123456789101112131415161718192021222324252627282930 |
- const sqlite3 = require('sqlite3')
- const { promisify } = require('util')
- const config = require('../config.js')
- const db = new sqlite3.Database(config.db.file)
- // 转换为Promise接口
- db.runAsync = promisify(db.run)
- db.allAsync = promisify(db.all)
- // 初始化数据库
- export async function initDB() {
- await db.runAsync(config.db.messages_table)
- await db.runAsync('PRAGMA journal_mode = WAL;')
- }
- // 消息存储
- export async function saveMessage(packet, clientId) {
- return db.runAsync(
- 'INSERT INTO messages (topic, payload, client_id) VALUES (?, ?, ?)',
- [packet.topic, packet.payload.toString(), clientId]
- )
- }
- // 消息查询
- export async function getMessages(limit = 100) {
- return db.allAsync(
- 'SELECT * FROM messages ORDER BY created_at DESC LIMIT ?',
- [limit]
- )
- }
|