95 lines
2.6 KiB
JavaScript
95 lines
2.6 KiB
JavaScript
import { openDB } from 'idb';
|
|
|
|
const DB_NAME = 'myplayer';
|
|
const STORE_NAME = 'historyMessages';
|
|
|
|
//初始化数据库
|
|
const initDB = async () => {
|
|
try {
|
|
// 打开数据库,如果不存在则会创建一个新的数据库
|
|
const db = await openDB('myplayer', 4, {
|
|
// 数据库升级回调
|
|
upgrade(db) {
|
|
console.log('数据库升级中...');
|
|
// 创建对象存储 groupHistoryMessages
|
|
if (!db.objectStoreNames.contains('groupHistoryMessages')) {
|
|
db.createObjectStore('groupHistoryMessages');
|
|
}
|
|
// 创建对象存储 historyMessages
|
|
if (!db.objectStoreNames.contains('historyMessages')) {
|
|
db.createObjectStore('historyMessages');
|
|
}
|
|
},
|
|
});
|
|
|
|
console.log('数据库初始化成功!');
|
|
// 在这里可以对数据库进行其他操作,例如读取或写入数据
|
|
} catch (error) {
|
|
console.error('初始化 IndexedDB 时发生错误:', error);
|
|
}
|
|
};
|
|
|
|
|
|
|
|
|
|
// 打开数据库
|
|
const getDB = async () => {
|
|
return openDB(DB_NAME, 4, {
|
|
upgrade(db) {
|
|
if (!db.objectStoreNames.contains(STORE_NAME)) {
|
|
db.createObjectStore(STORE_NAME); // 使用 id 作为 key
|
|
}
|
|
},
|
|
});
|
|
};
|
|
|
|
// 存储消息(追加到历史记录中)
|
|
const saveMessages = async (id, messages) => {
|
|
const db = await getDB();
|
|
try {
|
|
// 读取现有的历史消息
|
|
const existingMessages = await loadMessages(id);
|
|
|
|
// 确保 existingMessages 是一个数组
|
|
const newMessages = Array.isArray(existingMessages) ? existingMessages : [];
|
|
|
|
// 将当前消息追加到历史消息中
|
|
const updatedMessages = [...newMessages, ...messages]; // 将新消息追加到历史消息数组中
|
|
|
|
// 保存更新后的历史消息
|
|
await db.put(STORE_NAME, updatedMessages, id);
|
|
} catch (error) {
|
|
console.error('Error saving messages:', error);
|
|
}
|
|
};
|
|
|
|
// 获取消息
|
|
const loadMessages = async (id) => {
|
|
const db = await getDB();
|
|
try {
|
|
const messages = await db.get(STORE_NAME, id);
|
|
return messages || []; // 如果没有消息,返回空数组
|
|
} catch (error) {
|
|
console.error('Error loading messages:', error);
|
|
return [];
|
|
}
|
|
};
|
|
|
|
// 删除消息
|
|
const deleteMessages = async (id,messages) => {
|
|
const db = await getDB();
|
|
try {
|
|
if(messages.length === 0){
|
|
console.log('删除后没有消息了');
|
|
await db.delete(STORE_NAME, id);
|
|
}else{
|
|
console.log('删除后还有消息')
|
|
console.log(messages)
|
|
await db.put(STORE_NAME, messages, id);
|
|
}
|
|
} catch (error) {
|
|
console.error('Error deleting messages:', error);
|
|
}
|
|
};
|
|
|
|
export { saveMessages, loadMessages, deleteMessages, initDB }; |