github.com/nizigama/simple-note@v0.0.0-20210501235539-2cc762e06fe8/models/note.go (about) 1 package models 2 3 import ( 4 boltDB "github.com/nizigama/simple-note/services/database" 5 ) 6 7 type Note struct { 8 ID int 9 Title string 10 Body string 11 OwnerID int 12 } 13 14 const ( 15 NoteTableName string = "Notes" 16 ) 17 18 // Save persists the user in the struct in the database 19 func (n Note) Save() (uint64, error) { 20 21 simpleNote := map[string]interface{}{ 22 "title": n.Title, 23 "note": n.Body, 24 "ownerID": n.OwnerID, 25 } 26 27 return boltDB.Store(simpleNote, NoteTableName) 28 } 29 30 func ReadNote(noteID uint64) (Note, error) { 31 32 simpleNote, err := boltDB.Show(noteID, NoteTableName) 33 34 if err != nil { 35 return Note{}, err 36 } 37 38 return Note{ 39 Title: simpleNote["title"].(string), 40 Body: simpleNote["note"].(string), 41 OwnerID: int(simpleNote["ownerID"].(float64)), 42 }, nil 43 } 44 45 func ReadAllUserNotes(userID int) ([]Note, error) { 46 47 var notes []Note 48 res, err := boltDB.ManyByIntField(NoteTableName, "ownerID", userID) 49 50 if err != nil { 51 return nil, err 52 } 53 54 for _, simpleNote := range res { 55 notes = append(notes, Note{ 56 ID: int(simpleNote["itemID"].(uint64)), 57 Title: simpleNote["title"].(string), 58 Body: simpleNote["note"].(string), 59 OwnerID: int(simpleNote["ownerID"].(float64)), 60 }) 61 } 62 63 return notes, nil 64 } 65 66 func UpdateNote(n Note, itemID int) error { 67 simpleNote := map[string]interface{}{ 68 "title": n.Title, 69 "note": n.Body, 70 "ownerID": n.OwnerID, 71 } 72 73 return boltDB.Update(simpleNote, NoteTableName, uint64(itemID)) 74 } 75 76 func DeleteNote(itemID int) error { 77 78 return boltDB.Delete(NoteTableName, uint64(itemID)) 79 }