Implement boilerplate services

This commit is contained in:
2024-10-27 18:00:21 +01:00
parent 251e372f72
commit 91a3a0f4f7
3 changed files with 156 additions and 0 deletions

46
noteService.go Normal file
View File

@@ -0,0 +1,46 @@
package main
import (
"fmt"
"time"
)
type NoteService struct {
db *DB
}
type NoteServiceQuery struct {
Timestamp *string `db:"timestamp"`
PlayerID *int64 `db:"player"`
ID *int64 `db:"id"`
}
func (ns *NoteService) Query(query NoteServiceQuery) (Note, error) {
note := Note{}
sqlQuery := "SELECT id, content, timestamp, player FROM note"
whereQuery := BuildWhereQuery(query)
if whereQuery != "" {
sqlQuery += " " + whereQuery
}
err := ns.db.readConn.QueryRow(sqlQuery).Scan(&note.ID, &note.Content, &note.Timestamp, &note.Player.ID)
if err != nil {
return note, fmt.Errorf("failed getting note for query %q: %v", sqlQuery, err)
}
return note, nil
}
func (ns *NoteService) Create(content string, timestamp time.Time, player Player) (Note, error) {
note := Note{}
res, err := ns.db.writeConn.Exec("insert into note (content, timestamp, player) values (?, ?, ?)", content, timestamp, player.ID)
if err != nil {
return note, fmt.Errorf("failed to insert note: %v", err)
}
id, err := res.LastInsertId()
if err != nil {
return note, fmt.Errorf("failed to get last insert id: %v", err)
}
return ns.Query(NoteServiceQuery{ID: &id})
}