first commit
This commit is contained in:
@@ -0,0 +1,62 @@
|
||||
package mysql
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
|
||||
"secunda-test/internal/domain"
|
||||
)
|
||||
|
||||
type TeamRepository struct{ db *sql.DB }
|
||||
|
||||
func NewTeamRepository(db *sql.DB) *TeamRepository { return &TeamRepository{db: db} }
|
||||
|
||||
func (r *TeamRepository) Create(ctx context.Context, name string, createdBy int64) (domain.Team, error) {
|
||||
res, err := r.db.ExecContext(ctx, `INSERT INTO teams(name,created_by) VALUES(?,?)`, name, createdBy)
|
||||
if err != nil {
|
||||
return domain.Team{}, err
|
||||
}
|
||||
id, _ := res.LastInsertId()
|
||||
return domain.Team{ID: id, Name: name, CreatedBy: createdBy}, nil
|
||||
}
|
||||
|
||||
func (r *TeamRepository) AddMember(ctx context.Context, teamID, userID int64, role domain.Role) error {
|
||||
_, err := r.db.ExecContext(ctx, `
|
||||
INSERT INTO team_members(user_id,team_id,role) VALUES(?,?,?)
|
||||
ON DUPLICATE KEY UPDATE role=VALUES(role)`, userID, teamID, role)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *TeamRepository) ListByUser(ctx context.Context, userID int64) ([]domain.Team, error) {
|
||||
rows, err := r.db.QueryContext(ctx, `
|
||||
SELECT t.id,t.name,t.created_by,tm.role,t.created_at
|
||||
FROM teams t
|
||||
JOIN team_members tm ON tm.team_id=t.id
|
||||
WHERE tm.user_id=?
|
||||
ORDER BY t.created_at DESC`, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []domain.Team
|
||||
for rows.Next() {
|
||||
var t domain.Team
|
||||
if err := rows.Scan(&t.ID, &t.Name, &t.CreatedBy, &t.Role, &t.CreatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, t)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (r *TeamRepository) MemberRole(ctx context.Context, teamID, userID int64) (domain.Role, bool, error) {
|
||||
var role domain.Role
|
||||
err := r.db.QueryRowContext(ctx, `SELECT role FROM team_members WHERE team_id=? AND user_id=?`, teamID, userID).Scan(&role)
|
||||
if err == sql.ErrNoRows {
|
||||
return "", false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
return role, true, nil
|
||||
}
|
||||
Reference in New Issue
Block a user