package lishwist import ( "database/sql" "errors" "fmt" "strings" "lishwist/core/internal/db" ) type Wish struct { Id string Name string ClaimantId string `json:",omitempty"` ClaimantName string `json:",omitempty"` Sent bool RecipientId string `json:",omitempty"` RecipientName string `json:",omitempty"` RecipientRef string `json:",omitempty"` CreatorId string `json:",omitempty"` CreatorName string `json:",omitempty"` } func (s *Session) GetWishes() ([]Wish, error) { stmt := "SELECT wish.id, wish.name, wish.sent FROM wish WHERE wish.creator_id = ?1 AND wish.recipient_id = ?1" rows, err := db.Connection.Query(stmt, s.User.Id) if err != nil { return nil, fmt.Errorf("Query execution failed: %w", err) } defer rows.Close() wishs := []Wish{} for rows.Next() { var id string var name string var sent bool err = rows.Scan(&id, &name, &sent) if err != nil { return nil, fmt.Errorf("Failed to scan a row: %w", err) } wish := Wish{ Id: id, Name: name, Sent: sent, } wishs = append(wishs, wish) } err = rows.Err() if err != nil { return nil, fmt.Errorf("Rows returned an error: %w", err) } return wishs, nil } func (s *Session) MakeWish(name string) error { stmt := "INSERT INTO wish (name, recipient_id, creator_id) VALUES (?, ?, ?)" _, err := db.Connection.Exec(stmt, strings.TrimSpace(name), s.User.Id, s.User.Id) if err != nil { return fmt.Errorf("Query execution failed: %w", err) } return nil } func (s *Session) GetOthersWishes(userReference string) ([]Wish, error) { otherUser, err := getUserByReference(userReference) if err != nil { return nil, fmt.Errorf("Failed to get other user: %w", err) } if otherUser.Id == s.User.Id { return nil, errors.New("Use (s *Session) GetWishes() to view your own wishes") } stmt := "SELECT gift.id, gift.name, claimant.id, claimant.name, gift.sent, gift.creator_id, creator.name, gift.recipient_id FROM gift JOIN v_user AS user ON gift.recipient_id = user.id LEFT JOIN v_user AS claimant ON gift.claimant_id = claimant.id LEFT JOIN v_user AS creator ON gift.creator_id = creator.id WHERE user.id = ?" rows, err := db.Connection.Query(stmt, otherUser.Id) if err != nil { return nil, fmt.Errorf("Failed to execute query: %w", err) } defer rows.Close() wishes := []Wish{} for rows.Next() { var id string var name string var claimantId sql.NullString var claimantName sql.NullString var sent bool var creatorId string var creatorName string var recipientId string err = rows.Scan(&id, &name, &claimantId, &claimantName, &sent, &creatorId, &creatorName, &recipientId) if err != nil { return nil, fmt.Errorf("Failed to scan a row: %w", err) } wish := Wish{ Id: id, Name: name, ClaimantId: claimantId.String, ClaimantName: claimantName.String, Sent: sent, CreatorId: creatorId, CreatorName: creatorName, RecipientId: recipientId, } wishes = append(wishes, wish) } err = rows.Err() if err != nil { return nil, fmt.Errorf("Rows returned an error: %w", err) } return wishes, nil }