Skip to content

Commit

Permalink
Fix N+1 issue on API of current playlist songs
Browse files Browse the repository at this point in the history
  • Loading branch information
aidewoode committed Sep 15, 2022
1 parent 4c824b8 commit 2a2075c
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 3 deletions.
5 changes: 5 additions & 0 deletions app/controllers/api/v1/current_playlist/songs_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,12 @@ module Api
module V1
class CurrentPlaylist::SongsController < ApiController
def show
favorite_playlist = Current.user.favorite_playlist

@songs = Current.user.current_playlist.songs
.includes(:artist, :album)
.joins("Left JOIN playlists_songs T1 ON songs.id = T1.song_id AND T1.playlist_id = #{favorite_playlist.id}")
.select("songs.*, T1.playlist_id IS NOT NULL as is_favorited")
end
end
end
Expand Down
2 changes: 1 addition & 1 deletion app/views/api/v1/current_playlist/songs/show.json.jbuilder
Original file line number Diff line number Diff line change
@@ -1 +1 @@
json.array! @songs, partial: "api/v1/songs/song", as: :song
json.array! @songs, partial: "api/v1/songs/song", as: :song, cache: true
4 changes: 2 additions & 2 deletions app/views/api/v1/songs/_song.json.jbuilder
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
json.call(song, :id, :name, :duration)
json.url new_api_v1_stream_path(song_id: song.id)
json.url new_api_v1_stream_url(song_id: song.id)
json.album_name song.album.title
json.artist_name song.artist.title
json.is_favorited Current.user.favorited? song
json.is_favorited song.respond_to?(:is_favorited) ? song.is_favorited : Current.user.favorited?(song)
json.format need_transcode?(song.format) ? Stream::TRANSCODE_FORMAT : song.format
json.album_image_url do
json.small URI.join(root_url, image_url_for(song.album, size: "small"))
Expand Down

0 comments on commit 2a2075c

Please sign in to comment.