0
0
Expressframework~30 mins

DTO pattern for data transfer in Express - Mini Project: Build & Apply

Choose your learning style9 modes available
DTO Pattern for Data Transfer in Express
📖 Scenario: You are building a simple Express server that manages user data. To keep your code clean and safe, you want to use the DTO (Data Transfer Object) pattern. This means you will create a special object that only sends the needed user information to the client, hiding sensitive details like passwords.
🎯 Goal: Build an Express route that sends user data using a DTO object. The DTO will include only the user's id, name, and email, excluding the password.
📋 What You'll Learn
Create a user object with id, name, email, and password
Create a UserDTO class that takes a user object and stores only id, name, and email
Create an Express route /user that returns the UserDTO as JSON
Use the DTO pattern to send only safe user data to the client
💡 Why This Matters
🌍 Real World
Using DTOs helps protect sensitive data when sending information from a server to a client, which is important in real web applications to keep user data safe.
💼 Career
Understanding and implementing the DTO pattern is a common task for backend developers working with APIs, especially in Node.js and Express environments.
Progress0 / 4 steps
1
Create the user data object
Create a constant called user with these exact properties and values: id set to 1, name set to "Alice", email set to "alice@example.com", and password set to "secret123".
Express
Need a hint?

Use const user = { id: 1, name: "Alice", email: "alice@example.com", password: "secret123" }.

2
Create the UserDTO class
Create a class called UserDTO with a constructor that takes one parameter user. Inside the constructor, set this.id to user.id, this.name to user.name, and this.email to user.email. Do not include the password.
Express
Need a hint?

Define class UserDTO with a constructor that copies only id, name, and email from the user.

3
Set up Express and create the /user route
Import Express by writing import express from 'express'. Create an Express app by calling express() and store it in a constant called app. Then create a GET route at /user that sends a new UserDTO created from the user object as JSON.
Express
Need a hint?

Use import express from 'express', then const app = express(), and create a GET route with app.get('/user', (req, res) => { res.json(new UserDTO(user)) }).

4
Start the Express server
Add a line to start the Express server by calling app.listen on port 3000. Inside the listen callback, log the string "Server running on port 3000".
Express
Need a hint?

Use app.listen(3000, () => { console.log("Server running on port 3000") }) to start the server.