em-shop/stocks/src/service/product-service.js
2024-11-20 09:53:03 +05:00

61 lines
1.6 KiB
JavaScript
Executable File
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import ProductModel from '../models/product-model.js';
import ApiError from '../exceptions/api-error.js';
import rabbitMqService from '../rabbitmq.js';
import { Op } from 'sequelize';
class ProductService {
async createProduct(plu, name) {
const existingProduct = await ProductModel.findOne({ where: { plu }});
if (existingProduct) {
throw ApiError.BadRequest('Продукт с таким PLU уже существует');
}
const product = await ProductModel.create({ plu, name });
rabbitMqService.sendToQueue({
action: 'createProduct',
shop_id: null,
plu: product.plu,
oldData: null,
newData: product
});
return product;
}
async getProducts(
plu = null,
name = null,
page = 1,
pageSize = 10
) {
const offset = (page - 1) * pageSize;
const limit = pageSize;
const where = {};
if(plu) where.plu = plu;
if(name) where.name = {[Op.iLike]: `%${name}%`};
const products = await ProductModel.findAndCountAll({ limit, offset, where });
const totalPages = Math.ceil(products.count / pageSize);
rabbitMqService.sendToQueue({
action: 'getProducts',
shop_id: null,
plu,
oldData: null,
newData: null
});
return {
products: products.rows,
page,
pageSize,
totalPages,
totalProducts: products.count
}
}
}
export default new ProductService();