61 lines
1.6 KiB
JavaScript
Executable File
61 lines
1.6 KiB
JavaScript
Executable File
|
||
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(); |