This API is built with Node.js and Fastify and is structured into separate layers:
- Routes layer – handles HTTP endpoints
- Products service – contains business logic
- Repository – manages data storage
The server can run in two modes:
- Solo mode – a single instance handles all requests.
- Distributed mode – multiple instances are spawned using Node.js Cluster, one per CPU core. Each instance listens on a separate port, and incoming requests are distributed using a round-robin load balancing algorithm.
- Clone the repository and install dependencies:
npm install- Create a .env file and set the PORT variable:
PORT=4000- Run the app in development mode:
npm run start:dev- Build and run the app in production mode:
npm run start:prod- Run the app in distributed mode (multi-instance):
npm run start:multiAll endpoints are prefixed with /api/products.
Retrieve all products.
Response:
200 OK– returns an array of products
Retrieve a product by ID.
Response:
200 OK– product found400 Bad Request– invalidproductId(not a UUID)404 Not Found– product not found
Create a new product.
Request Body:
{
"name": "string",
"description": "string",
"price": 100,
"category": "electronics",
"inStock": true
}Response:
201 Created– product found400 Bad Request– missing required fields or invalid data (e.g. price ≤ 0)
Update an existing product.
Request Body: Partial or full product object.
Response:
200 OK– product found400 Bad Request– invalid productId (not a UUID)404 Not Found– product not found
Delete a product.
Response:
204 No Content– product deleted400 Bad Request– invalid productId (not a UUID)404 Not Found– product not found
{
"id": "string (uuid)",
"name": "string",
"description": "string",
"price": "number (> 0)",
"category": ["electronics", "books" "clothing"],
"inStock": "boolean"
}