实现音频服务api
This commit is contained in:
67
internal/repository/song_repo.go
Normal file
67
internal/repository/song_repo.go
Normal file
@@ -0,0 +1,67 @@
|
||||
package repository
|
||||
|
||||
import "database/sql"
|
||||
|
||||
type SongRepository struct {
|
||||
db *sql.DB
|
||||
}
|
||||
|
||||
func NewSongRepository(db *sql.DB) *SongRepository {
|
||||
return &SongRepository{db: db}
|
||||
}
|
||||
|
||||
func (r *SongRepository) GetAll() ([]Song, error) {
|
||||
rows, err := r.db.Query("SELECT id, title, artist_id, album_id, duration, media_file_id FROM songs")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
songs := []Song{}
|
||||
for rows.Next() {
|
||||
var song Song
|
||||
if err := rows.Scan(&song.ID, &song.Title, &song.ArtistID, &song.AlbumID, &song.Duration, &song.MediaFileID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
songs = append(songs, song)
|
||||
}
|
||||
return songs, nil
|
||||
}
|
||||
|
||||
func (r *SongRepository) GetAllWithDetails() ([]SongDetail, error) {
|
||||
rows, err := r.db.Query(`
|
||||
SELECT s.id, s.title, a.name as artist_name, al.title as album_title, s.duration, mf.path
|
||||
FROM songs s
|
||||
INNER JOIN media_files mf ON s.media_file_id = mf.id
|
||||
INNER JOIN artists a ON s.artist_id = a.id
|
||||
INNER JOIN albums al ON s.album_id = al.id
|
||||
ORDER BY s.title
|
||||
`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
songs := []SongDetail{}
|
||||
for rows.Next() {
|
||||
var song SongDetail
|
||||
if err := rows.Scan(&song.ID, &song.Title, &song.Artist, &song.Album, &song.Duration, &song.Path); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
songs = append(songs, song)
|
||||
}
|
||||
return songs, nil
|
||||
}
|
||||
|
||||
func (r *SongRepository) Get(id int) (Song, error) {
|
||||
var song Song
|
||||
rows, err := r.db.Query("SELECT id, title, artist_id, album_id, duration, media_file_id FROM songs WHERE id = ?", id)
|
||||
if err != nil {
|
||||
return Song{}, err
|
||||
}
|
||||
defer rows.Close()
|
||||
if rows.Next() {
|
||||
rows.Scan(&song.ID, &song.Title, &song.ArtistID, &song.AlbumID, &song.Duration, &song.MediaFileID)
|
||||
}
|
||||
return song, nil
|
||||
}
|
||||
Reference in New Issue
Block a user