forked from riwigefi/light-gpt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.ts
76 lines (61 loc) · 2.02 KB
/
db.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import Dexie from 'dexie';
interface Topic {
id: string;
name: string;
createdAt: number;
}
interface Conversation {
id: string;
role: string;
content: string;
topicId: string;
createdAt: number;
}
class ChatDatabase extends Dexie {
topics: Dexie.Table<Topic, string>;
conversations: Dexie.Table<Conversation, number>;
constructor() {
super('ChatDatabase');
this.version(1).stores({
topics: 'id, name',
conversations: 'id, role, content, topicId, createdAt',
});
this.topics = this.table('topics');
this.conversations = this.table('conversations');
}
}
export class ChatService {
private db: ChatDatabase;
constructor() {
this.db = new ChatDatabase();
}
async getTopics(): Promise<Topic[]> {
const topics = await this.db.topics.toArray();
topics.sort((a, b) => b.createdAt - a.createdAt);
return topics;
}
async getConversationsByTopicId(topicId: string): Promise<Conversation[]> {
const conversations = await this.db.conversations
.where('topicId')
.equals(topicId)
.toArray();
conversations.sort((a, b) => a.createdAt - b.createdAt);
return conversations;
}
async addConversation(conversation: Conversation): Promise<number> {
return await this.db.conversations.add(conversation);
}
async deleteConversationById(conversationId: string): Promise<void> {
await this.db.conversations.where('id').equals(conversationId).delete();
}
async addTopic(topic: Topic): Promise<string> {
return await this.db.topics.add(topic);
}
async deleteTopicById(topicId: string): Promise<void> {
await this.db.topics.where('id').equals(topicId).delete();
await this.db.conversations.where('topicId').equals(topicId).delete();
}
async updateTopicNameById(topicId: string, name: string): Promise<void> {
await this.db.topics.update(topicId, { name });
}
}