Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
115 changes: 51 additions & 64 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,55 +1,60 @@

# Clean code Architecture pattern applied to Digital Market Place API.
# Clean code Architecture pattern applied to Node.js REST API Example


<div style="width:100%; text-align:center">
<img src="public/images/clean-code_arch.jpeg" width="600">
</div>

A Node.js REST API for a digital marketplace, structured according to Uncle Bob's Clean Architecture principles. This project demonstrates separation of concerns, testability, and scalability by organizing code into distinct layers: Enterprise Business Rules, Application Business Rules, Interface Adapters, and Frameworks & Drivers.
**Objective:**

> This project demonstrates how to apply Uncle Bob's Clean Architecture principles in a Node.js REST API. It is designed as an educational resource to help developers structure their projects for maximum testability, maintainability, and scalability. The codebase shows how to keep business logic independent from frameworks, databases, and delivery mechanisms.

## Stack

## Table of Contents
- **Node.js** (Express.js) for the REST API
- **MongoDB** (MongoClient) for persistence
- **Jest** & **Supertest** for unit and integration testing
- **ESLint** & **Prettier** for linting and formatting
- **Docker** & **Docker Compose** for containerization
- **GitHub Actions** for CI/CD

- [Introduction](#introduction)
- [Architecture Overview](#architecture-overview)
- [Features](#features)
- [Getting Started](#getting-started)
- [Project Structure](#project-structure)
- [API Endpoints](#api-endpoints)
- [Testing](#testing)
- [Linting & Formatting](#linting--formatting)
- [Docker & Docker Compose](#docker--docker-compose)
- [CI/CD Workflow](#cicd-workflow)
- [Troubleshooting](#troubleshooting)
- [License](#license)
## Why Clean Architecture?

## Introduction
- **Separation of Concerns:** Each layer has a single responsibility and is independent from others.
- **Dependency Rule:** Data and control flow from outer layers (e.g., routes/controllers) to inner layers (use cases, domain), never the reverse. Lower layers are unaware of upper layers.
- **Testability:** Business logic can be tested in isolation by injecting dependencies (e.g., mock DB handlers) from above. No real database is needed for unit tests.
- **Security & Flexibility:** Infrastructure (DB, frameworks) can be swapped without touching business logic.

This backend API allows users to register, authenticate, and interact with products, blogs, and ratings. It is designed for maintainability and extensibility, following Clean Architecture best practices.
> **✨ Ultimate Flexibility:**
> This project demonstrates that your core business logic is never tied to any specific framework, ORM, or database. You can switch from Express to Fastify, MongoDB to PostgreSQL, or even move to a serverless environment—without rewriting your business rules. The architecture ensures your codebase adapts easily to new technologies, making future migrations and upgrades painless. This is true Clean Architecture in action: your app’s heart beats independently of any tool or vendor.

## Architecture Overview
## How Testing Works

The project is organized into the following layers:
- **Unit tests** inject mocks for all dependencies (DB, loggers, etc.) into use cases and controllers. This means you can test all business logic without a real database or server.
- **Integration tests** can use a real or in-memory database, but the architecture allows you to swap these easily.
- **Example:**
- The product use case receives a `createProductDbHandler` as a parameter. In production, this is the real DB handler; in tests, it's a mock function.
- Lower layers (domain, use cases) never import or reference Express, MongoDB, or any framework code.

- **Enterprise Business Rules**: Core business logic and domain models (`enterprise-business-rules/`).
- **Application Business Rules**: Use cases and application-specific logic (`application-business-rules/`).
- **Interface Adapters**: Controllers, database access, adapters, and middlewares (`interface-adapters/`).
- **Frameworks & Drivers**: Express.js, MongoDB, and other external libraries.
## Project Structure

```
enterprise-business-rules/
entities/ # Domain models (User, Product, Rating, Blog)
validate-models/ # Validation logic for domain models
application-business-rules/
use-cases/ # Application use cases (products, user)
use-cases/ # Application use cases (products, user, blog)
interface-adapters/
controllers/ # Route controllers for products, users
controllers/ # Route controllers for products, users, blogs
database-access/ # DB connection and data access logic
adapter/ # Adapters (e.g., request/response)
middlewares/ # Auth, logging, error handling
routes/ # Express route definitions
public/ # Static files and HTML views
```


## Features

- User registration and authentication (JWT)
Expand Down Expand Up @@ -84,10 +89,10 @@ public/ # Static files and HTML views
```bash
yarn install
```
3. Create a `.env` file in the root with your environment variables (see `.env.example` if available):
3. Create a `.env` file in the root with your environment variables:
```env
PORT=5000
MONGODB_URI=mongodb://localhost:27017/your-db
MONGO_URI=mongodb://localhost:27017/your-db
JWT_SECRET=your_jwt_secret
```
4. Start the server:
Expand All @@ -97,49 +102,37 @@ public/ # Static files and HTML views
yarn start
```

The server will run at [http://localhost:5000](http://localhost:5000).

## Project Structure

- `index.js` - Main entry point, sets up Express, routes, and middleware
- `routes/` - Express route definitions for products, users, blogs
- `interface-adapters/` - Controllers, DB access, adapters, and middleware
- `application-business-rules/` - Use cases for products and users
- `enterprise-business-rules/` - Domain models and validation logic
- `public/` - Static HTML views (landing page, 404)

## API Endpoints

### Products
See the `routes/` directory for all endpoints. Example:

- `POST /products/` - Create a new product
- `GET /products/` - Get all products
- `GET /products/:productId` - Get a product by ID
- `PUT /products/:productId` - Update a product
- `DELETE /products/:productId` - Delete a product
- `POST /products/:productId/:userId/rating` - Rate a product

### Users & Auth

- `POST /users/register` - Register a new user
- `POST /users/login` - User login
- `GET /users/profile` - Get user profile (auth required)

### Blogs

- `GET /blogs/` - Get all blogs
- `POST /blogs/` - Create a new blog

> More endpoints and details can be found in the route files under `routes/`.
## API Documentation & Models (Swagger UI)

- Interactive API docs are available at `/api-docs` when the server is running.
- All endpoints are documented with request/response schemas using Swagger/OpenAPI.
- **Models:**
- Each resource (User, Product, Blog) has two main schemas:
- **Input Model** (e.g., `UserInput`, `ProductInput`, `BlogInput`): What the client sends when creating or updating a resource. Only includes fields the client can set (e.g., no `_id`, no server-generated fields).
- **Output Model** (e.g., `User`, `Product`, `Blog`): What the API returns. Includes all fields, including those generated by the server (e.g., `_id`, `role`, etc.).
- This separation improves security, clarity, and validation.
- You can view and try all models in the "Schemas" section of Swagger UI.
- check at http://localhost:5000/api-docs. /_ (:5000 depend on you chosen port) _/

## Testing

- Tests are written using [Jest](https://jestjs.io/) and [Supertest](https://github.com/visionmedia/supertest).
- **Unit tests** (Jest): Test business logic in isolation by injecting mocks for all dependencies. No real DB required.
- **Integration tests** (Supertest): Test the full stack, optionally with a real or in-memory DB.
- To run all tests:
```bash
yarn test
```
- Test files are located in the `tests/` directory.
- Test files are in the `tests/` directory.

## Linting & Formatting

Expand All @@ -160,7 +153,7 @@ The server will run at [http://localhost:5000](http://localhost:5000).
docker-compose up --build
```
- The app will be available at [http://localhost:5000](http://localhost:5000).
- The MongoDB service runs at `mongodb://localhost:27017/cleanarchdb`.
- The MongoDB service runs at `mongodb://mongo:27017/cleanarchdb` (inside Docker) or `localhost:27017` (locally).
- To stop and remove containers, networks, and volumes:
```bash
docker-compose down -v
Expand All @@ -169,18 +162,12 @@ The server will run at [http://localhost:5000](http://localhost:5000).
## CI/CD Workflow

- GitHub Actions workflow is set up in `.github/workflows/ci-cd.yml`.
- On push to `main`, the workflow:
- Installs dependencies
- Lints and formats code
- Runs tests
- Builds a Docker image
- Pushes the image to Docker Hub (update credentials and repo in workflow and GitHub secrets)
- On push to `main`, the workflow lints, tests, builds, and pushes a Docker image.

## Troubleshooting

- Common issues and solutions are documented in [troubleshooting.md](./troubleshooting.md).
- Please add new issues and solutions as you encounter them.
- See [troubleshooting.md](./troubleshooting.md) for common issues and solutions.

## License

This project is licensed under the ISC License. See the [LICENSE](LICENSE) file for details.
ISC License. See [LICENSE](LICENSE).
7 changes: 4 additions & 3 deletions application-business-rules/use-cases/blogs/blog-handlers.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Blog use cases (Clean Architecture)
module.exports = {
createBlogUseCase: ({ dbBlogHandler, makeBlogModel, logEvents, errorHandlers }) =>
createBlogUseCase: ({ dbBlogHandler, makeBlogModel, logEvents }) =>
async function createBlogUseCaseHandler(blogData) {
try {
const validatedBlog = await makeBlogModel({ blogData });
Expand All @@ -16,7 +16,8 @@ module.exports = {
async function findAllBlogsUseCaseHandler() {
try {
const blogs = await dbBlogHandler.findAllBlogs();
return blogs || [];
// console.log('\n\n from find all blogs use case: ', blogs);
return Object.freeze(blogs.flat().data);
} catch (error) {
logEvents && logEvents(error.message, 'blogUseCase.log');
throw error;
Expand All @@ -35,7 +36,7 @@ module.exports = {
}
},

updateBlogUseCase: ({ dbBlogHandler, makeBlogModel, logEvents, errorHandlers }) =>
updateBlogUseCase: ({ dbBlogHandler, makeBlogModel, logEvents }) =>
async function updateBlogUseCaseHandler({ blogId, updateData }) {
try {
const existingBlog = await dbBlogHandler.findOneBlog({ blogId });
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,8 @@ const findAllProductsUseCase = () =>
async function findAllProductUseCaseHandler({ dbProductHandler, filterOptions }) {
try {
const allProducts = await dbProductHandler.findAllProductsDbHandler(filterOptions);
// console.log("from find all products use case: ", allProducts);
return Object.freeze(allProducts);
// console.log('from find all products use case: ', allProducts);
return Object.freeze(allProducts.data);
} catch (e) {
console.log('Error from fetch all product handler: ', e);
throw new Error(e.message);
Expand Down
67 changes: 33 additions & 34 deletions application-business-rules/use-cases/user/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const userUseCases = require('./user-handlers');
const authUseCases = require('./user-auth-usecases');
const profileUseCases = require('./user-profile-usecases');
const { dbUserHandler } = require('../../../interface-adapters/database-access');
const { makeUser, validateId } = require('../../../enterprise-business-rules/entities');
const { RequiredParameterError } = require('../../../interface-adapters/validators-errors/errors');
Expand All @@ -7,86 +8,84 @@ const { makeHttpError } = require('../../../interface-adapters/validators-errors

const entityModels = require('../../../enterprise-business-rules/entities');

const registerUserUseCaseHandler = userUseCases.registerUserUseCase({
// Auth Use Cases
const registerUserUseCaseHandler = authUseCases.registerUserUseCase({
dbUserHandler,
entityModels,
logEvents,
makeHttpError,
});

const loginUserUseCaseHandler = userUseCases.loginUserUseCase({
const loginUserUseCaseHandler = authUseCases.loginUserUseCase({
dbUserHandler,
logEvents,
makeHttpError,
});

const findOneUserUseCaseHandler = userUseCases.findOneUserUseCase({
const logoutUseCaseHandler = authUseCases.logoutUseCase({ RequiredParameterError, logEvents });
const refreshTokenUseCaseHandler = authUseCases.refreshTokenUseCase({
dbUserHandler,
validateId,
RequiredParameterError,
logEvents,
});

const findAllUsersUseCaseHandler = userUseCases.findAllUsersUseCase({ dbUserHandler, logEvents });
const logoutUseCaseHandler = userUseCases.logoutUseCase({ RequiredParameterError, logEvents });

const refreshTokenUseCaseHandler = userUseCases.refreshTokenUseCase({
const forgotPasswordUseCaseHandler = authUseCases.forgotPasswordUseCase({
dbUserHandler,
RequiredParameterError,
logEvents,
});

const updateUserUseCaseHandler = userUseCases.updateUserUseCase({
const resetPasswordUseCaseHandler = authUseCases.resetPasswordUseCase({
dbUserHandler,
makeUser,
validateId,
RequiredParameterError,
logEvents,
makeHttpError,
});

const deleteUserUseCaseHandler = userUseCases.deleteUserUseCase({
// Profile Use Cases
const findAllUsersUseCaseHandler = profileUseCases.findAllUsersUseCase({
dbUserHandler,
logEvents,
});
const findOneUserUseCaseHandler = profileUseCases.findOneUserUseCase({
dbUserHandler,
validateId,
RequiredParameterError,
logEvents,
});

const blockUserUseCaseHandler = userUseCases.blockUserUseCase({
const updateUserUseCaseHandler = profileUseCases.updateUserUseCase({
dbUserHandler,
makeUser,
validateId,
RequiredParameterError,
logEvents,
makeHttpError,
});

const unBlockUserUseCaseHandler = userUseCases.unBlockUserUseCase({
const deleteUserUseCaseHandler = profileUseCases.deleteUserUseCase({
dbUserHandler,
validateId,
RequiredParameterError,
logEvents,
});

const forgotPasswordUseCaseHandler = userUseCases.forgotPasswordUseCase({
const blockUserUseCaseHandler = profileUseCases.blockUserUseCase({
dbUserHandler,
validateId,
RequiredParameterError,
logEvents,
});

const resetPasswordUseCaseHandler = userUseCases.resetPasswordUseCase({
const unBlockUserUseCaseHandler = profileUseCases.unBlockUserUseCase({
dbUserHandler,
validateId,
RequiredParameterError,
logEvents,
makeHttpError,
});

module.exports = {
// Auth
registerUserUseCaseHandler,
loginUserUseCaseHandler,
logoutUseCaseHandler,
refreshTokenUseCaseHandler,
updateUserUseCaseHandler,
deleteUserUseCaseHandler,
forgotPasswordUseCaseHandler,
resetPasswordUseCaseHandler,
// Profile
findAllUsersUseCaseHandler,
findOneUserUseCaseHandler,
registerUserUseCaseHandler,
updateUserUseCaseHandler,
deleteUserUseCaseHandler,
blockUserUseCaseHandler,
unBlockUserUseCaseHandler,
forgotPasswordUseCaseHandler,
resetPasswordUseCaseHandler,
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
module.exports = {
registerUserUseCase: require('./user-handlers').registerUserUseCase,
loginUserUseCase: require('./user-handlers').loginUserUseCase,
refreshTokenUseCase: require('./user-handlers').refreshTokenUseCase,
logoutUseCase: require('./user-handlers').logoutUseCase,
forgotPasswordUseCase: require('./user-handlers').forgotPasswordUseCase,
resetPasswordUseCase: require('./user-handlers').resetPasswordUseCase,
};
Loading
Loading