tsk-8: Create Message endpoint (#15)

Closes #8

Reviewed-on: phoenix/textsender-api#15
Co-authored-by: phoenix <kundeng00@pm.me>
Co-committed-by: phoenix <kundeng00@pm.me>
This commit is contained in:
phoenix
2025-11-05 19:37:49 +00:00
committed by phoenix
parent 2045465111
commit 507eb9eb09
9 changed files with 230 additions and 3 deletions
+47
View File
@@ -0,0 +1,47 @@
package store
import (
"context"
"fmt"
"github.com/jackc/pgx/v5/pgxpool"
"git.kundeng.us/phoenix/textsender-models/pkg/message"
)
type MessageStore interface {
CreateMessage(ctx context.Context, msg *message.Message) error
MessageExists(ctx context.Context, msg *message.Message) (bool, error)
}
type PGMessageStore struct {
db *pgxpool.Pool
}
func NewMessageStore(db *pgxpool.Pool) *PGMessageStore {
return &PGMessageStore{db: db}
}
func (m *PGMessageStore) CreateMessage(ctx context.Context, msg *message.Message) error {
query := `
INSERT INTO messages (content, user_id)
VALUES ($1, $2)
RETURNING id
`
return m.db.QueryRow(ctx, query, msg.Content, msg.UserId).Scan(
&msg.Id,
)
}
func (m *PGMessageStore) MessageExists(ctx context.Context, msg *message.Message) (bool, error) {
query := `SELECT EXISTS(SELECT 1 FROM messages WHERE content = $1 AND user_id = $2)`
var exists bool
err := m.db.QueryRow(ctx, query, msg.Content, msg.UserId).Scan(&exists)
if err != nil {
return false, fmt.Errorf("checking if message exists: %w", err)
} else {
return exists, nil
}
}