Implement boilerplate services
This commit is contained in:
46
noteService.go
Normal file
46
noteService.go
Normal 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(¬e.ID, ¬e.Content, ¬e.Timestamp, ¬e.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})
|
||||
}
|
Reference in New Issue
Block a user