80 lines
1.3 KiB
Go
80 lines
1.3 KiB
Go
|
package cmd
|
||
|
|
||
|
import (
|
||
|
"time"
|
||
|
|
||
|
"gorm.io/driver/sqlite"
|
||
|
"gorm.io/gorm"
|
||
|
)
|
||
|
|
||
|
type Todo struct {
|
||
|
ID uint64
|
||
|
Desc string
|
||
|
DueDate time.Time
|
||
|
CreatedAt time.Time
|
||
|
}
|
||
|
|
||
|
func errPanic(err error, msg string) {
|
||
|
if err != nil {
|
||
|
panic(msg)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func parseDateString(date string) time.Time {
|
||
|
var (
|
||
|
t time.Time
|
||
|
err error
|
||
|
layouts = []string{
|
||
|
"02/01/2006",
|
||
|
"02/01/2006T15:04",
|
||
|
}
|
||
|
)
|
||
|
for _, layout := range layouts {
|
||
|
t, err = time.Parse(layout, date)
|
||
|
if err == nil {
|
||
|
return t
|
||
|
}
|
||
|
}
|
||
|
return time.Time{}
|
||
|
}
|
||
|
|
||
|
func openDB() *gorm.DB {
|
||
|
db, err := gorm.Open(sqlite.Open("todo.db"), &gorm.Config{})
|
||
|
errPanic(err, "failed to connect database")
|
||
|
|
||
|
return db
|
||
|
}
|
||
|
|
||
|
func createTodo(desc string, date string) {
|
||
|
db := openDB()
|
||
|
err := db.AutoMigrate(&Todo{})
|
||
|
errPanic(err, "failed to migrate database")
|
||
|
d := parseDateString(date)
|
||
|
|
||
|
t := Todo{Desc: desc, DueDate: d, CreatedAt: time.Now()}
|
||
|
db.Create(&t)
|
||
|
}
|
||
|
|
||
|
func updateTodo(id uint, new Todo) {
|
||
|
db := openDB()
|
||
|
var t Todo
|
||
|
res := db.First(&t, id)
|
||
|
errPanic(res.Error, "failed to find id")
|
||
|
new.ID = t.ID
|
||
|
db.Model(&t).Updates(new)
|
||
|
}
|
||
|
|
||
|
func deleteTodo(id uint) {
|
||
|
db := openDB()
|
||
|
db.Delete(&Todo{}, id)
|
||
|
}
|
||
|
|
||
|
func getAllTodos() []Todo {
|
||
|
db := openDB()
|
||
|
var todos []Todo
|
||
|
res := db.Find(&todos)
|
||
|
errPanic(res.Error, "failed to get all todos")
|
||
|
|
||
|
return todos
|
||
|
}
|