Мой контроллер слишком сцеплен?

Чтобы выразить это в контексте, у меня было задание пройти собеседование в Node.JS, которое в основном делает CRUD с продуктами (и у него есть определенные условия). Задание было понятным, и мне это удалось. После того, как компания проверила мой код, я получил отказ, потому что одной из основных причин (наряду с невыполнением модульного теста, неправильным комментарием кода и т. Д.) Было то, что

  • «Огромная муфта контроллера» и Модель находится в ProductService.

Я на самом деле смущен этим предложением, потому что я использовал шаблон служб и репозитория и разделял все проблемы следующим образом (структура папки):

  • Контроллеры Отвечает за контроль потока выполнения приложения
  • Модели Объект ORM базы данных
  • Репозитории обработка табличных данных через модели
  • Услуги отвечает за бизнес-логику

Маршрутизатор продукта (импорт в мой индексный маршрутизатор)

const router = require('koa-router')();
const ProductController = require('../../app/controllers/product.controller');
const AuthMiddleware = require('../../middleware/authValidation')

// router.get('location', ErpApiController.getLocation)

router.get("https://codereview.stackexchange.com/", ProductController.searchAllProducts);                                             // GET /api/v1/products/
router.get('code/:code', ProductController.searchProductByCode);                                  // GET /api/v1/products/code/:code
router.get('name/:name', ProductController.searchProductByName);                                  // GET /api/v1/products/name/:name
router.get('brand/:brand', ProductController.searchProductByBrand);                               // GET /api/v1/products/brand/:brand
router.get('category/:category', ProductController.searchProductByCategory);                      // GET /api/v1/products/brand/:brand

Вот мой Контроллер продукта

const productService = require("../services/product.service");

exports.searchAllProducts = async (ctx) => {
  const result = await productService.getAllProducts();
  ctx.body = result;
}

exports.searchProductByCode = async (ctx) => {
  const result = await productService.getAllProductByCode(ctx.params.code)
  ctx.body = result;
}

exports.searchProductByName = async (ctx) => {
  const result = await productService.getAllProductByName(ctx.params.name)
  ctx.body = result;
}
....

Репозиторий продуктов

const models = require("../models");
const Sequelize = require("sequelize");

exports.fetchAllProduct = async () => {
  return await models.Products.findAll({
    include: [
      // {
      //   model: models.Brands,
      //   as: "brand",
      //   attributes: { exclude: ['id', 'description', 'category_ID', 'createdAt', 'updatedAt'] },
      // },
      {
        model: models.ProductSizes,
        as: "sizes",
        attributes: { exclude: ['id', 'description', 'product_code', 'createdAt', 'updatedAt'] },
      },
      {
        model: models.Categories,
        as: "category",
        attributes:  ['name'],
        through: {
          attributes: [],
        }
      },
    ],
  });
}

exports.fetchProductByCode = async (code) => {
  return models.Products.findOne({
    where: {
      code: code,
    },
    include: [
      {
        model: models.ProductSizes,
        as: "sizes",
        attributes: { exclude: ['description', 'product_code', 'createdAt', 'updatedAt'] },
      },
      {
        model: models.Categories,
        as: "category",
        attributes:  ['name'],
        through: {
          attributes: [],
        }
      },
    ],
  })
}

Сервисный файл продукта

const dateFormat = require("../../utils/dateUtil");
const productRepo = require("../repositories/product.repository");
const productSizeRepo = require("../repositories/productSize.repository");
const productCateRepo = require("../repositories/productCategory.repository");
const categoryRepo = require("../repositories/category.repository");
const _ = require("lodash");



exports.getAllProducts = async () => {
  return await productRepo.fetchAllProduct();
}

exports.getAllProductByCode = async (ctxcode) => {
  const data = await productRepo.fetchProductByCode(ctxcode)

  if(!data) {
    return {
      code: "204",
      success: true,
      data: [],
    };
  }

  const products = [];
    
    products.push({
      code: data.code,
      name: data.name,
      description: data.description,
      img_url: data.img_url,
      product_url: data.product_url,
      brand_name: data.brand_name,
      color: data.color,
      start_period: dateFormat.dateFormat(data.start_period),
      end_period: dateFormat.dateFormat(data.end_period),
      isActive: data.isActive,
      sizes: data.sizes,
      categories: data.category
    })

  return {
    code: "200",
    success: true,
    count: products.length,
    message: "",
    data: products,
  };
}

exports.getAllProductByName = async (name) => {
  const data = await productRepo.fetchProductByName(name)

  if(!data) {
    return {
      code: "204",
      success: true,
      data: [],
    };
  }

  const products = [];
  for(let i =0; i < data.length; i++) 
  {
    products.push({
      code: data[i].code,
      name: data[i].name,
      description: data[i].description,
      img_url: data[i].img_url,
      product_url: data[i].product_url,
      brand_name: data[i].brand_name,
      color: data[i].color,
      start_period: dateFormat.dateFormat(data[i].start_period),
      end_period: dateFormat.dateFormat(data[i].end_period),
      isActive: data[i].isActive,
      sizes: data[i].sizes,
      categories: data[i].category
    })
  }

  return {
    code: "200",
    success: true,
    data: products,
  };

}

Хотелось бы узнать, что вы думаете по этому поводу и как я могу улучшить архитектуру

0

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *