DEVELOPMENT ENVIRONMENT

~liljamo/tixe

tixe/api/tags.go -rw-r--r-- 1.8 KiB
cbbeec42Jonni Liljamo docs: update README 10 months ago
                                                                                
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
/*
 * Copyright (C) 2023 Jonni Liljamo <jonni@liljamo.com>
 *
 * This file is licensed under AGPL-3.0-or-later, see NOTICE and LICENSE for
 * more information.
 */
package api

import (
	"context"
	"log"
	"net/http"
	"tixe/db"
	"tixe/types"

	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"github.com/oklog/ulid/v2"
)

type postTagsNew struct {
	Tag string `form:"tag"`
}

func TagsNew(c *gin.Context) {
	data := &postTagsNew{}
	if err := c.Bind(data); err != nil {
		log.Printf("[tixe/api] ERROR: Could not bind new tag data: %v", err)
		c.String(http.StatusBadRequest, "Could not bind new tag data")
		return;
	}

	session := sessions.Default(c)
	user := session.Get("user").(types.User)

	tagId := ulid.Make().String()

	_, err := db.PgPool.Exec(context.Background(),
		"INSERT INTO tags(id, user_id, tag) VALUES($1, $2, $3)", tagId, user.Id, data.Tag)
	if err != nil {
		log.Printf("[tixe/api] ERROR: Could not create new tag entry in database: %v", err)
		c.String(http.StatusInternalServerError, "Could not create new tag entry in database!")
		return;
	}

	c.Redirect(http.StatusFound, "/tags")
}

type postTagsDelete struct {
	Id string `form:"id"`
}

func TagsDelete(c *gin.Context) {
	data := &postTagsDelete{}
	if err := c.Bind(data); err != nil {
		log.Printf("[tixe/api] ERROR: Could not bind delete tag data: %v", err)
		c.String(http.StatusBadRequest, "Could not bind delete tag data")
		return;
	}

	session := sessions.Default(c)
	user := session.Get("user").(types.User)

	_, err := db.PgPool.Exec(context.Background(),
		"DELETE FROM tags WHERE id = $1 AND user_id = $2", data.Id, user.Id)
	if err != nil {
		log.Printf("[tixe/api] ERROR: Could not delete tag entry from database: %v", err)
		c.String(http.StatusInternalServerError, "Could not delete tag entry from database!")
		return;
	}

	c.Redirect(http.StatusFound, "/tags")
}