Files
plumber/internal/store/answer.go

64 lines
1.3 KiB
Go

package store
import (
"context"
"database/sql"
"fmt"
"strings"
"time"
"plumber/internal/store/sqlc"
)
// Answer is an admin reply to a question.
type Answer struct {
QuestionID string
AuthorID string
AuthorName string
Body string
CreatedAt string
UpdatedAt string
db *sql.DB
}
// NewAnswer returns an Answer bound to db.
func NewAnswer(db *sql.DB) *Answer {
return &Answer{db: db}
}
// Upsert inserts or updates the answer for QuestionID.
func (a *Answer) Upsert(ctx context.Context) error {
if a == nil || a.db == nil {
return fmt.Errorf("answer: no database")
}
a.Body = strings.TrimSpace(a.Body)
now := time.Now().UTC().Format(time.RFC3339)
if a.CreatedAt == "" {
a.CreatedAt = now
}
a.UpdatedAt = now
return sqlc.New(a.db).UpsertAnswer(ctx, sqlc.UpsertAnswerParams{
QuestionID: a.QuestionID,
AuthorID: a.AuthorID,
Body: a.Body,
CreatedAt: a.CreatedAt,
UpdatedAt: a.UpdatedAt,
})
}
func GetAnswer(ctx context.Context, db *sql.DB, questionID string) (*Answer, error) {
r, err := sqlc.New(db).GetAnswer(ctx, questionID)
if err != nil {
return nil, err
}
return &Answer{
QuestionID: r.QuestionID,
AuthorID: r.AuthorID,
AuthorName: r.AuthorName,
Body: r.Body,
CreatedAt: r.CreatedAt,
UpdatedAt: r.UpdatedAt,
db: db,
}, nil
}