Clean Architecture in ExpressJS
- User
Clean Architecture in ExpressJS
- Assistant
Clean Architecture is a design philosophy introduced by Robert C. Martin (Uncle Bob) that focuses on creating software that is easy to understand, maintain, and test. Here's how you can apply Clean Architecture principles to an ExpressJS application:
- Entities: These are the business objects of your application. They are defined by the business rules and are independent of any other concerns such as data access, UI, etc.
javascript// user.entity.js class User { constructor(id, name, email) { this.id = id; this.name = name; this.email = email; } } module.exports = User;- Use Cases: Use cases represent the specific business rules of your application. They orchestrate the flow of data and interact with entities and other use cases.
javascript// create-user.use-case.js const User = require('../entities/user.entity'); class CreateUser { constructor(userRepository) { this.userRepository = userRepository; } async execute(name, email) { const user = new User(null, name, email); return this.userRepository.save(user); } } module.exports = CreateUser;-
Interface Adapters: These are the adapters that convert data from the format most convenient for use cases and entities, to the format convenient for things like the web, the database, etc.
-
Controllers: Handle HTTP requests and responses, and interact with use cases.
javascript// user.controller.js const express = require('express'); const router = express.Router(); class UserController { constructor(createUserUseCase) { this.createUserUseCase = createUserUseCase; } registerRoutes() { router.post('/', async (req, res) => { try { const user = await this.createUserUseCase.execute(req.body.name, req.body.email); res.status(201).json(user); } catch (error) { res.status(400).json({ message: error.message }); } }); return router; } } module.exports = UserController;
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.