Skip to content

Commit

Permalink
Add API for favorite playlist songs
Browse files Browse the repository at this point in the history
  • Loading branch information
aidewoode committed Sep 21, 2022
1 parent 2a2075c commit ee228d9
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 0 deletions.
30 changes: 30 additions & 0 deletions app/controllers/api/v1/favorite_playlist/songs_controller.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# frozen_string_literal: true

module Api
module V1
class FavoritePlaylist::SongsController < ApiController
before_action :find_playlist
before_action :find_song

def create
@playlist.playlists_songs.create(song_id: @song.id, position: 1)
rescue ActiveRecord::RecordNotUnique
render json: {error: "RecordNotUnique", message: t("error.already_in_playlist")}, status: :bad_request
end

def destroy
@playlist.songs.destroy(@song)
end

private

def find_song
@song = Song.find(params[:song_id])
end

def find_playlist
@playlist = Current.user.favorite_playlist
end
end
end
end
5 changes: 5 additions & 0 deletions config/routes.rb
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,14 @@
resources :stream, only: [:new]
resources :transcoded_stream, only: [:new]
resources :cached_transcoded_stream, only: [:new]

namespace :current_playlist do
resource :songs, only: [:show]
end

namespace :favorite_playlist do
resource :songs, only: [:create, :destroy]
end
end
end
end
31 changes: 31 additions & 0 deletions test/controllers/api/v1/favorite_playlist/songs_controller_test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
require "test_helper"

class Api::V1::FavoritePlaylist::SongsControllerTest < ActionDispatch::IntegrationTest
setup do
@user = users(:visitor1)
@playlist = @user.favorite_playlist
@playlist.song_ids = [1, 2]
end

test "should add songs to playlist" do
post api_v1_favorite_playlist_songs_url, params: {song_id: 3}, headers: api_token_header(@user)
assert_equal [3, 1, 2], @playlist.reload.song_ids
end

test "should remove songs from playlist" do
delete api_v1_favorite_playlist_songs_url, params: {song_id: 1}, headers: api_token_header(@user)
assert_equal [2], @playlist.reload.song_ids

delete api_v1_favorite_playlist_songs_url, params: {song_id: 2}, headers: api_token_header(@user)
assert_equal [], @playlist.reload.song_ids
end

test "should not add song to playlist if already in playlist" do
post api_v1_favorite_playlist_songs_url, params: {song_id: 1}, headers: api_token_header(@user)
response = @response.parsed_body

assert_response :bad_request
assert_equal "RecordNotUnique", response["error"]
assert_equal I18n.t("error.already_in_playlist"), response["message"]
end
end

0 comments on commit ee228d9

Please sign in to comment.