7fife-backend/controllers/song.controller.js

230 lines
6.9 KiB
JavaScript

const Song = require('../models/song.model');
const Category = require('../models/categories.model');
const Subcategory = require('../models/subcategories.model');
const Album = require('../models/album.model');
const Artist =require('../models/artist.model')
const Language = require('../models/language.model')
const createSong = async (req, res) => {
try {
const {
categoryId,
subcategoryId,
albumId,
artistId,
title,
musicLink,
trackerID,
lyrics,
languageId
} = req.body;
const { coverArtImage, musicFile } = req.files;
// Check if both cover art image and music file are provided
// Find all related documents in parallel
const [category, subcategory, album, artist, language] = await Promise.all([
Category.findById(categoryId),
Subcategory.findById(subcategoryId),
Album.findById(albumId),
Artist.findById(artistId),
Language.findById(languageId)
]);
// Check if all related documents exist
if (!category || !subcategory || !album || !artist || !language) {
const missingEntities = [];
if (!category) missingEntities.push('Category');
if (!subcategory) missingEntities.push('Subcategory');
if (!album) missingEntities.push('Album');
if (!artist) missingEntities.push('Artist');
if (!language) missingEntities.push('Language');
const errorMessage = `The following entities were not found: ${missingEntities.join(', ')}.`;
return res.status(404).json({ error_code: 404, message: errorMessage });
}
// Extract file paths
const coverArtImagePath = coverArtImage[0].path;
const musicFilePath = musicFile[0].path;
// Construct the image URL for cover art
const baseUrl = `${req.protocol}://${req.get('host')}`;
const coverArtImageUrl = `${baseUrl}/${coverArtImagePath}`;
// Create the new song
const newSong = await Song.create({
categoryId,
subcategoryId,
albumId,
artistId,
title,
musicLink,
trackerID,
lyrics,
languageId,
coverArtImage: {
filename: coverArtImage[0].filename,
fileAddress: coverArtImagePath,
imageUrl: coverArtImageUrl // Add imageUrl to coverArtImage object
},
musicFile: {
filename: musicFile[0].filename,
fileAddress: musicFilePath
}
});
// Return success response with the new song
return res.status(201).json({
error_code: 200,
message: 'Song created successfully',
song: newSong
});
} catch (err) {
console.error('Error inside createSong:', err);
return res.status(500).json({ error_code: 500, message: 'Internal Server Error' });
}
};
const updateSong = async (req, res) => {
try {
const { id } = req.params; // Extract the song ID from the request parameters
const updatedSong = await Song.findByIdAndUpdate(id, req.body, { new: true }); // Find song by ID and update with the request body data
if (!updatedSong) {
return res.status(404).json({ error_code: 404, message: 'Song not found' });
}
return res.status(200).json({ error_code: 200, message: 'Song updated successfully', song: updatedSong });
} catch (err) {
console.error('Error inside updateSong:', err);
return res.status(500).json({ error_code: 500, message: 'Internal Server Error' });
}
};
const deleteSong = async (req, res) => {
try {
const { id } = req.params;
const deletedSong = await Song.findByIdAndDelete(id);
if (!deletedSong) {
return res.status(404).json({ error_code: 404, message: 'Song not found' });
}
return res.status(200).json({ error_code: 200, message: 'Song deleted successfully' });
} catch (err) {
console.error('Error inside deleteSong:', err);
return res.status(500).json({ error_code: 500, message: 'Internal Server Error' });
}
};
const getSong = async (req, res) => {
try {
const { id } = req.params;
const song = await Song.findById(id)
.populate('languageId', 'name')
.populate('artistId', 'ArtistName')
.select('title musicLink trackerID lyrics coverArtImage');
if (!song) {
return res.status(404).json({ error_code: 404, message: 'Song not found' });
}
return res.status(200).json({ error_code: 200, message: 'Song retrieved successfully', song });
} catch (err) {
console.error('Error inside getSong:', err);
return res.status(500).json({ error_code: 500, message: 'Internal Server Error' });
}
};
const changeSongStatus = async (req, res) => {
try {
const { id } = req.params;
const songData = await Song.findById(id);
if (!songData) {
return res.status(400).send({
error_code: 400,
message: 'song not found'
});
}
songData.status = songData.status === 'activate' ? 'deactivate' : 'activate';
await songData.save();
res.status(200).send({
message: `song status toggled successfully to ${songData.status}`,
songData: songData
});
} catch (err) {
console.error('Error inside update admin', err);
res.status(500).send({
error_code: 500,
message: 'Internal Server Error'
});
}
};
const getAllSongs = async (req, res) => {
try {
const { title, artist, category } = req.query;
let query = {};
// Build query object based on search fields
const searchFields = ['title', 'artist', 'category'];
searchFields.forEach(field => {
if (req.query[field]) {
query[field] = { $regex: req.query[field], $options: 'i' };
}
});
// Pagination parameters
const pageNumber = Math.max(1, parseInt(req.query.pageNumber) || 1);
const pageSize = Math.max(1, parseInt(req.query.pageSize) || 10);
// Count total songs based on the query
const totalSongs = await Song.countDocuments(query);
const totalPages = Math.ceil(totalSongs / pageSize);
// Find songs based on the query and pagination
const songs = await Song.find(query)
.populate({ path: 'categoryId', select: 'name' })
.populate({ path: 'albumId', select: 'albumName' })
.populate({ path: 'subcategoryId', select: 'SubCategoriesName' })
.populate({ path: 'artistId', select: 'ArtistName' })
.sort({ title: 1 })
.skip((pageNumber - 1) * pageSize)
.limit(pageSize);
// Check if songs are found
if (songs.length === 0) {
return res.status(404).json({ error_code: 404, message: 'Songs not found' });
}
// Return songs along with pagination details
return res.status(200).json({
error_code: 200,
message: 'Songs retrieved successfully',
songs,
total_pages: totalPages,
current_page: pageNumber
});
} catch (err) {
console.error('Error inside getAllSongs:', err);
return res.status(500).json({ error_code: 500, message: 'Internal server error' });
}
};
module.exports = {
createSong,
updateSong,
deleteSong,
getSong,
getAllSongs,
changeSongStatus
};