todo_controller.go 2.43 KB
Newer Older
Jisan Ahmed's avatar
Jisan Ahmed committed
package controllers

import (
	"Todo/models"
	"database/sql"
	"encoding/json"
	"fmt"

	"strconv"

	"github.com/beego/beego/v2/server/web"
)

type TodoController struct {
	web.Controller
	model models.TodoModel
}

func NewTodoController(db *sql.DB) *TodoController {
	return &TodoController{
		model: models.TodoModel{DB: db},
	}
}

func (this *TodoController) OutputContext(status int, message string) {
	this.Ctx.Output.SetStatus(status)
	this.Ctx.Output.Body([]byte(message + "\n"))
}
func (c *TodoController) Index() {
    c.OutputContext(200, "Welcome to the Todo API")
}


func (this *TodoController) ListTodos() {
	todos, err := this.model.All()
	if err != nil {
		this.OutputContext(500, "Failed to fetch todos")
		return
	}
	this.Data["json"] = todos
	this.ServeJSON()
}

func (this *TodoController) NewTodo() {
	req := struct{ Name string }{}
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil || req.Name == "" {
		this.OutputContext(400, "Invalid request: empty name")
		return
	}
	fmt.Println(req)
	_, err = this.model.Create(req.Name)
	if err != nil {
		this.OutputContext(500, "Failed to create todo")
		return
	}
	this.OutputContext(201, "Todo created successfully")
}

func (this *TodoController) GetTodo() {
	ids := this.Ctx.Input.Param(":id")
	id, _ := strconv.Atoi(ids)
	todo, err := this.model.Find(id)
	if err != nil {
		this.OutputContext(404, "Todo not found")
		return
	}
	this.Data["json"] = todo
	this.ServeJSON()
}

func (this *TodoController) UpdateTodo() {
	ids := this.Ctx.Input.Param(":id")
	id, _ := strconv.Atoi(ids)
	req := struct {
		Name string
		Done string
	}{}

	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		this.OutputContext(400, "Invalid request: "+err.Error())
		return
	}

	todo, err := this.model.Find(id)
	if err != nil {
		this.OutputContext(404, "Todo not found")
		return
	}

	if req.Name != "" {
		todo.Name = req.Name
	}
	if req.Done == "true" {
		todo.Done = true
	} else if req.Done == "false" {
		todo.Done = false
	}

	err = this.model.Update(id, todo.Name, todo.Done)
	if err != nil {
		this.OutputContext(500, "Failed to update todo")
		return
	}
	this.OutputContext(200, "Todo updated successfully")
}

func (this *TodoController) DeleteTodo() {
	ids := this.Ctx.Input.Param(":id")
	id, _ := strconv.Atoi(ids)
	err := this.model.Delete(id)
	if err != nil {
		this.OutputContext(500, "Failed to delete todo")
		return
	}
	this.OutputContext(200, "Todo deleted successfully")
}