76 lines
2.7 KiB
JavaScript
76 lines
2.7 KiB
JavaScript
const DB = require('../../database/mysql');
|
|
|
|
const { Product } = DB;
|
|
|
|
class ProductService {
|
|
static async createProduct(data) {
|
|
return Product.create(data);
|
|
}
|
|
|
|
static async getAllProducts() {
|
|
return Product.findAll({
|
|
order: [['createdAt', 'DESC']],
|
|
});
|
|
}
|
|
|
|
static async getProductsByUserId(ownerId) {
|
|
return Product.findAll({
|
|
where: { ownerId },
|
|
include: [
|
|
{
|
|
model: DB.User,
|
|
as: 'owner',
|
|
attributes: ['username', 'email'],
|
|
},
|
|
],
|
|
order: [['createdAt', 'DESC']],
|
|
});
|
|
}
|
|
|
|
static async getProductBySlug(slug) {
|
|
const products = await Product.findAll({
|
|
where: { slug },
|
|
include: [
|
|
{ model: DB.Category, as: "productCategories", attributes: ["name"], through: { attributes: [] } },
|
|
{ model: DB.Tag, as: "productTags", attributes: ["name"], through: { attributes: [] } },
|
|
{ model: DB.User, as: "owner", attributes: { exclude: ["email", "phone", "salt", "hash"] } }
|
|
],
|
|
order: [['createdAt', 'DESC']],
|
|
});
|
|
//let product = products[0];
|
|
|
|
return products[0];
|
|
}
|
|
|
|
static async getProductsByCategory(category) {
|
|
const limit = 100, offset = 0;
|
|
|
|
const products = await Product.findAndCountAll({
|
|
include: [
|
|
{ model: DB.Brand, as: "brand", attributes: ["name", "description"] },
|
|
{ model: DB.Category, as: "productCategories", attributes: ["slug", "name", "description"], through: { attributes: [] }, ...(category && { where: { slug: category } }), },
|
|
{ model: DB.Tag, as: "productTags", attributes: ["name"], through: { attributes: [] } },
|
|
{ model: DB.User, as: "owner", attributes: { exclude: ["email", "phone", "salt", "hash"] } }
|
|
],
|
|
limit: parseInt(limit),
|
|
offset: offset * limit,
|
|
order: [["createdAt", "DESC"]],
|
|
//where: { categoryId: 4 },
|
|
distinct: true,
|
|
});
|
|
/*
|
|
const products = await Product.findAll({
|
|
where: { category },
|
|
include: [
|
|
{ model: DB.Category, as: "productCategories", attributes: ["name"], through: { attributes: [] } },
|
|
{ model: DB.Tag, as: "productTags", attributes: ["name"], through: { attributes: [] } },
|
|
{ model: DB.User, as: "owner", attributes: { exclude: ["email", "phone", "salt", "hash"] } }
|
|
],
|
|
order: [['createdAt', 'DESC']],
|
|
});
|
|
*/
|
|
return products;
|
|
}
|
|
}
|
|
|
|
module.exports = ProductService; |