-
Notifications
You must be signed in to change notification settings - Fork 4
/
+page.server.ts
51 lines (41 loc) · 1.48 KB
/
+page.server.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
import type { PageServerLoad, Actions, RequestEvent } from '../$types';
import { tursoClient } from '$lib/server/turso';
import { questions, choices, votes } from '../../../drizzle/schema';
import { eq } from 'drizzle-orm';
export const load: PageServerLoad = async ({ cookies }) => {
const userId = cookies.get('userid');
if (!userId) {
cookies.set('userid', crypto.randomUUID(), { path: '/' });
}
};
export const actions = {
default: async ({ request }: RequestEvent) => {
const data = await request.formData();
const questionDeleteId: string = data.get('question_delete_id') as unknown as string;
const db = tursoClient();
// get question
const pollQuestion = await db.query.questions.findFirst({
where: (questions, { eq }) => eq(questions.deleteId, questionDeleteId),
with: {
choices: {
with: {
votes: true
}
}
}
});
if (pollQuestion === undefined) {
return { ok: false, message: 'Unknown delete id!' };
}
if (pollQuestion.choices.length > 0) {
for (const choice of pollQuestion.choices) {
if (choice.votes.length) {
await db.delete(votes).where(eq(votes.choiceId, choice.id)).returning().all();
}
await db.delete(choices).where(eq(choices.id, choice.id)).run();
}
}
await db.delete(questions).where(eq(questions.id, pollQuestion.id)).returning().get();
return { ok: true, message: 'Poll deleted!' };
}
} satisfies Actions;