package Database import ( "database/sql" "time" "github.com/gofrs/uuid" "gorm.io/gorm" "gorm.io/gorm/clause" ) // FriendRequest Set with Friend being the requestee, and UserID being the requester type FriendRequest struct { Base UserID uuid.UUID `gorm:"type:uuid;column:user_id;not null;" json:"user_id"` User User ` json:"user"` FriendID string `gorm:"not null" json:"friend_id"` // Stored encrypted FriendUsername string ` json:"friend_username"` // Stored encrypted FriendImagePath string ` json:"friend_image_path"` FriendPublicAsymmetricKey string ` json:"asymmetric_public_key"` // Stored encrypted FriendRequestDeviceTokens []FriendRequestDeviceToken ` json:"tokens"` SymmetricKey string `gorm:"not null" json:"symmetric_key"` // Stored encrypted AcceptedAt sql.NullTime ` json:"accepted_at"` CreatedAt time.Time `gorm:"not null" json:"created_at"` } type FriendRequestList []FriendRequest // GetFriendRequestByID gets friend request func GetFriendRequestByID(id string) (FriendRequest, error) { var ( friendRequest FriendRequest err error ) err = DB.Preload(clause.Associations). First(&friendRequest, "id = ?", id). Error return friendRequest, err } // GetFriendRequestsByUserID gets friend request by user id func GetFriendRequestsByUserID(userID string, page int) ([]FriendRequest, error) { var ( friends []FriendRequest offset int err error ) offset = page * PageSize err = DB.Model(FriendRequest{}). Preload("FriendRequestDeviceTokens.DeviceToken"). Where("user_id = ?", userID). Offset(offset). Limit(PageSize). Order("created_at DESC"). Find(&friends). Error return friends, err } // CreateFriendRequest creates friend request func (friendRequest *FriendRequest) CreateFriendRequest() error { return DB.Session(&gorm.Session{FullSaveAssociations: true}). Create(friendRequest). Error } // CreateFriendRequests creates multiple friend requests func (friendRequest *FriendRequestList) CreateFriendRequests() error { return DB.Session(&gorm.Session{FullSaveAssociations: true}). Create(friendRequest). Error } // UpdateFriendRequest Updates friend request func (friendRequest *FriendRequest) UpdateFriendRequest() error { return DB.Where("id = ?", friendRequest.ID). Updates(friendRequest). Error } // DeleteFriendRequest deletes friend request func (friendRequest *FriendRequest) DeleteFriendRequest() error { return DB.Session(&gorm.Session{FullSaveAssociations: true}). Delete(friendRequest). Error } func (friendRequest *FriendRequest) AttachDeviceToken(deviceToken DeviceToken, requester bool) error { var ( requestToken FriendRequestDeviceToken err error ) requestToken = FriendRequestDeviceToken{ DeviceToken: deviceToken, FriendRequestID: friendRequest.ID, } err = DB.Session(&gorm.Session{FullSaveAssociations: true}). Create(&requestToken). Error return err }