Skip to content

Commit

Permalink
register notification user do nothing if exists
Browse files Browse the repository at this point in the history
  • Loading branch information
konrad2002 committed Sep 23, 2024
1 parent 5a919fd commit 9b3f614
Showing 1 changed file with 22 additions and 7 deletions.
29 changes: 22 additions & 7 deletions service/notification_user_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,10 @@ func GetNotificationUserById(id primitive.ObjectID) (model.NotificationUser, err
return getNotificationUserByBsonDocument(bson.D{{"_id", id}})
}

func GetNotificationUserByToken(token string) (model.NotificationUser, error) {
return getNotificationUserByBsonDocument(bson.D{{"token", token}})
}

func RemoveNotificationUserById(id primitive.ObjectID) error {

ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
Expand Down Expand Up @@ -98,18 +102,29 @@ func UpdateNotificationUser(user model.NotificationUser) (model.NotificationUser
return GetNotificationUserById(user.Identifier)
}

// RegisterNotificationUser adds the given token to the database,
// if the token already exists, it just returns the user
func RegisterNotificationUser(token string) (model.NotificationUser, error) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

user := model.NotificationUser{
Token: token,
}

r, err := notificationUserCollection.InsertOne(ctx, user)
existing, err := GetNotificationUserByToken(token)
if err != nil {
return model.NotificationUser{}, err
if err.Error() == entryNotFoundMessage {
user := model.NotificationUser{
Token: token,
}

r, err2 := notificationUserCollection.InsertOne(ctx, user)
if err2 != nil {
return model.NotificationUser{}, err2
}

existing, _ = GetNotificationUserById(r.InsertedID.(primitive.ObjectID))
} else {
return model.NotificationUser{}, err
}
}

return GetNotificationUserById(r.InsertedID.(primitive.ObjectID))
return existing, nil
}

0 comments on commit 9b3f614

Please sign in to comment.