Sure! Below is a detailed, modular code for an Order Management System built with Express.js. The application supports CRUD operations for orders, including order creation, viewing order details, updating, and deleting orders.
We'll structure the application into the following modules:
- server.js: The main entry point of the application.
- routes/orderRoutes.js: Defines the API endpoints for order operations.
- controllers/orderController.js: Contains the logic for handling requests.
- models/orderModel.js: Defines the Order data model.
We'll use an in-memory array to store orders for simplicity. In a production environment, you'd typically use a database.
Let's begin!
1. Install Dependencies
First, make sure you have Node.js installed. Initialize a new Node.js project and install the required dependencies:
npm init -y
npm install express body-parser
2. server.js
// server.js
const express = require('express');
const bodyParser = require('body-parser');
const orderRoutes = require('./routes/orderRoutes');
const app = express();
const PORT = process.env.PORT || 3000;
// Middleware to parse JSON requests
app.use(bodyParser.json());
// Use the order routes
app.use('/orders', orderRoutes);
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Explanation:
- Imports the necessary modules (
express, body-parser, and our order routes).
- Sets up the Express app and configures it to parse JSON request bodies.
- Uses the
/orders route for all order-related endpoints.
- Starts the server on the specified port.
3. routes/orderRoutes.js
// routes/orderRoutes.js
const express = require('express');
const router = express.Router();
const orderController = require('../controllers/orderController');
// Create a new order
router.post('/', orderController.createOrder);
// Get all orders
router.get('/', orderController.getAllOrders);
// Get a specific order by ID
router.get('/:id', orderController.getOrderById);
// Update an existing order
router.put('/:id', orderController.updateOrder);
// Delete an order
router.delete('/:id', orderController.deleteOrder);
module.exports = router;
Explanation:
- Creates a router for order-related routes.
- Defines routes for creating, retrieving, updating, and deleting orders.
- Each route maps to a corresponding controller function.
- Exports the router to be used in
server.js.
4. controllers/orderController.js
// controllers/orderController.js
const Order = require('../models/orderModel');
// In-memory orders array
let orders = [];
let currentId = 1;
// Create a new order
exports.createOrder = (req, res) => {
const { customerName, items } = req.body;
if (!customerName || !items) {
return res.status(400).json({ message: 'Customer name and items are required.' });
}
const newOrder = new Order(currentId++, customerName, items);
orders.push(newOrder);
res.status(201).json(newOrder);
};
// Get all orders
exports.getAllOrders = (req, res) => {
res.json(orders);
};
// Get a specific order by ID
exports.getOrderById = (req, res) => {
const id = parseInt(req.params.id);
const order = orders.find((o) => o.id === id);
if (!order) {
return res.status(404).json({ message: 'Order not found.' });
}
res.json(order);
};
// Update an existing order
exports.updateOrder = (req, res) => {
const id = parseInt(req.params.id);
const { customerName, items } = req.body;
const orderIndex = orders.findIndex((o) => o.id === id);
if (orderIndex === -1) {
return res.status(404).json({ message: 'Order not found.' });
}
if (!customerName || !items) {
return res.status(400).json({ message: 'Customer name and items are required.' });
}
orders[orderIndex] = { id, customerName, items };
res.json(orders[orderIndex]);
};
// Delete an order
exports.deleteOrder = (req, res) => {
const id = parseInt(req.params.id);
const orderIndex = orders.findIndex((o) => o.id === id);
if (orderIndex === -1) {
return res.status(404).json({ message: 'Order not found.' });
}
orders.splice(orderIndex, 1);
res.json({ message: 'Order deleted successfully.' });
};
Explanation:
- Imports the
Order model.
- Uses an in-memory
orders array to store orders and a currentId to assign unique IDs.
- createOrder: Validates input and creates a new order.
- getAllOrders: Returns all orders.
- getOrderById: Retrieves a specific order by ID.
- updateOrder: Updates an existing order after validating the input and ensuring the order exists.
- deleteOrder: Deletes an order if it exists.
5. models/orderModel.js
// models/orderModel.js
class Order {
constructor(id, customerName, items) {
this.id = id;
this.customerName = customerName;
this.items = items; // Array of items
this.orderDate = new Date();
}
}
module.exports = Order;
Explanation:
- Defines an
Order class to model order data.
- Includes properties like
id, customerName, items, and orderDate.
- Exports the
Order class for use in the controller.
6. Testing the API
You can use a tool like Postman or curl to test the API endpoints.
Create a New Order
- Endpoint:
POST /orders
- Request Body:
{
"customerName": "John Doe",
"items": [
{
"product": "Widget",
"quantity": 3
},
{
"product": "Gadget",
"quantity": 2
}
]
}
- Response: Returns the created order with a unique ID.
Get All Orders
- Endpoint:
GET /orders
- Response: Returns an array of all orders.
Get Order by ID
- Endpoint:
GET /orders/:id
- Example:
GET /orders/1
- Response: Returns the order with the specified ID.
Update an Order
- Endpoint:
PUT /orders/:id
- Request Body:
{
"customerName": "Jane Smith",
"items": [
{
"product": "Thingamajig",
"quantity": 5
}
]
}
- Response: Returns the updated order.
Delete an Order
- Endpoint:
DELETE /orders/:id
- Example:
DELETE /orders/1
- Response:
{ "message": "Order deleted successfully." }
7. Run the Application
Start the server by running:
node server.js
You should see:
Server is running on port 3000
Conclusion
This modular Express.js application provides a simple Order Management System with full CRUD functionality. The code is organized into separate modules for easy maintenance and scalability:
- server.js: Sets up the server and middleware.
- routes/orderRoutes.js: Defines the API endpoints.
- controllers/orderController.js: Contains the business logic.
- models/orderModel.js: Defines the Order data structure.
For a production-ready application, consider integrating a database (e.g., MongoDB, PostgreSQL) and adding features like authentication, error handling middleware, and input validation libraries (e.g., Joi).
Feel free to ask if you need further assistance or explanations!