Closes #11 Reviewed-on: phoenix/textsender-api#17 Co-authored-by: phoenix <kundeng00@pm.me> Co-committed-by: phoenix <kundeng00@pm.me>
48 lines
1.1 KiB
Go
48 lines
1.1 KiB
Go
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
|
|
}
|
|
}
|