File size: 1,399 Bytes
cfb0fa4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { v } from 'convex/values';
import { mutation, query } from './_generated/server';

export const list = query({
	args: { userId: v.string() },
	handler: async (ctx, { userId }) => {
		return await ctx.db
			.query('conversations')
			.withIndex('by_userId', (q) => q.eq('userId', userId))
			.collect();
	}
});

export const get = query({
	args: { chatId: v.string() },
	handler: async (ctx, { chatId }) => {
		return await ctx.db
			.query('conversations')
			.withIndex('by_chatId', (q) => q.eq('chatId', chatId))
			.first();
	}
});

export const save = mutation({
	args: {
		chatId: v.string(),
		userId: v.string(),
		title: v.string(),
		data: v.any()
	},
	handler: async (ctx, { chatId, userId, title, data }) => {
		const existing = await ctx.db
			.query('conversations')
			.withIndex('by_chatId', (q) => q.eq('chatId', chatId))
			.first();

		if (existing) {
			await ctx.db.patch(existing._id, { title, data, updatedAt: Date.now() });
		} else {
			await ctx.db.insert('conversations', {
				chatId,
				userId,
				title,
				data,
				updatedAt: Date.now()
			});
		}
	}
});

export const remove = mutation({
	args: { chatId: v.string() },
	handler: async (ctx, { chatId }) => {
		const existing = await ctx.db
			.query('conversations')
			.withIndex('by_chatId', (q) => q.eq('chatId', chatId))
			.first();

		if (existing) {
			await ctx.db.delete(existing._id);
		}
	}
});