In Express, why do developers use a Data Transfer Object (DTO)?
Think about how data is shaped and controlled when moving between parts of an app.
A DTO defines a clear data structure for transferring data, helping validate and secure the data flow. It does not replace routing or store sessions.
Given this DTO and Express route, what will the server respond with when sending {"name": "Alice", "age": 30, "extra": "ignore"}?
class UserDTO { constructor(data) { this.name = data.name; this.age = data.age; } } app.post('/user', (req, res) => { const userDto = new UserDTO(req.body); res.json(userDto); });
Look at which properties the DTO constructor copies from the input.
The DTO only copies 'name' and 'age' properties, ignoring 'extra'. So the response JSON includes only those two.
Choose the correct DTO class that safely extracts only 'title' and 'content' from input data.
Only include the fields 'title' and 'content' exactly as requested.
Option A includes only 'title' and 'content'. Others add extra fields not requested.
Identify the error when this DTO is used in an Express route:
class ProductDTO {
constructor(data) {
this.name = data.name;
this.price = data.price;
}
}
app.post('/product', (req, res) => {
const product = new ProductDTO();
res.json(product);
});Check how the constructor is called and what arguments it expects.
The constructor expects a data object but is called without arguments, so 'data' is undefined and accessing 'data.name' causes a TypeError.
Consider this function that uses a DTO pattern to filter input data:
function filterUserData(input) {
const allowedFields = ['username', 'email'];
const filteredData = {};
for (const key in input) {
if (allowedFields.includes(key)) {
filteredData[key] = input[key];
}
}
return filteredData;
}
const input = { username: 'bob', email: 'bob@example.com', password: 'secret' };
const filteredData = filterUserData(input);What is the value of filteredData?
Only keys in allowedFields should be included in filteredData.
The function copies only 'username' and 'email' from input, ignoring 'password'. So filteredData has only those two keys.