The DTO pattern helps move data between parts of an app clearly and safely. It keeps data organized and easy to manage.
DTO pattern for data transfer in 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.
class ProductDTO {
constructor({ id, title, price }) {
this.id = id;
this.title = title;
this.price = price;
}
}class CreateUserDTO {
constructor(data) {
this.name = data.name;
this.email = data.email;
}
}class UserResponseDTO {
constructor(user) {
this.id = user.id;
this.name = user.name;
}
}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.
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'); });
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.
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.
Practice
DTO (Data Transfer Object) in an Express application?Solution
Step 1: Understand the role of DTOs
DTOs are simple objects designed to carry data between parts of an application clearly and safely.Step 2: Identify the correct purpose in Express context
In Express, DTOs help control what data is sent or received, improving code clarity and security.Final Answer:
To clearly define and control the data sent between different parts of the app -> Option AQuick Check:
DTO purpose = data control and clarity [OK]
- Confusing DTOs with database or UI code
- Thinking DTOs handle server setup
- Assuming DTOs manage styling
Solution
Step 1: Review class syntax for DTO
A DTO is often a simple class with a constructor to assign properties.Step 2: Check each option's correctness
class UserDTO { constructor(name, email) { this.name = name; this.email = email; } } correctly defines a class with a constructor assigning properties. function UserDTO(name, email) { return { name, email }; } returns an object but is a function, not a class. const UserDTO = { name: '', email: '' }; is a plain object, not a class. let UserDTO = (name, email) => { this.name = name; this.email = email; }; uses arrow function incorrectly with 'this'.Final Answer:
class UserDTO { constructor(name, email) { this.name = name; this.email = email; } } -> Option DQuick Check:
DTO class = constructor with properties [OK]
- Using arrow functions with 'this' in DTOs
- Defining DTO as plain object without constructor
- Returning object from function instead of class
class UserDTO {
constructor(name, email) {
this.name = name;
this.email = email;
}
}
app.post('/user', (req, res) => {
const userDto = new UserDTO(req.body.name, req.body.email);
res.json(userDto);
});Solution
Step 1: Understand DTO construction
The UserDTO constructor only assigns name and email properties, ignoring password.Step 2: Analyze response JSON
The response sends the userDto object, which includes only name and email fields.Final Answer:
{"name":"Alice","email":"alice@example.com"} -> Option BQuick Check:
DTO filters out extra fields [OK]
- Expecting password to be included in response
- Confusing request body with DTO properties
- Assuming all request fields are sent back
class ProductDTO {
constructor(id, name) {
this.id = id;
this.name = name;
}
}
app.post('/product', (req, res) => {
const productDto = ProductDTO(req.body.id, req.body.name);
res.json(productDto);
});Solution
Step 1: Check how DTO instance is created
The code calls ProductDTO as a function without 'new', which is incorrect for classes.Step 2: Understand class instantiation in JavaScript
Classes must be instantiated with 'new' keyword to create an object.Final Answer:
Missing 'new' keyword when creating ProductDTO instance -> Option CQuick Check:
Class instantiation requires 'new' [OK]
- Calling class like a regular function
- Confusing res.send and res.json usage
- Thinking DTO must be a function, not class
title and description in an Express app. Which approach correctly enforces this validation inside the DTO class?Solution
Step 1: Understand validation needs
The DTO must check that title and description are non-empty strings and throw errors if not.Step 2: Evaluate each option's validation
class TaskDTO { constructor(title, description) { if (!title || typeof title !== 'string') throw new Error('Invalid title'); if (!description || typeof description !== 'string') throw new Error('Invalid description'); this.title = title; this.description = description; } } explicitly checks and throws errors for invalid inputs. class TaskDTO { constructor(title, description) { this.title = title || 'default'; this.description = description || 'default'; } } assigns defaults instead of validating. class TaskDTO { constructor(title, description) { this.title = title; this.description = description; } } assigns without checks. function createTaskDTO(title, description) { return { title, description }; } is a function without validation.Final Answer:
class TaskDTO { constructor(title, description) { if (!title || typeof title !== 'string') throw new Error('Invalid title'); if (!description || typeof description !== 'string') throw new Error('Invalid description'); this.title = title; this.description = description; } } -> Option AQuick Check:
Validation inside constructor = class TaskDTO { constructor(title, description) { if (!title || typeof title !== 'string') throw new Error('Invalid title'); if (!description || typeof description !== 'string') throw new Error('Invalid description'); this.title = title; this.description = description; } } [OK]
- Skipping validation and assigning defaults silently
- Using functions without validation for DTOs
- Not throwing errors on invalid data
Ready to prove it?
Pass the test and this pattern moves unknown
