todo_controllers.go 2.5 KB
Newer Older
Jisan Ahmed's avatar
Jisan Ahmed committed
package controllers

import (
	 "TodoWithORM/models"
	"encoding/json"

	"strconv" 

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

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

func (c *TodoController) OutputContext(status int, message string) {
	c.Ctx.Output.SetStatus(status)
	c.Ctx.Output.Body([]byte(message + "\n"))
}

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 (c *TodoController) Index() {
	c.Data["json"] = map[string]string{"message": "Welcome to Todo App"}
	c.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
	}
	err = this.model.Save(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, err := strconv.Atoi(ids)
	if err != nil {
		this.OutputContext(400, "Invalid ID")
		return
	}
	todo := this.model.Find(id)
	if todo == 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, err := strconv.Atoi(ids)
	if err != nil {
		this.OutputContext(400, "Invalid ID")
		return
	}
	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 := this.model.Find(id)
	if todo == 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, err := strconv.Atoi(ids)
	if err != nil {
		this.OutputContext(400, "Invalid ID")
		return
	}
	err = this.model.Delete(id)
	if err != nil {
		this.OutputContext(500, "Failed to delete todo")
		return
	}
	this.OutputContext(200, "Todo deleted successfully")
}