File size: 1,171 Bytes
fc15a4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { collections } from '$lib/server/database.js';
import { error } from '@sveltejs/kit';
import { ObjectId } from 'mongodb';
import { nanoid } from 'nanoid';

export async function POST({ params, url, locals }) {
	const conversation = await collections.conversations.findOne({
		_id: new ObjectId(params.id),
		sessionId: locals.sessionId
	});

	if (!conversation) {
		throw error(404, 'Conversation not found');
	}

	const shares = conversation.shares || [];

	const existingShare = shares.find((share) => share.msgCount === conversation.messages.length);

	if (existingShare) {
		return new Response(
			JSON.stringify({
				url: url.origin + `/r/${existingShare.id}`
			}),
			{ headers: { 'Content-Type': 'application/json' } }
		);
	}

	const share = {
		id: nanoid(7),
		msgCount: conversation.messages.length
	};

	await collections.conversations.updateOne(
		{
			_id: conversation._id
		},
		{
			$set: {
				shares: [...shares, share],
				updatedAt: new Date()
			}
		}
	);

	return new Response(
		JSON.stringify({
			url: url.origin.replace('huggingface.co', 'hf.co') + `/r/${share.id}`
		}),
		{ headers: { 'Content-Type': 'application/json' } }
	);
}