You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

98 lines
3.2 KiB
JavaScript

import Video from '../models/Video.js';
import Playlist from '../models/Playlist.js';
import Artist from '../models/Artist.js';
import ApiError from '../controllers/ErrorController.js';
class VideoService {
async create({name, videoHQ, videoLQ, playlist, artist}) {
const getArtist = await Artist.findById(artist);
if(!getArtist) {
throw ApiError.BadRequest('Такого исполнителя не существует');
}
if(playlist) {
const getPlaylist = await Playlist.findById(playlist);
if(!getPlaylist) {
throw ApiError.BadRequest('Такого плейлиста не существует');
}
}
const video = await Video.create({name, videoHQ, videoLQ, playlist, artist, date: new Date()});
return {video};
}
async getAll({page, search}) {
const limit = page ? 10 : 0;
const videos = await Video.find({name: {$regex: search || '', $options: 'i'}}).populate([{ path: 'artist', select: 'name' }, { path: 'playlist', select: 'name' }]).skip(page * limit).limit(limit).sort({_id: -1});
const count = await Video.countDocuments({name: {$regex: search || '', $options: 'i'}});
return {videos, count: Math.ceil(count/limit)};
}
async getOne() {
const video = await Video.aggregate([
{ $sample: { size: 1 } },
{
$lookup:
{
from: 'artists',
localField: 'artist',
foreignField: '_id',
as : "artist"
},
},
{
$lookup:
{
from: 'playlists',
localField: 'playlist',
foreignField: '_id',
as : "playlist"
},
},
]);
if(!video) {
throw ApiError.BadRequest('Видео не существует');
}
const oneVideo = video[0];
return {video: oneVideo};
}
async edit({id, name, videoHQ, videoLQ, playlist, artist}) {
if(artist) {
const getArtist = await Artist.findById(artist);
if(!getArtist) {
throw ApiError.BadRequest('Такого исполнителя не существует');
}
}
if(playlist) {
const getPlaylist = await Playlist.findById(playlist);
if(!getPlaylist) {
throw ApiError.BadRequest('Такого плейлиста не существует');
}
}
const video = await Video.findByIdAndUpdate(id, {name, videoHQ, videoLQ, playlist, artist}, {returnOriginal: false});
if(!video) {
throw ApiError.BadRequest('Видео не существует');
}
return {video};
}
async delete({id}) {
const video = await Video.findByIdAndDelete(id).select(['login']);
if(!video) {
throw ApiError.BadRequest('Видео не существует');
}
return {video};
}
}
export default new VideoService();