Structuring Business Logic
Introduction: Why Organize Business Logic?
Welcome back! In the last few lessons, you learned how to validate incoming data, centralize error responses, and log API requests. These are all important steps for building a reliable API. Now, let’s talk about another key part of making your code easy to manage: organizing your business logic.
Business logic is the part of your code that handles the main rules and operations of your application. For example, deciding how to create a new user, update user information, or delete a user. If you mix this logic directly into your API routes, your code can quickly become messy and hard to update.
By keeping business logic in its own place, you make your code easier to read, test, and reuse. This lesson will show you how to do that using a simple and practical approach.
What Is a Service and Why Use One?
A service is a file or module where you put all the main logic for working with your data. Instead of writing the logic for creating, updating, or deleting users directly in your API routes, you put it in a service. Then, your routes can just call these service functions.
Why is this helpful?
- It keeps your code organized and easy to read.
- You can reuse the same logic in different parts of your app.
- If you need to change how something works (like how users are created), you only have to update it in one place. This approach is especially helpful as your application grows. For example, if you later add validation, database calls, or caching to user creation, those changes would live entirely in the service—without touching your API route. This separation allows you to scale features without bloating route handlers.
Think of a service as a toolbox: instead of building a new tool every time you need to do something, you keep your tools in one place and use them whenever you need. This pattern also prepares your app for future upgrades, like switching from a mock database to a real one (e.g., PostgreSQL or MongoDB). You won’t need to rewrite all your routes—just adjust the service functions.
Building a User Service: Practical Example
Let’s build a user service step by step. We’ll create a file called userService.ts and add functions for all the main user operations.
Here’s the complete code for our user service:
Let’s break down what each function does:
getAllUsers: Returns the full list of users.getUserById: Finds and returns a user with a specificid. If no user is found, it returnsundefined.createUser: Takes user data (without anid), creates a new user with a uniqueid, adds it to the list, and returns the new user.updateUser: Finds a user byidand updates their information. If the user doesn’t exist, it returnsnull.deleteUser: Removes a user byidfrom the list. Returnstrueif successful, orfalseif the user wasn’t found.
Example Usage:
By putting all these functions in one file, you can now use them anywhere in your app, making your code much cleaner and easier to manage.
