File size: 1,847 Bytes
e8410db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { json, type RequestEvent } from '@sveltejs/kit';
import { tokenIsAvailable } from '$lib/utils';
import { REACTION_EMOJIS } from "$lib/utils";
import prisma from '$lib/prisma';

/** @type {import('./$types').RequestHandler} */

export async function POST({ cookies, request } : RequestEvent) {
  const token = cookies.get('hf_access_token')
  if (!token) {
    return json({
      error: {
        token: "You must be logged"
      }
    }, { status: 401 })
  }

  const is_token_available = await tokenIsAvailable(token)
  if (!is_token_available) {
    return json({
      error: {
        token: "Invalid token"
      }
    }, { status: 401 })
  }

  const { emoji, gallery_id } = await request.json()

  if (!REACTION_EMOJIS.includes(emoji)) {
    return json({
      error: {
        emoji: "Invalid emoji"
      }
    }, { status: 400 })
  }

  if (!gallery_id ) {
    return json({
      error: {
        gallery_id: "Invalid gallery_id"
      }
    }, { status: 400 })
  }

  const gallery = await prisma.gallery.findUnique({
    where: {
      id: gallery_id
    }
  })

  if (!gallery) {
    return json({
      error: {
        gallery_id: "Gallery not found"
      }
    }, { status: 404 })
  }

  const reaction_exist = await prisma.reaction.findFirst({
    where: {
      galleryId: gallery_id,
      hf_user_id: is_token_available.sub,
      emoji
    }
  })

  if (reaction_exist) {
    await prisma.reaction.delete({
      where: {
        id: reaction_exist.id
      }
    })

    return json({
      success: true,
      delete: true,
      id: reaction_exist.id
    })
  }

  const new_reaction = await prisma.reaction.create({
    data: {
      emoji,
      galleryId: gallery_id,
      hf_user_id: is_token_available.sub
    }
  })

  return json({
    success: true,
    delete: false,
    id: new_reaction.id
  })
}