0
0
Expressframework~30 mins

Repository pattern for data access in Express - Mini Project: Build & Apply

Choose your learning style9 modes available
Repository pattern for data access in Express
📖 Scenario: You are building a simple Express app that manages a list of books. To keep your code clean and organized, you will use the repository pattern to handle data access. This means you will create a separate module that manages the books data, so your main app code stays simple and easy to maintain.
🎯 Goal: Build a repository module that stores books data and provides methods to get all books and add a new book. Then use this repository in an Express route to show all books.
📋 What You'll Learn
Create a books array with initial book objects
Create a BookRepository object with methods to get all books and add a book
Use the repository methods inside an Express route to send the list of books as JSON
Set up a basic Express server listening on port 3000
💡 Why This Matters
🌍 Real World
The repository pattern helps keep your Express app organized by separating data access from route handling. This makes your code easier to maintain and test.
💼 Career
Many backend jobs require clean code organization. Using repository pattern is a common practice to manage data access in Node.js and Express applications.
Progress0 / 4 steps
1
DATA SETUP: Create the initial books data array
Create a variable called books that is an array containing these two book objects exactly: { id: 1, title: 'The Hobbit' } and { id: 2, title: '1984' }.
Express
Need a hint?

Use const books = [ ... ] and include the two objects inside the array.

2
CONFIGURATION: Create the BookRepository object
Create a constant called BookRepository that is an object with two methods: getAll which returns the books array, and add which takes a book parameter and pushes it into the books array.
Express
Need a hint?

Define BookRepository as an object with two functions: getAll and add.

3
CORE LOGIC: Use the repository in an Express route
Create an Express app by requiring express and calling express(). Then add a GET route on '/books' that uses BookRepository.getAll() to get all books and sends them as JSON with res.json().
Express
Need a hint?

Use require('express') and express() to create the app. Then add a GET route on /books that sends JSON from the repository.

4
COMPLETION: Start the Express server on port 3000
Add a line to start the Express app listening on port 3000 using app.listen(3000).
Express
Need a hint?

Use app.listen(3000) to start the server on port 3000.