Create and delete methods

This commit is contained in:
kolaente 2021-02-09 22:03:45 +01:00
parent fafeb9f29e
commit ee5bade0fb
Signed by: konrad
GPG Key ID: F40E70337AB24C9B
3 changed files with 53 additions and 5 deletions

View File

@ -1454,3 +1454,32 @@ func (err ErrUnknownSubscriptionEntityType) HTTPError() web.HTTPError {
Message: "The subscription entity type is invalid.",
}
}
// ErrSubscriptionAlreadyExists represents an error where a subscription entity already exists
type ErrSubscriptionAlreadyExists struct {
EntityID int64
EntityType SubscriptionEntityType
UserID int64
}
// IsErrSubscriptionAlreadyExists checks if an error is ErrSubscriptionAlreadyExists.
func IsErrSubscriptionAlreadyExists(err error) bool {
_, ok := err.(*ErrSubscriptionAlreadyExists)
return ok
}
func (err *ErrSubscriptionAlreadyExists) Error() string {
return fmt.Sprintf("Subscription for this (entity_id, entity_type, user_id) already exists [EntityType: %d, EntityID: %d, UserID: %d]", err.EntityType, err.EntityID, err.UserID)
}
// ErrCodeSubscriptionAlreadyExists holds the unique world-error code of this error
const ErrCodeSubscriptionAlreadyExists = 12002
// HTTPError holds the http error description
func (err ErrSubscriptionAlreadyExists) HTTPError() web.HTTPError {
return web.HTTPError{
HTTPCode: http.StatusPreconditionFailed,
Code: ErrCodeSubscriptionAlreadyExists,
Message: "You're already subscribed.",
}
}

View File

@ -72,10 +72,30 @@ func getEntityTypeFromString(entityType string) SubscriptionEntityType {
return SubscriptionEntityUnknown
}
func (sb *Subscription) Create(s *xorm.Session, auth web.Auth) error {
func (sb *Subscription) Create(s *xorm.Session, auth web.Auth) (err error) {
// Rights method alread does the validation of the entity type so we don't need to do that here
exists, err := s.
Where("entity_id = ? AND entity_type = ? AND user_id = ?", sb.EntityID, sb.EntityType, sb.UserID).
Exist(&Subscription{})
if err != nil {
return err
}
if exists {
return &ErrSubscriptionAlreadyExists{
EntityID: sb.EntityID,
EntityType: sb.EntityType,
UserID: sb.UserID,
}
}
_, err = s.Insert(sb)
return
}
func (sb *Subscription) Delete(s *xorm.Session, auth web.Auth) error {
func (sb *Subscription) Delete(s *xorm.Session, auth web.Auth) (err error) {
_, err = s.
Where("entity_id = ? AND entity_type = ? AND user_id = ?", sb.EntityID, sb.EntityType, sb.UserID).
Delete(&Subscription{})
return
}

View File

@ -18,7 +18,6 @@ package models
import (
"code.vikunja.io/api/pkg/db"
"code.vikunja.io/api/pkg/user"
"github.com/stretchr/testify/assert"
"testing"
)
@ -86,7 +85,7 @@ func TestSubscription_Create(t *testing.T) {
defer s.Close()
})
t.Run("Subscription already exists for this entity", func(t *testing.T) {
t.Run("existing subscription for (entity_id, entity_type, user_id) ", func(t *testing.T) {
db.LoadAndAssertFixtures(t)
s := db.NewSession()
defer s.Close()