Задание 1
Раздели «толстый контроллер» на слои: HTTP, сервис, домен, репозиторий. Объясни, что куда попало и почему.
// routes/orders.js — как есть, 120 строк в одном обработчике
app.post('/api/orders', async (req, reply) => {
const { items, promoCode, address, phone } = req.body;
if (!items || items.length === 0) {
return reply.code(400).send({ error: 'Корзина пуста' });
}
if (!/^\+?[0-9]{10,15}$/.test(phone)) {
return reply.code(400).send({ error: 'Некорректный телефон' });
}
const user = await prisma.user.findUnique({ where: { id: req.userId } });
if (!user) return reply.code(401).send({ error: 'Не авторизован' });
const products = await prisma.product.findMany({
where: { id: { in: items.map(i => i.productId) } },
});
let subtotal = 0;
for (const item of items) {
const p = products.find(x => x.id === item.productId);
if (!p) return reply.code(404).send({ error: 'Товар не найден' });
if (p.stock < item.qty) {
return reply.code(409).send({ error: `Нет в наличии: ${p.title}` });
}
subtotal += p.price * item.qty;
}
let discount = 0;
if (promoCode) {
const promo = await prisma.promo.findUnique({ where: { code: promoCode } });
if (promo && subtotal >= promo.minSubtotal) {
discount = Math.min(Math.round(subtotal * promo.percent / 100), promo.maxDiscount);
}
}
const delivery = (subtotal - discount) >= 5000 ? 0 : 400;
const total = subtotal - discount + delivery;
const order = await prisma.$transaction(async (tx) => {
for (const item of items) {
await tx.product.update({
where: { id: item.productId },
data: { stock: { decrement: item.qty } },
});
}
return tx.order.create({
data: { userId: user.id, total, discount, delivery, address, phone,
items: { create: items.map(i => ({ productId: i.productId, qty: i.qty,
price: products.find(p => p.id === i.productId).price })) } },
include: { items: true },
});
});
await sendEmail(user.email, 'Заказ принят', `Сумма: ${total}`);
console.log('Заказ создан', order.id);
return reply.code(201).send(order);
});
Решение
// ══════ ДОМЕННЫЙ СЛОЙ ══════
// Чистые правила предметной области. Ни БД, ни HTTP, ни логгера.
// Тестируется без единого мока.
// domain/errors.js
export class DomainError extends Error {}
export class EmptyCartError extends DomainError {}
export class OutOfStockError extends DomainError {
constructor(products) { super('Нет в наличии'); this.products = products; }
}
export class ProductNotFoundError extends DomainError {
constructor(ids) { super('Товар не найден'); this.ids = ids; }
}
// domain/pricing.js
const FREE_DELIVERY_FROM = 5000;
const DELIVERY_BASE = 400;
export function calculateSubtotal(lines) {
return lines.reduce((sum, l) => sum + l.price * l.qty, 0);
}
export function calculateDiscount(subtotal, promo) {
if (!promo || subtotal < promo.minSubtotal) return 0;
return Math.min(
Math.round(subtotal * promo.percent / 100),
promo.maxDiscount
);
}
export function calculateDelivery(afterDiscount, region = 'standard') {
if (region === 'pickup') return 0;
return afterDiscount >= FREE_DELIVERY_FROM ? 0 : DELIVERY_BASE;
}
// domain/order-draft.js
export class OrderDraft {
constructor({ user, lines, promo, delivery }) {
this.user = user;
this.lines = lines;
this.promo = promo;
this.deliveryInfo = delivery;
}
// Фабрика: собирает черновик из входных данных и товаров
static from({ items, promo, delivery, user, products }) {
const missing = items
.filter(i => !products.some(p => p.id === i.productId))
.map(i => i.productId);
if (missing.length > 0) throw new ProductNotFoundError(missing);
const lines = items.map(i => {
const product = products.find(p => p.id === i.productId);
return { productId: product.id, title: product.title,
price: product.price, qty: i.qty, stock: product.stock };
});
return new OrderDraft({ user, lines, promo, delivery });
}
validate() {
if (this.lines.length === 0) throw new EmptyCartError();
const unavailable = this.lines.filter(l => l.stock < l.qty);
if (unavailable.length > 0) {
throw new OutOfStockError(
unavailable.map(l => ({ id: l.productId, title: l.title }))
);
}
}
// Цены считаются ЗДЕСЬ, а не берутся из запроса клиента
get amounts() {
const subtotal = calculateSubtotal(this.lines);
const discount = calculateDiscount(subtotal, this.promo);
const delivery = calculateDelivery(subtotal - discount,
this.deliveryInfo.region);
return { subtotal, discount, delivery, total: subtotal - discount + delivery };
}
}
// ══════ СЛОЙ ДАННЫХ ══════
// Только доступ к хранилищу. Никаких бизнес-правил.
// repositories/product-repository.js
export class ProductRepository {
constructor(db) { this.db = db; }
findManyByIds(ids) {
return this.db.product.findMany({
where: { id: { in: ids }, isActive: true },
select: { id: true, title: true, price: true, stock: true },
});
}
}
// repositories/promo-repository.js
export class PromoRepository {
constructor(db) { this.db = db; }
findActiveByCode(code) {
if (!code) return null;
return this.db.promo.findFirst({
where: { code, isActive: true, expiresAt: { gt: new Date() } },
});
}
}
// repositories/order-repository.js
export class OrderRepository {
constructor(db) { this.db = db; }
// Транзакция и защита от гонки — забота этого слоя
async createWithStockReservation(draft) {
const { subtotal, discount, delivery, total } = draft.amounts;
return this.db.$transaction(async (tx) => {
for (const line of draft.lines) {
// Атомарная проверка остатка: между чтением и записью
// товар могли разобрать
const updated = await tx.product.updateMany({
where: { id: line.productId, stock: { gte: line.qty } },
data: { stock: { decrement: line.qty } },
});
if (updated.count === 0) {
throw new OutOfStockError([{ id: line.productId, title: line.title }]);
}
}
return tx.order.create({
data: {
userId: draft.user.id,
subtotal, discount, delivery, total,
status: 'new',
address: draft.deliveryInfo.address,
phone: draft.deliveryInfo.phone,
promoCode: draft.promo?.code ?? null,
items: {
create: draft.lines.map(l => ({
productId: l.productId, qty: l.qty, price: l.price,
})),
},
},
include: { items: true },
});
});
}
}
// ══════ СЕРВИСНЫЙ СЛОЙ ══════
// Сценарий: что происходит при оформлении заказа.
// Знает про репозитории и внешние сервисы, но не про HTTP.
// services/order-service.js
export class OrderService {
constructor({ orders, products, promos, events, logger }) {
this.orders = orders;
this.products = products;
this.promos = promos;
this.events = events;
this.logger = logger;
}
async create(input, user) {
// 1. Собрать данные
const [products, promo] = await Promise.all([
this.products.findManyByIds(input.items.map(i => i.productId)),
this.promos.findActiveByCode(input.promoCode),
]);
// 2. Применить доменные правила
const draft = OrderDraft.from({ ...input, user, products, promo });
draft.validate();
// 3. Сохранить
const order = await this.orders.createWithStockReservation(draft);
// 4. Побочные эффекты — асинхронно, не блокируя ответ
await this.events.publish('order.created', { orderId: order.id });
this.logger.info({ orderId: order.id, total: order.total }, 'Заказ создан');
return order;
}
}
// ══════ HTTP-СЛОЙ ══════
// Тонкий: разобрать запрос, вызвать сервис, перевести ошибки в статусы.
// api/schemas.js
const CreateOrderSchema = z.object({
items: z.array(z.object({
productId: z.number().int().positive(),
qty: z.number().int().min(1).max(99),
})).min(1),
promoCode: z.string().trim().max(32).optional(),
delivery: z.object({
address: z.string().trim().min(5).max(500),
phone: z.string().trim().regex(/^\+?[0-9]{10,15}$/, 'Некорректный телефон'),
region: z.enum(['standard', 'far', 'pickup']).default('standard'),
}),
});
// api/serializers.js — что отдаём наружу
export function serializeOrder(order) {
return {
id: order.id,
total: order.total,
discount: order.discount,
delivery: order.delivery,
status: order.status,
createdAt: order.createdAt,
items: order.items.map(i => ({
productId: i.productId, qty: i.qty, price: i.price,
})),
// internalNote, margin и прочее наружу НЕ уходят
};
}
// api/orders.routes.js
export default async function orderRoutes(app, { orderService }) {
app.post('/api/v1/orders', { preHandler: [app.auth] },
async (request, reply) => {
const input = CreateOrderSchema.parse(request.body);
try {
const order = await orderService.create(input, request.user);
return reply.code(201).send({ data: serializeOrder(order) });
} catch (err) {
// Перевод доменных ошибок в HTTP — работа ИМЕННО этого слоя
if (err instanceof EmptyCartError) {
return reply.code(422).send({
error: { code: 'EMPTY_CART', message: 'Корзина пуста' },
});
}
if (err instanceof OutOfStockError) {
return reply.code(409).send({
error: { code: 'OUT_OF_STOCK', message: 'Часть товаров недоступна',
details: err.products },
});
}
if (err instanceof ProductNotFoundError) {
return reply.code(404).send({
error: { code: 'PRODUCT_NOT_FOUND', details: err.ids },
});
}
throw err; // всё остальное — общий обработчик, 500
}
});
}
// ══════ СБОРКА ══════
// container.js — единственное место, где создаются зависимости
const orderService = new OrderService({
orders: new OrderRepository(prisma),
products: new ProductRepository(prisma),
promos: new PromoRepository(prisma),
events: eventBus,
logger,
});
/* ══════ ЧТО КУДА ПОПАЛО И ПОЧЕМУ ══════
HTTP-слой получил:
• Разбор и валидацию ФОРМАТА запроса (zod)
• Перевод доменных ошибок в коды состояния
• Сериализацию ответа (что показываем наружу)
Почему: это единственное, что связано с протоколом.
Появится CLI или обработчик очереди — этот слой
просто не понадобится.
Сервисный слой получил:
• Порядок шагов сценария
• Оркестрацию репозиториев и внешних сервисов
• Побочные эффекты (события, логи)
Почему: это «что делает система», без привязки
к способу вызова и способу хранения.
Доменный слой получил:
• Формулы расчёта цены, скидки, доставки
• Правила валидации бизнес-смысла (пустая корзина,
нехватка товара)
• Доменные ошибки
Почему: это правила предметной области. Они не меняются
при смене БД или переходе с REST на GraphQL.
И тестируются мгновенно, без моков.
Слой данных получил:
• Запросы к БД, транзакцию, защиту от гонки
Почему: как именно хранить — деталь реализации.
Замена Prisma на что-то другое затронет только его.
ЧТО УЛУЧШИЛОСЬ ПОМИМО СТРУКТУРЫ
1. Гонка при списании остатка исправлена:
было чтение → проверка → запись (не атомарно),
стало updateMany с условием.
2. Цена больше не может быть подменена клиентом:
считается из данных БД в домене.
3. Промокод проверяется на активность и срок действия
(в исходном коде — нет).
4. Наружу уходит только то, что положено (serializeOrder),
а не вся сущность целиком.
5. console.log заменён структурированным логгером.
6. Отправка письма перенесена в событие: падение почтового
сервиса больше не роняет создание заказа.
7. Расчёт цен покрывается тестами за минуту —
раньше требовался поднятый сервер и база.
*/
Замена чтения-проверки-записи на updateMany с условием — не побочный эффект рефакторинга, а типичная находка: разделение на слои заставляет явно посмотреть на каждый шаг, и гонки, незаметные в стострочном обработчике, становятся очевидными.