database.js 801 B

123456789101112131415161718192021222324252627282930
  1. const sqlite3 = require('sqlite3')
  2. const { promisify } = require('util')
  3. const config = require('../config.js')
  4. const db = new sqlite3.Database(config.db.file)
  5. // 转换为Promise接口
  6. db.runAsync = promisify(db.run)
  7. db.allAsync = promisify(db.all)
  8. // 初始化数据库
  9. export async function initDB() {
  10. await db.runAsync(config.db.messages_table)
  11. await db.runAsync('PRAGMA journal_mode = WAL;')
  12. }
  13. // 消息存储
  14. export async function saveMessage(packet, clientId) {
  15. return db.runAsync(
  16. 'INSERT INTO messages (topic, payload, client_id) VALUES (?, ?, ?)',
  17. [packet.topic, packet.payload.toString(), clientId]
  18. )
  19. }
  20. // 消息查询
  21. export async function getMessages(limit = 100) {
  22. return db.allAsync(
  23. 'SELECT * FROM messages ORDER BY created_at DESC LIMIT ?',
  24. [limit]
  25. )
  26. }