1
0

Added functions for adding items to a todolist

This commit is contained in:
konrad
2018-06-10 19:49:40 +02:00
committed by kolaente
parent 7bac9f490e
commit 91f67dc364
9 changed files with 190 additions and 2 deletions

View File

@ -142,3 +142,16 @@ func IsErrListDoesNotExist(err error) bool {
func (err ErrListDoesNotExist) Error() string {
return fmt.Sprintf("List does not exist [ID: %d]", err.ID)
}
// ErrListItemCannotBeEmpty represents a "ErrListDoesNotExist" kind of error. Used if the list does not exist.
type ErrListItemCannotBeEmpty struct{}
// IsErrListItemCannotBeEmpty checks if an error is a ErrListDoesNotExist.
func IsErrListItemCannotBeEmpty(err error) bool {
_, ok := err.(ErrListItemCannotBeEmpty)
return ok
}
func (err ErrListItemCannotBeEmpty) Error() string {
return fmt.Sprintf("List item text cannot be empty.")
}

View File

@ -13,7 +13,7 @@ type ListItem struct {
Created int64 `xorm:"created" json:"created"`
Updated int64 `xorm:"updated" json:"updated"`
CreatedBy User `xorm:"-"`
CreatedBy User `xorm:"-" json:"createdBy"`
}
// TableName returns the table name for listitems
@ -21,7 +21,46 @@ func (ListItem) TableName() string {
return "items"
}
// GetItemsByListID gets all todoitems for a list
func GetItemsByListID(listID int64) (items []*ListItem, err error) {
err = x.Where("list_id = ?", listID).Find(&items)
if err != nil {
return
}
// Get all users and put them into the array
var userIDs []int64
for _, i := range items {
found := false
for _, u := range userIDs {
if i.CreatedByID == u {
found = true
break
}
}
if !found {
userIDs = append(userIDs, i.CreatedByID)
}
}
var users []User
err = x.In("id", userIDs).Find(&users)
if err != nil {
return
}
for in, item := range items {
for _, user := range users {
if item.CreatedByID == user.ID {
items[in].CreatedBy = user
break
}
}
// obsfucate the user password
items[in].CreatedBy.Password = ""
}
return
}

View File

@ -0,0 +1,37 @@
package models
// CreateOrUpdateListItem adds or updates a todo item to a list
func CreateOrUpdateListItem(item *ListItem) (err error) {
// Check if we have at least a text
if item.Text == "" {
return ErrListItemCannotBeEmpty{}
}
// Check if the list exists
_, err = GetListByID(item.ListID)
if err != nil {
return
}
// Check if the user exists
_, _, err = GetUserByID(item.CreatedBy.ID)
if err != nil {
return
}
item.CreatedByID = item.CreatedBy.ID
if item.ID != 0 {
_, err = x.ID(item.ID).Update(item)
if err != nil {
return
}
} else {
_, err = x.Insert(item)
if err != nil {
return
}
}
return
}

View File

@ -10,7 +10,7 @@ type List struct {
Created int64 `xorm:"created" json:"created"`
Updated int64 `xorm:"updated" json:"updated"`
Items []*ListItem `xorm:"-"`
Items []*ListItem `xorm:"-" json:"items"`
}
// GetListByID returns a list by its ID
@ -32,6 +32,7 @@ func GetListByID(id int64) (list List, err error) {
}
list.Owner = user
list.Owner.Password = ""
items, err := GetItemsByListID(list.ID)
if err != nil {