Add applications

This commit is contained in:
2022-02-16 15:30:38 +01:00
parent 205adeb118
commit f35f277b16
10 changed files with 248 additions and 21 deletions

View File

@@ -0,0 +1,15 @@
package applications
type Application struct {
Id int
ProjectId int
Name string
}
func NewApplication(id int, projectId int, name string) *Application {
return &Application{
Id: id,
ProjectId: projectId,
Name: name,
}
}

View File

@@ -0,0 +1,7 @@
package applications
import "context"
type Repository interface {
CreateApplication(ctx context.Context, name string, userId int, projectId int) (int, error)
}

View File

@@ -0,0 +1,29 @@
package applications
import (
"context"
"errors"
"go.uber.org/zap"
)
type Service struct {
repository Repository
logger *zap.Logger
}
func NewService(logger *zap.Logger, repository Repository) *Service {
return &Service{
logger: logger,
repository: repository,
}
}
func (s Service) CreateApplication(ctx context.Context, applicationName string, userId int, projectId int) (int, error) {
if applicationName == "" {
return -1, errors.New("application name is empty")
}
applicationId, err := s.repository.CreateApplication(ctx, applicationName, userId, projectId)
return applicationId, err
}

View File

@@ -0,0 +1,61 @@
package postgres
import (
"context"
"errors"
"github.com/jackc/pgx/v4"
"go.uber.org/zap"
"serverctl/pkg/application/applications"
"serverctl/pkg/db"
)
type ApplicationRepository struct {
db *db.Client
logger *zap.Logger
}
var _ applications.Repository = ApplicationRepository{}
func NewApplicationRepository(logger *zap.Logger, db *db.Client) applications.Repository {
return &ApplicationRepository{logger: logger, db: db}
}
func (a ApplicationRepository) CreateApplication(ctx context.Context, name string, userId int, projectId int) (int, error) {
conn := a.db.GetConn(ctx)
defer conn.Release()
var applicationId int
err := conn.BeginTxFunc(ctx, pgx.TxOptions{}, func(tx pgx.Tx) error {
var exists bool
err := tx.QueryRow(
ctx,
"select exists(select 1 from sctl_project_member where project_id = $1 and member_id = $2 and role = 'admin')", projectId, userId,
).Scan(&exists)
if err != nil {
a.logger.Info("cannot query project member status in database",
zap.Int("userId", userId),
zap.Int("projectId", projectId),
zap.String("error", err.Error()))
return err
}
if !exists {
a.logger.Info("cannot create application as user isn't admin for project, or project doesn't exist",
zap.Int("userId", userId),
zap.Int("projectId", projectId))
return errors.New("user isn't admin or admin of project")
}
err = tx.QueryRow(ctx, "insert into sctl_application(name, project_id) values($1, $2) returning id", name, projectId).Scan(&applicationId)
if err != nil {
a.logger.Info("could not create application", zap.String("error", err.Error()))
return err
}
return nil
})
if err != nil {
return -1, err
}
return applicationId, nil
}