kibe
kibe

Reputation: 181

Are controllers inside the application layer or infrastructure layer? Should I even use controllers in Clean Architecture?

As far as I can understand, Clean Architecture/DDD states that your use cases can be triggered by anything, let it be a HTTP request or GUI, correct?

I am trying to emulate that, but I am not really sure if I am doing it correctly.

Inside my infrastructure folder, I have routers. For example:

import express from 'express'
import UserController from '../controllers/user_controller.js'
import ExpressRouterAdapter from './ExpressRouterAdapter.js'

export default function UsersRouter () {
  const router = express.Router()

  router.route('/:username').get(ExpressRouterAdapter.adapt(UserController.getUser))

  return router
}

(ExpressRouterAdapter is just an adapter that transforms Express requests into a simple httpRequest JS object)

And here is my GetUser controller:

export class GetUser {
  constructor ({ FindUserService }) {
    this.findUser = FindUserService
  }

  async handle (httpRequest = {}) {
    try {
      const { username } = httpRequest.params

      if (!username) {
        return {
          statusCode: 400,
          body: 'Missing username parameter.'
        }
      }

      const user = await this.findUser.execute(username) 

      // ...

I have a few questions:

  1. Should I even have controllers? Should the Router direct it to the use-case/service directly?
  2. ^^ The reason I ask that is because my controllers are really HTTP centered. For example some of them are called: PostUser, GetUser, DeleteUser. So I am guessing they should be inside the infrastructure folder, right?

I am guessing that controllers are ONLY used if your delivery mechanism is a web app, right?

Upvotes: 3

Views: 2293

Answers (1)

Alexey Zimarev
Alexey Zimarev

Reputation: 19640

You're right. There's nothing really to do with DDD because DDD is about contexts and language, but for clean architecture and ports and adapters that's the correct thought.

Normally, you would have the structure like this:

enter image description here

So, your application exposes an API that represents a port and you can connect different edge components that implement a physical delivery protocol of different kinds to talk to your application.

Upvotes: 9

Related Questions