0
0
Expressframework~5 mins

DTO pattern for data transfer in Express

Choose your learning style9 modes available
Introduction

The DTO pattern helps move data between parts of an app clearly and safely. It keeps data organized and easy to manage.

When sending user data from a client to a server in an API.
When you want to control exactly what data is sent or received.
When you need to validate or format data before using it.
When separating database models from what the app exposes.
When working with multiple layers like controllers and services.
Syntax
Express
class UserDTO {
  constructor({ id, name, email }) {
    this.id = id;
    this.name = name;
    this.email = email;
  }
}

// Usage example:
const dto = new UserDTO({ id: 1, name: 'Alice', email: 'alice@example.com' });

A DTO is usually a simple class or object that holds only the data you want to transfer.

It often has a constructor to set its properties from raw input.

Examples
This DTO holds product data with only id, title, and price fields.
Express
class ProductDTO {
  constructor({ id, title, price }) {
    this.id = id;
    this.title = title;
    this.price = price;
  }
}
This DTO is for creating a user and only includes name and email, ignoring other fields.
Express
class CreateUserDTO {
  constructor(data) {
    this.name = data.name;
    this.email = data.email;
  }
}
This DTO is for sending user data back to clients, hiding sensitive info like password.
Express
class UserResponseDTO {
  constructor(user) {
    this.id = user.id;
    this.name = user.name;
  }
}
Sample Program

This Express app uses a UserDTO class to accept user data in a POST request. It creates a DTO from the request body and sends it back as JSON. This keeps data structured and clear.

Express
import express from 'express';

class UserDTO {
  constructor({ id, name, email }) {
    this.id = id;
    this.name = name;
    this.email = email;
  }
}

const app = express();
app.use(express.json());

app.post('/users', (req, res) => {
  // Create DTO from request body
  const userDto = new UserDTO(req.body);

  // Here you could save userDto to database or process it

  // Send back the DTO as confirmation
  res.json(userDto);
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
OutputSuccess
Important Notes

DTOs help keep your app's data clean and separate from database or UI details.

Always validate data before creating a DTO to avoid errors.

DTOs can make your code easier to test and maintain.

Summary

DTOs are simple objects to move data clearly between app parts.

They help control what data is sent or received.

Using DTOs improves code organization and safety.