Performance: DTO pattern for data transfer
This pattern affects how data is prepared and sent over the network, impacting response size and serialization time.
class UserDTO { constructor(user) { this.id = user.id; this.name = user.name; this.email = user.email; } } app.get('/user', (req, res) => { const user = getUserFromDb(); const dto = new UserDTO(user); res.json(dto); // sends only needed fields });
app.get('/user', (req, res) => { const user = getUserFromDb(); res.json(user); // sends entire user object including sensitive and unnecessary fields });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Sending full data object | N/A | N/A | High due to large JSON parsing | [X] Bad |
| Sending DTO with minimal fields | N/A | N/A | Low due to smaller JSON parsing | [OK] Good |
DTO (Data Transfer Object) in an Express application?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);
});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);
});title and description in an Express app. Which approach correctly enforces this validation inside the DTO class?Pass the test and this pattern moves unknown