serverctl/pkg/db/postgres/projectsRepository.go
2022-02-14 01:25:36 +01:00

67 lines
1.5 KiB
Go

package postgres
import (
"context"
"serverctl/pkg/application/projects"
"serverctl/pkg/db"
)
var _ projects.Repository = &ProjectsRepository{}
type ProjectsRepository struct {
db *db.Client
}
func NewProjectsRepository(db *db.Client) projects.Repository {
return &ProjectsRepository{db: db}
}
type projectData struct {
Name string `json:"name"`
MemberIds []int `json:"memberIds"`
AdminIds []int `json:"adminIds"`
}
func NewProjectData(project *projects.CreateProject) projectData {
return projectData{
Name: project.Name,
AdminIds: project.AdminIds,
MemberIds: project.MemberIds,
}
}
func (p ProjectsRepository) Create(ctx context.Context, project *projects.CreateProject) (int, error) {
conn := p.db.GetConn(ctx)
defer conn.Release()
var projectId int
err := conn.QueryRow(ctx, "insert into sctl_project(data) values ($1) returning id", NewProjectData(project)).Scan(&projectId)
if err != nil {
return -1, err
}
return projectId, nil
}
func (p ProjectsRepository) GetForMemberId(ctx context.Context, memberId int) ([]*projects.Project, error) {
conn := p.db.GetConn(ctx)
defer conn.Release()
rows, _ := conn.Query(ctx, "select id, data from sctl_project")
projectsArr := make([]*projects.Project, 0)
for rows.Next() {
var (
id int
data projectData
)
err := rows.Scan(&id, &data)
if err != nil {
return nil, err
}
projectsArr = append(projectsArr, projects.NewProject(id, data.Name, data.MemberIds, data.AdminIds))
}
return projectsArr, nil
}