Course contentsShow
← Node.js
Lesson 691 of 1,9807. Web Framework Architecture and MiddlewareFree lesson

Domain Entity Modeling

Represent business objects as distinct entities within the request handling flow.

In this lesson, you will learn how to represent your business data as robust, self-contained entities to keep your request handlers clean and focused.

The Problem with Raw Data

When handling HTTP requests in Node.js, it is common to pass raw JSON objects from your req.body directly into database functions. While quick, this often leads to "anemic" code where validation logic, business rules, and data formatting are scattered throughout your routes and controllers. Domain Entity Modeling solves this by encapsulating data into distinct classes or factory functions that represent the "truth" of your business.

From Raw Objects to Domain Entities

Instead of passing generic objects, you wrap incoming data into an entity that understands its own business rules. Consider a User entity:

class User {
  constructor({ id, email, role }) {
    if (!email.includes('@')) throw new Error('Invalid email');
    this.id = id;
    this.email = email;
    this.role = role;
  }

  hasPermission(action) {
    return this.role === 'admin' || action === 'read';
  }
}

In your request handler, you convert the incoming payload into this entity immediately:

app.post('/update-profile', (req, res) => {
  try {
    // Mapping raw input to a Domain Entity
    const user = new User(req.body);
    
    if (user.hasPermission('write')) {
      // Proceed with logic using the entity
    }
  } catch (err) {
    // Handled by our Standardized Error Mapping
    res.status(400).send(err.message);
  }
});

Why this matters

By treating your data as entities rather than plain objects, you achieve three things:

  1. Encapsulation: The logic for what makes a "User" valid lives in one place, not spread across every route.
  2. Predictability: When a service function receives a User instance, it is guaranteed to have been validated and structured correctly.
  3. Decoupling: If your database schema changes, you update the entity constructor, not every individual route handler in your application.

By establishing these boundaries, you transform your codebase from a collection of loosely coupled request handlers into a structured system that mirrors the actual domain of your business.

Key Takeaway: Domain Entity Modeling encapsulates your business logic into objects that define, validate, and protect your data, ensuring your controllers remain thin and focused on traffic flow rather than data manipulation.