MusicTopus/src/middleware/Albums.js
Damien Broqua 1251ca1e02 #3 (#25)
Co-authored-by: dbroqua <contact@darkou.fr>
Reviewed-on: #25
Co-authored-by: Damien Broqua <dbroqua@noreply.localhost>
Co-committed-by: Damien Broqua <dbroqua@noreply.localhost>
2022-03-03 17:03:18 +01:00

157 lines
3.6 KiB
JavaScript

import moment from "moment";
import Pages from "./Pages";
import AlbumsModel from "../models/albums";
import ErrorEvent from "../libs/error";
/**
* Classe permettant la gestion des albums d'un utilisateur
*/
class Albums extends Pages {
/**
* Méthode permettant d'ajouter un album dans une collection
* @param {Object} req
* @return {Object}
*/
static async postAddOne(req) {
const { body, user } = req;
const data = {
...body,
discogsId: body.id,
User: user._id,
};
data.released = data.released
? moment(data.released.replace("-00", "-01"))
: null;
delete data.id;
const album = new AlbumsModel(data);
return album.save();
}
/**
* Méthode permettant de récupérer les éléments distincts d'une collection
* @param {String} field
* @param {ObjectId} user
* @return {Array}
*/
static async getAllDistincts(field, user) {
const distincts = await AlbumsModel.find(
{
user,
},
[],
{
sort: {
[field]: 1,
},
}
).distinct(field);
return distincts;
}
/**
* Méthode permettant de récupérer la liste des albums d'une collection
* @return {Object}
*/
async getAll() {
const {
page = 1,
limit = 4,
sort = "artists_sort",
order = "asc",
artists_sort,
format,
} = this.req.query;
const skip = (page - 1) * limit;
const where = {};
if (artists_sort) {
where.artists_sort = artists_sort;
}
if (format) {
where["formats.name"] = format;
}
const count = await AlbumsModel.count({
user: this.req.user._id,
...where,
});
const rows = await AlbumsModel.find(
{
user: this.req.user._id,
...where,
},
[],
{
skip,
limit,
sort: {
[sort]: order.toLowerCase() === "asc" ? 1 : -1,
},
}
);
return {
rows,
count,
};
}
/**
* Méthode permettant de supprimer un élément d'une collection
* @return {Boolean}
*/
async deleteOne() {
const res = await AlbumsModel.findOneAndDelete({
user: this.req.user._id,
_id: this.req.params.itemId,
});
if (res) {
return true;
}
throw new ErrorEvent(404, "Impossible de trouver cet album");
}
/**
* Méthode permettant de créer la page "ma-collection"
*/
async loadMyCollection() {
const artists = await Albums.getAllDistincts(
"artists_sort",
this.req.user._id
);
const formats = await Albums.getAllDistincts(
"formats.name",
this.req.user._id
);
this.setPageContent("artists", artists);
this.setPageContent("formats", formats);
}
/**
* Méthode permettant d'afficher le détails d'un album
*/
async loadItem() {
const { itemId: _id } = this.req.params;
const { _id: User } = this.req.user;
const item = await AlbumsModel.findOne({
_id,
User,
});
this.setPageContent("item", item);
}
}
export default Albums;