-
Notifications
You must be signed in to change notification settings - Fork 0
/
userManager.ts
103 lines (85 loc) · 2.45 KB
/
userManager.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import { type Client, createClient } from "edgedb";
import e from "./dbschema/edgeql-js";
import ServerMessage from "./serverMessage";
export type User = {
id: string;
name?: string;
createdAt: number;
characterTraits: string[];
};
class UserManager {
client: Client;
constructor() {
const baseClient = createClient();
this.client = baseClient.withConfig({ allow_user_specified_id: true });
}
async createUser(user: User) {
const query = e.insert(e.User, {
createdAt: e.datetime(new Date(user.createdAt).toISOString()),
characterTraits: [],
name: user.name,
id: user.id,
messages: null,
});
const res = await query.run(this.client);
if (!res) throw new Error("User could not be created");
}
async updateUser(user: Partial<User> & { id: string }) {
const query = e.update(e.User, () => ({
filter_single: { id: user.id },
set: {
name: user.name,
characterTraits: user.characterTraits,
},
}));
const res = await query.run(this.client);
if (!res) throw new Error("User could not be updated");
}
async getOrCreateUser(userId: string, userName?: string) {
const query = e.select(e.User, () => ({
id: true,
filter_single: { id: userId },
}));
const result = await query.run(this.client);
if (result?.id !== userId) {
await this.createUser({
id: userId,
characterTraits: [],
createdAt: Date.now(),
name: userName,
});
}
return userId;
}
async getAllUsers() {
const query = e.select(e.User, () => ({
id: true,
name: true,
createdAt: true,
characterTraits: true,
messages: { content: true, createdAt: true, role: true, topic: true },
}));
const results = await query.run(this.client);
return results;
}
async deleteAllUsersExcept(userIds: string[]) {
const query = e.params({ ids: e.array(e.uuid) }, ({ ids }) =>
e.delete(e.User, (user) => ({
filter: e.op(user.id, "not in", e.array_unpack(ids)),
}))
);
return await query.run(this.client, {
ids: userIds,
});
}
async addMessageToHistory(userId: string, serverMessage: ServerMessage) {
const query = e.update(e.User, () => ({
filter_single: { id: userId },
set: {
messages: { "+=": e.insert(e.Message, serverMessage.toDBMessage()) },
},
}));
await query.run(this.client);
}
}
export default UserManager;