Skip to content

controller ve service birbirinden ayrılmalı #65

@saracalihan

Description

@saracalihan

Router içinde veritabanı ile ilgili business logic yapılmamalı bunun yerine ilgili işlemler fonksiyon haline getirilip service olarak kullanılmalı.

// src/services/content.js
const getContent = (slug) => {
try {
    const content = await models.contents.findOne({
      where: {
        slug,
      },
      include: [
        {
          model: models.images,
          as: 'image',
        },
        {
          model: models.users,
          as: 'user',
        },
      ],
    });

    if (!content) {
      return {
        errors: [
          {
            message: 'Content not found or you don\'t have a permission!',
          },
        ],
      };
    }
    content.views += 1;
    await content.save();
    return content;
  } catch (err) {
    return {
      errors: [
        {
          message: err.message,
        },
      ],
    };
  }
};

 const ContentService = {
  getContent,
};
export default ContentService;

Service içinde sadece veritabanı ile konuşma fonksiyonun ismine göre veritabanı ile konuşma işlemi yapılmalıdır. Alakasız hiçbir işlem yapılmamalıdır.

// src/routes/content.js
import ContentService from '../services/content.js';

// ...

const updateContentSchema = {
  body: Joi.object({
    name: Joi.string()
      .max(50),
    type: Joi.string()
      .min(0)
      .max(10),
    description: Joi.string()
      .max(250),
    image_path: Joi.string()
      .max(250),
  }),
};

// ...

const update = (req, res) =>{ // Controller
const { error } = updateContentSchema.body.validate(req.body);
  if (error) {
    return res.status(400).send({
      errors: error.details,
    });
  }

  const { slug } = req.params;
  try{
    let content = await ContentService.getContent(slug);
    await ContentService.updateContent(updateableFieldsFromBody, content.id);
  } catch(error){
    next(error);
  };
};

export default {
  prefix: '/contents',
  inject: (router) => {
    // ...
    router.put('/:slug', update);
  },
};

Metadata

Metadata

Assignees

Labels

invalidThis doesn't seem right

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions