aboutsummaryrefslogtreecommitdiff
path: root/apps/web/app/api/store/helper.ts
blob: 17794a0b03d743b6a42378f4602de47d29e083f9 (plain) (blame)
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
import { z } from "zod";
import { db } from "@/server/db";
import { contentToSpace, space, storedContent } from "@repo/db/schema";
import { and, eq, inArray } from "drizzle-orm";
// import { LIMITS } from "@repo/shared-types";
// import { limit } from "@/app/actions/doers";
import { type AddFromAPIType } from "@repo/shared-types";

export const createMemoryFromAPI = async (input: {
	data: AddFromAPIType;
	userId: string;
}) => {
	// if (!(await limit(input.userId, input.data.type))) {
	// 	return {
	// 		success: false,
	// 		data: 0,
	// 		error: `You have exceeded the limit of ${LIMITS[input.data.type as keyof typeof LIMITS]} ${input.data.type}s.`,
	// 	};
	// }

	const vectorSaveResponse = await fetch(
		`${process.env.BACKEND_BASE_URL}/api/add`,
		{
			method: "POST",
			body: JSON.stringify({
				pageContent: input.data.pageContent,
				title: input.data.title.slice(0, 500),
				description: input.data.description.slice(0, 500),
				url: input.data.url,
				spaces: input.data.spaces,
				user: input.userId,
				type: input.data.type,
			}),
			headers: {
				"Content-Type": "application/json",
				Authorization: "Bearer " + process.env.BACKEND_SECURITY_KEY,
			},
		},
	);

	if (!vectorSaveResponse.ok) {
		const errorData = await vectorSaveResponse.text();
		console.error(errorData);
		return {
			success: false,
			data: 0,
			error: `Failed to save to vector store. Backend returned error: ${errorData}`,
		};
	}

	let contentId: number;

	const saveToDbUrl =
		(input.data.url.split("#supermemory-user-")[0] ?? input.data.url) +
		"#supermemory-user-" +
		input.userId;

	const noteId = new Date().getTime();

	// Insert into database
	try {
		const insertResponse = await db
			.insert(storedContent)
			.values({
				content: input.data.pageContent,
				title: input.data.title,
				description: input.data.description,
				url: saveToDbUrl,
				baseUrl: saveToDbUrl,
				image: input.data.image,
				savedAt: new Date(),
				userId: input.userId,
				type: input.data.type,
				noteId,
			})
			.returning({ id: storedContent.id });

		if (!insertResponse[0]?.id) {
			return {
				success: false,
				data: 0,
				error: "Failed to save to database",
			};
		}

		contentId = insertResponse[0].id;
	} catch (e) {
		const error = e as Error;
		console.log("Error: ", error.message);

		if (error.message.includes("D1_ERROR: UNIQUE constraint failed:")) {
			return {
				success: false,
				data: 0,
				error: "Content already exists",
			};
		}

		return {
			success: false,
			data: 0,
			error: "Failed to save to database with error: " + error.message,
		};
	}

	if (input.data.spaces.length > 0) {
		// Adding the many-to-many relationship between content and spaces
		const spaceData = await db
			.select()
			.from(space)
			.where(
				and(
					inArray(
						space.id,
						input.data.spaces.map((s) => parseInt(s)),
					),
					eq(space.user, input.userId),
				),
			)
			.all();

		await Promise.all(
			spaceData.map(async (s) => {
				await db
					.insert(contentToSpace)
					.values({ contentId: contentId, spaceId: s.id });

				await db.update(space).set({ numItems: s.numItems + 1 });
			}),
		);
	}

	try {
		if (!vectorSaveResponse.ok) {
			const resp = await vectorSaveResponse.text();
			return {
				success: false,
				data: 0,
				error: `Failed to save to vector store. Backend returned error: ${resp}`,
			};
		}

		await vectorSaveResponse.json();

		return {
			success: true,
			data: 1,
		};
	} catch (e) {
		return {
			success: false,
			data: 0,
			error: `Failed to save to vector store. Backend returned error: ${e as string}`,
		};
	}
};