diff --git a/README.md b/README.md
index be3c061..616227b 100644
--- a/README.md
+++ b/README.md
@@ -1,48 +1,52 @@
-# Clean code Architecture pattern applied to Digital Market Place API.
+# Clean code Architecture pattern applied to Node.js REST API Example
+
-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
@@ -50,6 +54,7 @@ routes/ # Express route definitions
public/ # Static files and HTML views
```
+
## Features
- User registration and authentication (JWT)
@@ -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:
@@ -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
@@ -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
@@ -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).
diff --git a/application-business-rules/use-cases/blogs/blog-handlers.js b/application-business-rules/use-cases/blogs/blog-handlers.js
index 07c6e4c..d53c425 100644
--- a/application-business-rules/use-cases/blogs/blog-handlers.js
+++ b/application-business-rules/use-cases/blogs/blog-handlers.js
@@ -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 });
@@ -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;
@@ -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 });
diff --git a/application-business-rules/use-cases/products/product-handlers.js b/application-business-rules/use-cases/products/product-handlers.js
index af3fd6e..514e439 100644
--- a/application-business-rules/use-cases/products/product-handlers.js
+++ b/application-business-rules/use-cases/products/product-handlers.js
@@ -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);
diff --git a/application-business-rules/use-cases/user/index.js b/application-business-rules/use-cases/user/index.js
index 8b11900..fbac97d 100644
--- a/application-business-rules/use-cases/user/index.js
+++ b/application-business-rules/use-cases/user/index.js
@@ -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');
@@ -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,
};
diff --git a/application-business-rules/use-cases/user/user-auth-usecases.js b/application-business-rules/use-cases/user/user-auth-usecases.js
new file mode 100644
index 0000000..f3714fc
--- /dev/null
+++ b/application-business-rules/use-cases/user/user-auth-usecases.js
@@ -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,
+};
diff --git a/application-business-rules/use-cases/user/user-handlers.js b/application-business-rules/use-cases/user/user-handlers.js
index 0ad9c03..f3e5288 100644
--- a/application-business-rules/use-cases/user/user-handlers.js
+++ b/application-business-rules/use-cases/user/user-handlers.js
@@ -229,7 +229,7 @@ module.exports = {
* @throws {RequiredParameterError} If the ID is not provided.
* @throws {new Error} If the user is not found.
*/
- deleteUserUseCase: ({ dbUserHandler, validateId, RequiredParameterError, logEvents }) => {
+ deleteUserUseCase: ({ dbUserHandler, validateId, logEvents }) => {
return async function deleteUserUseCaseHandler({ userId }) {
const newId = validateId(userId);
try {
@@ -268,7 +268,7 @@ module.exports = {
* @throws {new Error} If the user is not found.
* @throws {Error} If there is an error refreshing the token.
*/
- refreshTokenUseCase: ({ dbUserHandler, RequiredParameterError, logEvents }) => {
+ refreshTokenUseCase: ({ dbUserHandler, logEvents }) => {
return async function refreshTokenUseCaseHandler({ refreshToken, jwt }) {
try {
console.log(`refreshToken: ${refreshToken}`);
@@ -316,7 +316,7 @@ module.exports = {
* @param {string} refreshToken - The refresh token to be used for logout.
* @return {Object} An object containing the access token and refresh token.
*/
- logoutUseCase: ({ RequiredParameterError, logEvents }) => {
+ logoutUseCase: ({ logEvents }) => {
return async function logoutUseCaseHandler({ refreshToken }) {
try {
if (!refreshToken) {
@@ -334,7 +334,7 @@ module.exports = {
},
//block user
- blockUserUseCase: ({ dbUserHandler, validateId, RequiredParameterError, logEvents }) => {
+ blockUserUseCase: ({ dbUserHandler, validateId, logEvents }) => {
return async function blockUserUseCaseHandler({ userId }) {
const newId = validateId(userId);
@@ -363,7 +363,7 @@ module.exports = {
},
//un-block user
- unBlockUserUseCase: ({ dbUserHandler, validateId, RequiredParameterError, logEvents }) => {
+ unBlockUserUseCase: ({ dbUserHandler, validateId, logEvents }) => {
return async function unBlockUserUseCaseHandler({ userId }) {
const newId = validateId(userId);
diff --git a/application-business-rules/use-cases/user/user-profile-usecases.js b/application-business-rules/use-cases/user/user-profile-usecases.js
new file mode 100644
index 0000000..7eff18a
--- /dev/null
+++ b/application-business-rules/use-cases/user/user-profile-usecases.js
@@ -0,0 +1,8 @@
+module.exports = {
+ findAllUsersUseCase: require('./user-handlers').findAllUsersUseCase,
+ findOneUserUseCase: require('./user-handlers').findOneUserUseCase,
+ updateUserUseCase: require('./user-handlers').updateUserUseCase,
+ deleteUserUseCase: require('./user-handlers').deleteUserUseCase,
+ blockUserUseCase: require('./user-handlers').blockUserUseCase,
+ unBlockUserUseCase: require('./user-handlers').unBlockUserUseCase,
+};
diff --git a/enterprise-business-rules/entities/blog-model.js b/enterprise-business-rules/entities/blog-model.js
index a052243..a930d84 100644
--- a/enterprise-business-rules/entities/blog-model.js
+++ b/enterprise-business-rules/entities/blog-model.js
@@ -1,5 +1,3 @@
-const blogValidation = require('../validate-models/blog-validation');
-
module.exports = {
makeBlogModel: ({ blogValidation, logEvents }) => {
return async function makeBlog({ blogData }) {
diff --git a/enterprise-business-rules/validate-models/blog-validation.js b/enterprise-business-rules/validate-models/blog-validation.js
index fad1cbe..befcdf6 100644
--- a/enterprise-business-rules/validate-models/blog-validation.js
+++ b/enterprise-business-rules/validate-models/blog-validation.js
@@ -1,6 +1,6 @@
const productValidation = require('./product-validation-fcts')();
-const { validateDescription, validateTitle, validateObjectId } = productValidation;
+const { validateDescription, validateTitle } = productValidation;
//validate cover image for only more optimized types
const validateCoverImage = ({ cover_image, InvalidPropertyError }) => {
diff --git a/enterprise-business-rules/validate-models/user-validation-functions.js b/enterprise-business-rules/validate-models/user-validation-functions.js
index c6bee5d..c8404e6 100644
--- a/enterprise-business-rules/validate-models/user-validation-functions.js
+++ b/enterprise-business-rules/validate-models/user-validation-functions.js
@@ -83,18 +83,23 @@ async function validatePassword(password) {
}
// Validate role of the user, either user or admin
-const validRoles = new Set(['user', 'admin']);
function validateRole(roles) {
- // make role always an array
-
- if (!validRoles.has(roles)) {
+ const validRoles = new Set(['user', 'admin']);
+ if (Array.isArray(roles)) {
+ for (const role of roles) {
+ if (!validRoles.has(role)) {
+ throw new InvalidPropertyError(`A user's role must be either 'user' or 'admin'.`);
+ }
+ }
+ return roles;
+ } else if (typeof roles === 'string') {
+ if (!validRoles.has(roles)) {
+ throw new InvalidPropertyError(`A user's role must be either 'user' or 'admin'.`);
+ }
+ return [roles];
+ } else {
throw new InvalidPropertyError(`A user's role must be either 'user' or 'admin'.`);
}
-
- if (!Array.isArray(roles)) {
- roles = [roles];
- }
- return roles;
}
//validate mongodb id
diff --git a/index.js b/index.js
index d42fe6e..e33af76 100644
--- a/index.js
+++ b/index.js
@@ -7,10 +7,48 @@ const { dbconnection } = require('./interface-adapters/database-access/db-connec
const errorHandler = require('./interface-adapters/middlewares/loggers/errorHandler.js');
const { logger } = require('./interface-adapters/middlewares/loggers/logger.js');
const createIndexFn = require('./interface-adapters/database-access/db-indexes.js');
+const swaggerUi = require('swagger-ui-express');
+const swaggerJSDoc = require('swagger-jsdoc');
+
+const PORT = process.env.PORT || 5000;
+
+const swaggerDefinition = {
+ openapi: '3.0.0',
+ info: {
+ title: 'Clean Architecture REST API',
+ version: '1.0.0',
+ description: 'API documentation for the Clean Architecture Node.js REST API',
+ contact: {
+ name: 'Avom Brice',
+ email: 'bricefrkc@gmail.com',
+ },
+ },
+ servers: [
+ {
+ url: `http://localhost:${PORT}`,
+ description: 'Local server API documentation',
+ },
+ ],
+ components: {
+ securitySchemes: {
+ bearerAuth: {
+ type: 'http',
+ scheme: 'bearer',
+ bearerFormat: 'JWT',
+ },
+ },
+ },
+ security: [{ bearerAuth: [] }],
+};
+
+const options = {
+ swaggerDefinition,
+ apis: ['./routes/*.js'],
+};
+const swaggerSpec = swaggerJSDoc(options);
const app = express();
-const PORT = process.env.PORT || 5000;
var cookieParser = require('cookie-parser');
const corsOptions = require('./interface-adapters/middlewares/config/corsOptions.Js');
@@ -26,14 +64,19 @@ app.use(express.json());
app.use(cookieParser());
app.use(express.urlencoded({ extended: false }));
+// Register Swagger UI BEFORE any static or catch-all routes
+app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));
+
// Use the new single entry point for all routes
const mainRouter = require('./routes');
-app.use('/', mainRouter);
-app.use('/', (_, res) => {
+// Only serve index.html for the root path
+app.get('/', (_, res) => {
res.sendFile(path.join(__dirname, 'public', 'views', 'index.html'));
});
+app.use('/', mainRouter);
+
//for no specified endpoint that is not found. this must after all the middlewares
app.all('*', (req, res) => {
res.status(404);
diff --git a/interface-adapters/controllers/blogs/blog-controller.js b/interface-adapters/controllers/blogs/blog-controller.js
index ccc6bd2..ac82739 100644
--- a/interface-adapters/controllers/blogs/blog-controller.js
+++ b/interface-adapters/controllers/blogs/blog-controller.js
@@ -4,7 +4,7 @@ const defaultHeaders = {
'x-content-type-options': 'nosniff',
};
-const createBlogController = ({ createBlogUseCaseHandler, errorHandlers, logEvents }) =>
+const createBlogController = ({ createBlogUseCaseHandler, logEvents }) =>
async function createBlogControllerHandler(httpRequest) {
const { body } = httpRequest;
if (!body || Object.keys(body).length === 0) {
@@ -32,13 +32,14 @@ const createBlogController = ({ createBlogUseCaseHandler, errorHandlers, logEven
};
const findAllBlogsController = ({ findAllBlogsUseCaseHandler, logEvents }) =>
- async function findAllBlogsControllerHandler(httpRequest) {
+ async function findAllBlogsControllerHandler() {
try {
const blogs = await findAllBlogsUseCaseHandler();
+ const safeBlogs = Array.isArray(blogs) ? blogs : blogs ? [blogs] : [];
return {
headers: defaultHeaders,
statusCode: 200,
- data: { blogs },
+ data: { blogs: safeBlogs },
};
} catch (e) {
logEvents && logEvents(e.message, 'blogController.log');
diff --git a/interface-adapters/controllers/products/index.js b/interface-adapters/controllers/products/index.js
index ba93270..97cf335 100644
--- a/interface-adapters/controllers/products/index.js
+++ b/interface-adapters/controllers/products/index.js
@@ -1,28 +1,26 @@
-const { dbProductHandler } = require('../../database-access');
-
const {
createProductController,
- deleteProductController,
- updateProductController,
findAllProductController,
findOneProductController,
+ updateProductController,
+ deleteProductController,
rateProductController,
// findBestUserRaterController
-} = require('./product-controller')();
+} = require('./product-controller');
const {
createProductUseCaseHandler,
- updateProductUseCaseHandler,
- deleteProductUseCaseHandler,
findAllProductUseCaseHandler,
findOneProductUseCaseHandler,
+ updateProductUseCaseHandler,
+ deleteProductUseCaseHandler,
rateProductUseCaseHandler,
- // findBestUserRaterUseCaseHandler
} = require('../../../application-business-rules/use-cases/products');
const { makeHttpError } = require('../../validators-errors/http-error');
const errorHandlers = require('../../validators-errors/errors');
const { logEvents } = require('../../middlewares/loggers/logger');
+const { dbProductHandler } = require('../../database-access');
const createProductControllerHandler = createProductController({
createProductUseCaseHandler,
@@ -68,11 +66,9 @@ const rateProductControllerHandler = rateProductController({
module.exports = {
createProductControllerHandler,
-
- updateProductControllerHandler,
- deleteProductControllerHandler,
findAllProductControllerHandler,
findOneProductControllerHandler,
+ updateProductControllerHandler,
+ deleteProductControllerHandler,
rateProductControllerHandler,
- // findBestUserRaterControllerHandler
};
diff --git a/interface-adapters/controllers/products/product-controller.js b/interface-adapters/controllers/products/product-controller.js
index e9cde52..2771a8a 100644
--- a/interface-adapters/controllers/products/product-controller.js
+++ b/interface-adapters/controllers/products/product-controller.js
@@ -136,7 +136,7 @@ const findOneProductController = ({
'Content-Type': 'application/json',
'x-content-type-options': 'nosniff',
},
- statusCode: 201,
+ statusCode: 200,
data: { product },
};
} catch (e) {
@@ -163,14 +163,24 @@ const findAllProductController = ({ dbProductHandler, findAllProductUseCaseHandl
filterOptions,
})
.then((products) => {
- // console.log("products from findAllProductController: ", products);
+ // Always return a flat array if possible
+ let safeProducts = [];
+ if (Array.isArray(products)) {
+ if (typeof products.flat === 'function') {
+ safeProducts = products.flat();
+ } else {
+ safeProducts = products;
+ }
+ } else if (products) {
+ safeProducts = [products];
+ }
return {
headers: {
'Content-Type': 'application/json',
'x-content-type-options': 'nosniff',
},
- statusCode: 201,
- data: { products },
+ statusCode: 200,
+ data: { products: safeProducts },
};
})
.catch((e) => {
@@ -383,12 +393,11 @@ const rateProductController = ({
});
};
-module.exports = () =>
- Object.freeze({
- createProductController,
- findOneProductController,
- findAllProductController,
- deleteProductController,
- updateProductController,
- rateProductController,
- });
+module.exports = {
+ createProductController,
+ findOneProductController,
+ findAllProductController,
+ deleteProductController,
+ updateProductController,
+ rateProductController,
+};
diff --git a/interface-adapters/controllers/users/create-user.js b/interface-adapters/controllers/users/create-user.js
deleted file mode 100644
index f5cc000..0000000
--- a/interface-adapters/controllers/users/create-user.js
+++ /dev/null
@@ -1,407 +0,0 @@
-// const { UniqueConstraintError, InvalidPropertyError, RequiredParameterError } = require("../../config/validators-errors/errors");
-// const { makeHttpError } = require("../../config/validators-errors/http-error");
-// const { logEvents } = require("../../middlewares/loggers/logger");
-
-// module.exports = {
-// /**
-// * Registers a new user using the provided user case handler.
-// *
-// * @param {Object} options - The options object.
-// * @param {Function} options.registerUserUserCaseHandler - The user case handler for registering a new user.
-// * @param {Object} httpRequest - The HTTP request object.
-// * @param {Object} httpRequest.body - The request body containing the user information.
-// * @return {Promise