DEV Community

Cover image for Tracking Order Status in Node.js: A Deep Dive
Muhammad Ranju
Muhammad Ranju

Posted on

Tracking Order Status in Node.js: A Deep Dive

**_In the dynamic world of e-commerce, tracking the status of an order is crucial for both businesses and customers. An effective tracking system ensures transparency and enhances the customer experience. In this article, we will explore a Node.js Express controller designed to handle order tracking. The controller fetches order details based on a tracking number and returns a status-specific response.

_**
**

Introduction to the Code

This Node.js codebase is a part of an Express application. It is designed to fetch an order's status from a database and return a corresponding message. The code uses asynchronous operations to handle database queries and HTTP responses efficiently.

*Key Components
*

  1. Imports and Constants
const asyncHandler = require("../../../../../utils/asyncHandler");
const Orders = require("../../../../../models/Orders.model");
const ApiResponse = require("../../../../../utils/ApiResponse");
const OrderStatusEnum = require("../../../../../Constants");
Enter fullscreen mode Exit fullscreen mode
  • asyncHandler: A utility to manage asynchronous functions and error handling.
  • Orders: The Mongoose model for accessing order data.
  • ApiResponse: A utility to create standardized API responses.
  • OrderStatusEnum: An object containing various order status constants.
  1. Controller Definition
const orderTrackingController = asyncHandler(async (req, res) => {
Enter fullscreen mode Exit fullscreen mode

The controller function, orderTrackingController, is wrapped in asyncHandler to handle asynchronous operations gracefully.

  1. Extracting Tracking Number
const { trackingNumber } = req.body;
Enter fullscreen mode Exit fullscreen mode

This line extracts the trackingNumber from the request body, which is needed to fetch the order details.

  1. Fetching Order
const order = await Orders.findOne({ trackingNumber: trackingNumber }).populate("shippingAddressId");
Enter fullscreen mode Exit fullscreen mode

This query fetches the order matching the provided tracking number and populates the shippingAddressId field with related data.

  1. Handling Order Not Found
if (!order) {
    return res.status(404).json(new ApiResponse(404, null, "Order not found"));
}
Enter fullscreen mode Exit fullscreen mode

If no order is found, the controller returns a 404 response with an appropriate message.

  1. Creating Response Function
const createResponse = (heading, body) => new ApiResponse(200, { heading, body });
Enter fullscreen mode Exit fullscreen mode
  1. Determining the Response Based on Order Status
switch (order.orderStatus) {
Enter fullscreen mode Exit fullscreen mode

The switch statement checks the orderStatus and constructs a response based on its value.

  • Order Status: Pending
  case OrderStatusEnum.PENDING:
      response = createResponse(
          "Processed and Ready to Ship",
          "Your package has been processed and will be with our delivery partner soon."
      );
      break;
Enter fullscreen mode Exit fullscreen mode
  • Order Status: Cancelled
  javascriptCopy codecase OrderStatusEnum.CANCELLED:
      response = createResponse(
          "Your Order has been cancelled",
          "Your order has been cancelled due to some reasons."
      );
      break;
Enter fullscreen mode Exit fullscreen mode
  • Order Status: Placed
  javascriptCopy codecase OrderStatusEnum.PLACED:
      response = createResponse(
          "Reached our Logistics Facility",
          "Your package has arrived at our logistics facility from where it will be sent to the last mile hub."
      );
      break;
Enter fullscreen mode Exit fullscreen mode
  • Order Status: Shipped
  javascriptCopy codecase OrderStatusEnum.SHIPPED:
      response = createResponse(
          "Shipped",
          `Your package is on the way to our last hub with tracking number ${order.trackingNumber} from where it will be delivered to you.`
      );
      break;
Enter fullscreen mode Exit fullscreen mode
  • Order Status: Out for Delivery
  javascriptCopy codecase OrderStatusEnum.OUT_FOR_DELIVERY:
      response = createResponse(
          "Out for Delivery",
          `Our delivery partner will attempt to deliver your package today to ${order.shippingAddressId?.city}.`
      );
      break;
Enter fullscreen mode Exit fullscreen mode
  • Order Status: Delivered
    javascriptCopy codecase OrderStatusEnum.DELIVERED:
    response = createResponse(
    "Delivered",
    Your package has been delivered to ${order.shippingAddressId?.city}.
    );
    break;

  • Default Case

  javascriptCopy codedefault:
      response = new ApiResponse(200, order, "Order status found successfully");
      break;
Enter fullscreen mode Exit fullscreen mode
  1. Sending Response to Client
        return res.status(200).json(response);
Enter fullscreen mode Exit fullscreen mode

This line sends the constructed response back to the client.

  1. Exporting the Controller
  module.exports = orderTrackingController;
Enter fullscreen mode Exit fullscreen mode

This Node.js Express controller is a robust solution for tracking order statuses. By using asynchronous operations and clear, status-specific messages, it enhances the user experience and ensures efficient order tracking. Whether an order is pending, shipped, or delivered, this controller provides precise updates, keeping customers informed throughout the delivery process. This approach not only improves transparency but also builds trust with customers, making it an essential component of any e-commerce application.

Top comments (0)