diff --git a/backend/controllers/template/template.go b/backend/controllers/template/template.go index f5a0b62..2b50d02 100644 --- a/backend/controllers/template/template.go +++ b/backend/controllers/template/template.go @@ -174,4 +174,36 @@ func Put(c *gin.Context) { } func Delete(c *gin.Context) { + // Get request data, with id, and user + id, err := strconv.Atoi(c.Param("id")) + if err != nil { + res.Error(c, err.Error(), http.StatusBadRequest) + return + } + + user, err := jwt.GetUser(c) + if err != nil { + res.NeedsToLogin(c) + return + } + + // Check if template exists + templates, err := template.Get("id = $1 AND user_id = $2", id, user.Id) + if err != nil { + res.Error(c, err.Error(), http.StatusInternalServerError) + return + } + + if len(templates) == 0 { + res.Error(c, "Template not found", http.StatusNotFound) + return + } + + // Delete template, and return success + if err := template.Delete(id); err != nil { + res.Error(c, err.Error(), http.StatusInternalServerError) + return + } + + res.Success(c, gin.H{"message": "Successfully deleted template"}) } diff --git a/backend/models/template/template.go b/backend/models/template/template.go index b356c7f..11a693d 100644 --- a/backend/models/template/template.go +++ b/backend/models/template/template.go @@ -82,3 +82,13 @@ func Update(id int, name string, template string) error { return err } + +func Delete(id int) error { + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + + query := `DELETE FROM templates WHERE id = $1` + _, err := db.Pool.Exec(ctx, query, id) + + return err +} diff --git a/backend/routes/routes.go b/backend/routes/routes.go index bd480a1..b4bf726 100644 --- a/backend/routes/routes.go +++ b/backend/routes/routes.go @@ -29,7 +29,7 @@ func SetupRoutes() *gin.Engine { templates.GET("/:id", template.GetID) templates.POST("", template.Create) templates.PUT("/:id", template.Put) - // DELETE (Delete) + templates.DELETE("/:id", template.Delete) // Cover letter routes covers := auth.Group("/cover") diff --git a/frontend/src/routes/templates/$templateId.tsx b/frontend/src/routes/templates/$templateId.tsx index 71dff54..a07994f 100644 --- a/frontend/src/routes/templates/$templateId.tsx +++ b/frontend/src/routes/templates/$templateId.tsx @@ -33,9 +33,9 @@ function RouteComponent() { const a = confirm("Are you sure?"); if (!a) return; - requests.delete(`/template/${templateId}`, { + requests.delete(`/templates/${templateId}`, { success() { - navigate({ to: "/" }); + navigate({ to: "/templates" }); }, }); };