From d61d51e6a60fc7b2a208f29e8c4da73f30d6d384 Mon Sep 17 00:00:00 2001 From: Stanislas Lange Date: Sun, 1 Dec 2024 18:47:24 +0100 Subject: [PATCH] refactor(track): streamline track love/unlove functionality with reusable method --- .../ViewModel/ScobbledTrackViewModel.swift | 50 +++++++++++++------ 1 file changed, 34 insertions(+), 16 deletions(-) diff --git a/firstfm/ViewModel/ScobbledTrackViewModel.swift b/firstfm/ViewModel/ScobbledTrackViewModel.swift index 7c0fcbf..d90856b 100644 --- a/firstfm/ViewModel/ScobbledTrackViewModel.swift +++ b/firstfm/ViewModel/ScobbledTrackViewModel.swift @@ -1,33 +1,51 @@ import Foundation -import SwiftUI import NotificationBannerSwift +import SwiftUI import Valet struct Nothing: Codable { } class ScrobbledTrackViewModel { - let myValet = getValet() + let valet = getValet() func loveTrack(track: ScrobbledTrack) { - let storedToken = try? myValet.string(forKey: "sk") - - LastFMAPI.request(lastFMMethod: "track.love", args: ["artist": track.artist.name, "track": track.name, "sk": storedToken ?? ""]) { (_: Nothing?, error) -> Void in - if error != nil { - DispatchQueue.main.async { - FloatingNotificationBanner(title: "Failed to like track", subtitle: error?.localizedDescription, style: .danger).show() - } - } - } + performTrackAction( + track: track, action: "track.love", successMessage: "Track liked successfully", + failureMessage: "Failed to like track") } func unloveTrack(track: ScrobbledTrack) { - let storedToken = try? myValet.string(forKey: "sk") + performTrackAction( + track: track, action: "track.unlove", successMessage: "Track unliked successfully", + failureMessage: "Failed to unlike track") + } + + private func performTrackAction( + track: ScrobbledTrack, action: String, successMessage: String, failureMessage: String + ) { + guard let storedToken = try? valet.string(forKey: "sk") else { + DispatchQueue.main.async { + FloatingNotificationBanner( + title: "Error", subtitle: "Failed to retrieve stored token", style: .danger + ).show() + } + return + } - LastFMAPI.request(lastFMMethod: "track.unlove", args: ["artist": track.artist.name, "track": track.name, "sk": storedToken ?? ""]) { (_: Nothing?, error) -> Void in - if error != nil { - DispatchQueue.main.async { - FloatingNotificationBanner(title: "Failed to unlike track", subtitle: error?.localizedDescription, style: .danger).show() + LastFMAPI.request( + lastFMMethod: action, + args: ["artist": track.artist.name, "track": track.name, "sk": storedToken] + ) { (_: Nothing?, error) -> Void in + DispatchQueue.main.async { + if let error = error { + FloatingNotificationBanner( + title: failureMessage, subtitle: error.localizedDescription, style: .danger + ).show() + } else { + FloatingNotificationBanner( + title: successMessage, subtitle: nil, style: .success + ).show() } } }