??? Clean Architecture in Node.js: Implementing MVC & Repository Patterns

??? Clean Architecture in Node.js: Implementing MVC & Repository Patterns

After architecting multiple Node.js applications, here's a practical guide to implementing clean, maintainable architecture patterns.

?? MVC Pattern Implementation:

// Model (user.model.js)
class User {
    constructor(id, name, email) {
        this.id = id;
        this.name = name;
        this.email = email;
    }
}

// Controller (user.controller.js)
class UserController {
    async getUser(req, res) {
        try {
            const user = await userService.findById(req.params.id);
            res.json(user);
        } catch (error) {
            res.status(500).send(error.message);
        }
    }
}

// View (if using server-side rendering)
app.set('view engine', 'ejs');        

?? Repository Pattern for Clean Data Access:

// Interface (repository.interface.js)
class IUserRepository {
    findById(id) { throw new Error('Method not implemented'); }
    save(user) { throw new Error('Method not implemented'); }
}

// Implementation (user.repository.js)
class UserRepository extends IUserRepository {
    constructor(database) {
        super();
        this.db = database;
    }

    async findById(id) {
        return this.db.users.findUnique({
            where: { id }
        });
    }

    async save(user) {
        return this.db.users.create({
            data: user
        });
    }
}        

?? Factory Pattern for Object Creation:

// User Factory
class UserFactory {
    static createUser(type, userData) {
        switch(type) {
            case 'ADMIN':
                return new AdminUser(userData);
            case 'CUSTOMER':
                return new CustomerUser(userData);
            default:
                return new RegularUser(userData);
        }
    }
}

// Usage
const user = UserFactory.createUser('ADMIN', {
    name: 'John',
    email: '[email protected]'
});        

?? Benefits of These Patterns:

1. MVC Pattern:

  • Separation of concerns
  • Easier testing
  • Clear code organization

2. Repository Pattern:

  • Database independence
  • Centralized data access logic
  • Easier to implement caching

3. Factory Pattern:

  • Encapsulated object creation
  • Runtime flexibility
  • Reduced code duplication


? Quick Implementation Tips:

// Dependency Injection
class UserService {
    constructor(userRepository) {
        this.userRepository = userRepository;
    }

    async getUser(id) {
        return this.userRepository.findById(id);
    }
}

// Usage with Express
const app = express();
const userRepo = new UserRepository(database);
const userService = new UserService(userRepo);
const userController = new UserController(userService);

app.get('/users/:id', userController.getUser);        

?? Pro Tip: Use dependency injection containers like awilix for better management of dependencies and testing.

?? What design patterns have you found most useful in your Node.js projects? Share your experiences below!

#nodejs #javascript #designpatterns #webdevelopment #programming #architecture #cleancode


要查看或添加评论,请登录

Dhruv Patel的更多文章

社区洞察

其他会员也浏览了