-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnotes.go
132 lines (105 loc) · 2.44 KB
/
notes.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
package main
import (
"context"
"strings"
"time"
"njournal/models"
"github.com/google/uuid"
"github.com/wailsapp/wails/v2/pkg/runtime"
"gorm.io/gorm"
)
type Note struct {
ID uuid.UUID
Title string
Content string
UpdatedAt time.Time
CreatedAt time.Time
}
func createNote(rowNote *models.Note) Note {
return Note{
ID: rowNote.ID,
Title: rowNote.Title,
Content: rowNote.Content,
UpdatedAt: rowNote.UpdatedAt,
CreatedAt: rowNote.CreatedAt,
}
}
func createNoteList(rowNotes []*models.Note) []Note {
var notes []Note
for _, rowNote := range rowNotes {
notes = append(notes, Note{
ID: rowNote.ID,
Title: rowNote.Title,
Content: rowNote.Content,
UpdatedAt: rowNote.UpdatedAt,
CreatedAt: rowNote.CreatedAt,
})
}
return notes
}
type NotesService struct {
db *gorm.DB
ctx context.Context
}
func (n *NotesService) Create(noteArgs Note) (*Note, error) {
today := time.Now()
title := CreateTitle(noteArgs.Content)
note := &models.Note{
ID: uuid.New(),
Title: title,
Content: noteArgs.Content,
UpdatedAt: today,
CreatedAt: today,
}
err := n.db.Create(¬e).Error
if err != nil {
return nil, err
}
return &Note{
ID: note.ID,
Content: note.Content,
}, nil
}
func (n *NotesService) GetNoteByID(id uuid.UUID) (*Note, error) {
runtime.LogDebugf(n.ctx, "Getting note by ID: %d", id)
note := &models.Note{}
err := n.db.Where("id = ?", id).Take(note).Error
if err != nil {
return nil, err
}
noteToReturn := createNote(note)
return ¬eToReturn, nil
}
func (n *NotesService) Update(noteToUpdate Note) (*Note, error) {
today := time.Now()
title := CreateTitle(noteToUpdate.Content)
note := &models.Note{}
err := n.db.Where("id = ?", noteToUpdate.ID).Take(note).Error
if err != nil {
return nil, err
}
note.Title = title
note.Content = noteToUpdate.Content
note.UpdatedAt = today
err = n.db.Save(¬e).Error
if err != nil {
return nil, err
}
noteToReturn := createNote(note)
return ¬eToReturn, nil
}
func (n *NotesService) List(option ListNotesOptions) ([]Note, error) {
order := option.OrderBy + " " + option.Order
var notes []*models.Note
err := n.db.Order(order).Find(¬es).Error
if err != nil {
return nil, err
}
notesToReturn := createNoteList(notes)
return notesToReturn, nil
}
func CreateTitle(content string) string {
head := strings.Split(content, "\n")[0]
head = strings.ReplaceAll(head, "#", "")
return head
}