- Lab
- Core Tech

Guided: Build an Inventory Management Microservice in Node.js
This lab presents a practical introduction to microservice development with Express, focusing on the fundamentals of CRUD operations. You will learn to create, read, update, and delete inventory items within a pre-built User Interface (UI), all while managing data within server memory. By the end, you'll have a fully operational microservice and a clear grasp of how to apply these techniques in real-world applications.

Path Info
Table of Contents
-
Challenge
Initialize In-Memory Storage
Introduction to Initializing In-Memory Storage in Inventory Management
In the initial step of developing your Inventory Management Microservice using Node.js and Express, the primary focus will be on constructing the core component for data storage - the in-memory storage mechanism. This setup is essential for facilitating the efficient storage and retrieval of inventory data. Through implementing in-memory data storage, you'll lay the foundation for operations such as create, read, update, and delete (CRUD) pertaining to inventory items, directly impacting the microservice's functionality.
Project Structure Overview:
-
server.js
: Acts as the heart of your microservice, encapsulating the logic for routing, middleware, and in-memory data storage definition. Here, you'll implement the CRUD operations that underpin the functionality of your inventory system. -
public/
: Houses static files that serve as the frontend of your microservice. This includes:-
index.html
: A pre-configured user interface file for interacting with the microservice's backend functionalities. This HTML file provides a straightforward way for users to add, update, view, and delete inventory items through the web browser. -
app.js
: A JavaScript file responsible for handling the frontend logic that interacts with your Express backend. It defines the behavior for submitting forms, handling responses, and updating the UI in response to user actions and server responses.
-
Implementing In-Memory Storage:
A simple JavaScript array, named
inventoryItems
, will be used to store your inventory items. This approach to in-memory data storage is chosen for its simplicity and effectiveness, providing quick access and manipulation of data, which is ideal for the scope of this lab.Method Design:
-
Initialize Storage Array: Declare
inventoryItems
as an empty array withinserver.js
. This will act as the dynamic repository for inventory items during the microservice's operation. -
Structure of Inventory Items: Inventory items will be stored within
inventoryItems
as JavaScript objects, each object representing an item with properties such asid
,name
,quantity
, anddescription
for comprehensive inventory management. -
CRUD Operations Implementation: You will leverage the
inventoryItems
array to perform CRUD operations. These essential functionalities form the backbone of the microservice, allowing for the addition, retrieval, modification, and deletion of inventory items. -
Validation and Error Handling: Integrate simple validation for CRUD operations to maintain data integrity, for instance, by ensuring that both
name
andquantity
are provided for item additions or updates. Error handling mechanisms should also be implemented to manage and respond to erroneous operations or invalid data inputs gracefully.
With the
inventoryItems
array now ready, you've laid the groundwork for your Inventory Management Microservice. By runningnode server.js
and heading to {{localhost:3000}}, you can now view your Inventory Management UI.Next, you'll focus on implementing the Create operation. This involves setting up a POST route to add new items to your inventory, enabling dynamic updates to your item list. Once added, you can immediately see the changes reflected in your Inventory Management UI.
-
-
Challenge
Adding the Create Operation
Introduction to Adding New Items in Inventory Management
This step focuses on implementing the functionality to add new items to your inventory through a POST request. By setting up this feature, you enable the dynamic expansion of your inventory based on user inputs.
Method Design:
-
Route Setup: A POST route
app.post('/api/inventory', (req, res) => {...})
is prepared in yourserver.js
file. This route targets capturing and storing new inventory items from the request payload. -
Data Extraction and Validation: Extract
name
,quantity
, anddescription
from the request body. Check if name and quantity are present; if missing, return a 400 status code with an error message. -
Item Creation and Storage: Upon validation, construct an object for the new inventory item with
id
,name
,quantity
, anddescription
. Use the array's length to assign a uniqueid
to each item. Add this object by pushing to theinventoryItems
array, effectively recording the new addition. -
Client Response: End the process by responding to the request with the newly added item, signifying successful addition through a 201 status code.
With the successful addition of new items to your inventory through the POST route, you've taken a significant step in building the functionality of your Inventory Management Microservice. If you re-run
node server.js
and head to {{localhost:3000}} you can test this addition functionality through the UI successfully.Next, you'll focus on enabling the ability to read and display these items. This involves setting up GET routes to fetch all items and specific items by ID from your inventory, providing access to the current inventory list. Move to the next step to enhance your microservice with these retrieval capabilities.
-
-
Challenge
Adding the Get Operation
Introduction to Implementing Retrieval Operations in Inventory Management
With the functionality to add items now in place, your next objective is to develop the retrieval features of your Inventory Management Microservice. This involves detailed logic for two critical GET routes: one for fetching the entire inventory and another for retrieving details of a specific item by its ID. These capabilities are essential for any robust inventory system, allowing for both broad oversight and individual item inspection.
Method Design:
-
Retrieving All Inventory Items: Enhance the route
app.get('/api/inventory', (req, res) => {...})
to return all current inventory items. Implement logic within this route to fetch and return the entireinventoryItems
array. Ensure to respond with a 200 status code, indicating a successful retrieval of the inventory list. -
Fetching a Specific Item by ID: The route
app.get('/api/inventory/:id', (req, res) => {...})
requires you to extract theid
parameter fromreq.params
and use it to find the corresponding item in theinventoryItems
array. This is done using thefind
method, checking each item'sid
against the providedid
. If an item is found, return it with a status code of 200, signaling a successful fetch. For cases where no matching item is found, send a 404 status code with an "Item not found." message. This distinction is critical for handling client requests accurately and providing clear feedback. -
Response Considerations: The implementation of both routes should consider the format and completeness of the response. For the route returning all items, ensure the entire
inventoryItems
array is sent back as JSON. When returning a specific item, the response should include the item's details in JSON format if found. Proper handling of these responses ensures a seamless interaction with the inventory system for end-users, facilitating both comprehensive and targeted queries of inventory data. Having implemented retrieval operations, your Inventory Management Microservice now supports viewing the entire inventory or specific items by ID. This functionality enriches the microservice, offering detailed insights into inventory data. If you re-runnode server.js
and head to {{localhost:3000}} you can test this retrieval functionality through the UI successfully.
Next, you will introduce the update operation. This step involves creating logic within a PUT route to modify existing inventory items, ensuring your microservice can adapt to changes in inventory details efficiently. Proceed to the next step to further refine the versatility of your inventory system.
-
-
Challenge
Adding the Update Operation
Introduction to Enhancing Update Capabilities in Inventory Management
With foundational elements in place for adding and retrieving inventory items, the next step is to incorporate the ability to update existing items in your Inventory Management Microservice. This step is essential for maintaining accurate and current inventory information, allowing for modifications to item details such as name, quantity, and description. You will implement logic within a PUT route to enable the modification of existing inventory items based on their ID.
Method Design:
-
Identifying the Item to Update: Utilize the PUT route
app.put('/api/inventory/:id', (req, res) => {...})
to extract the item's ID from the URL parameters. This ID is essential for locating the specific item within theinventoryItems
array that requires updates. -
Validating the Item's Existence: Use the extracted ID to search for the item within
inventoryItems
. If the item exists, proceed with updating its details; otherwise, return a 404 Not Found response to indicate the item's absence. -
Extracting and Applying Updates: Derive the new item details from the request body, including
name
,quantity
, anddescription
. Update the identified item's details within theinventoryItems
array to reflect these changes. -
Confirming the Update: Respond with the updated item object and a 200 status code to signify the successful application of updates. This feedback confirms to the client that the item has been updated and provides the updated item's details. Having successfully integrated the update operation, your Inventory Management Microservice is now more versatile, accommodating changes to inventory item details efficiently. This enhancement further solidifies the microservice's utility in managing a dynamic inventory. If you re-run
node server.js
and head to {{localhost:3000}}, you can test this update functionality through the UI successfully.
Next, you will focus on adding the delete operation. This final step allows for the removal of items from the inventory, completing the full spectrum of CRUD (Create, Read, Update, Delete) operations within your microservice. Proceed to implement this capability and finalize the functionality of your inventory system.
-
-
Challenge
Adding the Delete Operation
Introduction to Implementing Delete Operations in Inventory Management
After mastering the creation, retrieval, and update functionalities within your Inventory Management Microservice, it's time to add the ability to delete inventory items. This essential feature enables efficient removal of items from your inventory, keeping the data current and accurate. The implementation of a DELETE route facilitates handling deletion requests by identifying items with their unique ID.
Method Design:
-
Extracting the Item ID: Initiate the process in the DELETE route
app.delete('/api/inventory/:id', (req, res) => {...})
by extracting the target item's ID from the URL parameters. The ID is essential for pinpointing the item slated for deletion within theinventoryItems
array. -
Locating and Removing the Item: Use the extracted ID to locate the item within
inventoryItems
usingfindIndex
, as shown:const itemIndex = inventoryItems.findIndex(item => item.id === parseInt(id, 10))
. This method searches for the item's index based on its ID. If an item is found (i.e.,itemIndex
is not-1
), proceed to remove it from the array withinventoryItems.splice(itemIndex, 1)
. If no item matches the ID (itemIndex
is-1
), issue a 404 Not Found response, indicating the item doesn't exist in the inventory. -
Confirming Item Deletion: Upon successful item deletion, confirm the action by sending back a 200 status code alongside a message that clearly states the item has been removed. This feedback reassures the client of the successful operation and the item's removal from the inventory. With the CRUD operations fully implemented, your Inventory Management Microservice is now equipped to handle a wide range of data management tasks effectively. If you re-run
node server.js
and head to {{localhost:3000}} you can test the full spectrum of CRUD functionality through the UI successfully. Consider exploring additional features such as user authentication, advanced filtering and sorting of inventory items, or integrating with external APIs for enhanced functionality. Continue refining your skills and expanding your microservice to cater to more complex requirements.
-
-
Challenge
Implement Input Validation Middleware
Introduction to Input Validation Middleware in Inventory Management
With CRUD operations in place, ensuring data integrity and security becomes paramount. The next advancement introduces a precise approach to validating input data through the
validateInventoryItem
middleware. This function is critical for examining thename
andquantity
fields of inventory items during creation and update requests. By enforcing stringent checks, it helps prevent the entry of invalid data, thereby enhancing the microservice's reliability and security.Method Design:
-
Detailed Validation Logic: Focus on enhancing the
validateInventoryItem
middleware to perform detailed checks on the request body'sname
andquantity
fields. Your logic should verify the presence ofname
and ensurequantity
is not undefined, a number, and non-negative. This step involves careful consideration of the conditions that constitute valid input, aiming to capture common input errors such as missing data or incorrect value types. -
Error Handling and Progression: If the validation fails due to any of these conditions, the middleware should immediately halt the process, responding to the client with a 400 status code and a descriptive error message. This prompt feedback helps in quickly identifying and correcting input issues. Conversely, if the input passes all checks, proceed by invoking
next()
, allowing the request to move to the subsequent middleware or route handler. -
Middleware Application: Ensure that this refined validation logic is seamlessly integrated into your POST and PUT routes. Applying the
validateInventoryItem
middleware to these routes guarantees that all attempts to add or update inventory items undergo comprehensive validation, reinforcing the integrity of the data processed by your microservice.
Important Note:
- After implementing the
validateInventoryItem
function, make sure to update theapp.post()
andapp.put()
routes to include this middleware. This ensures all attempts to add or update inventory items are thoroughly validated, reinforcing data integrity. Update them as follows: app.post('/api/inventory', validateInventoryItem, (req, res) => {...});
app.put('/api/inventory/:id', validateInventoryItem, (req, res) => {...});
With the successful integration of input validation middleware, your microservice now has an added layer of security and data integrity, ensuring that all incoming data for creating and updating inventory items meets the required standards.
Next, you will turn your attention to refining the microservice's robustness through the implementation of error-handling middleware. In the upcoming step, you'll focus on global error management to ensure your microservice gracefully handles unexpected situations. This includes providing informative feedback to users and maintaining the stability of your service.
-
-
Challenge
Implement Error Middleware
Introduction to Implementing Dynamic Error Handling in Inventory Management
As you refine your Inventory Management Microservice, it's crucial to enhance its ability to handle errors intelligently. This next step focuses on developing an advanced error handling middleware. This middleware will be designed to provide clear and informative feedback to clients by dynamically responding to various errors based on their nature and context.
Method Design:
-
Crafting a Responsive Error Handling Middleware: Your task is to expand the error handling capabilities of your middleware. Focus on using the error object to tailor the HTTP response, working with two key aspects:
- Determine the HTTP Status Code:
- Create a variable named
statusCode
. - Check if the error object (
err
) has a specific status code (err.status
). - If yes, use this status code for the response.
- Otherwise, default to
500
for an Internal Server Error.
- Create a variable named
- Extracting the Error Message:
- Define a variable named
errorMessage
to capture the message from the error object. - If the error object doesn't provide a message, default to
'Something went wrong!'
.
- Define a variable named
- Determine the HTTP Status Code:
-
Sending the Custom Error Response:
- With the
statusCode
anderrorMessage
prepared, use them to construct and send a response to the client. - This response should include both the status code and the tailored error message, ensuring the client receives a clear understanding of the error encountered. Implementing this error handling improves your microservice's reliability and client communication by providing detailed feedback on errors. This step is a foundation for future enhancements, like advanced error categorization or integrating error tracking for better insights.
- With the
-
-
Challenge
Conclusion
Congratulations on successfully completing the Inventory Management Microservice lab! Throughout this lab you've taken significant strides in developing a fully functional inventory management system using Node.js and Express, integrating CRUD operations, input validation, and enhanced error handling.
Summary of Your Achievements:
- Express Framework: You've built a robust microservice using Express, understanding the framework's capabilities in routing, middleware, and handling HTTP requests.
- CRUD Operations: You implemented Create, Read, Update, and Delete (CRUD) operations, forming the backbone of your inventory management system.
- Input Validation: By adding middleware for input validation, you've ensured that data integrity is maintained, preventing invalid data from being processed.
- Error Handling: You've enhanced the microservice's resilience by implementing comprehensive error handling, improving the clarity and usefulness of error messages sent to clients.
Testing Your Microservice: To interact with your microservice, start the server with
node server.js
and head to {{localhost:3000}}.Interacting with Your Microservice: Here are examples of how you can perform inventory operations:
-
Adding a New Item:
POST /api/inventory
with a JSON body containingname
,quantity
, anddescription
. -
Fetching Inventory Items:
GET /api/inventory
to retrieve a list of all items. -
Updating an Item:
PUT /api/inventory/:id
with a JSON body to update the details of an item by its ID. -
Deleting an Item:
DELETE /api/inventory/:id
to remove an item from the inventory by its ID.
Further Development:
Your inventory management microservice lays a solid foundation, but there's always room for improvement and expansion. Consider adding features like authentication, advanced search and filtering capabilities, or integration with external APIs for additional functionalities.
Further Learning Resources:
To continue enhancing your skills in Node.js, Express, and web development, Pluralsight offers extensive courses that cover these topics and more. Dive deeper into backend development, database integration, and modern JavaScript frameworks to build more complex and scalable applications.
What's a lab?
Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.
Provided environment for hands-on practice
We will provide the credentials and environment necessary for you to practice right within your browser.
Guided walkthrough
Follow along with the author’s guided walkthrough and build something new in your provided environment!
Did you know?
On average, you retain 75% more of your learning if you get time for practice.