Streamlining Business Logic with DTOs and Zod Validation in Our Portal Backend

Introduction

We've been working on the backend for our FNSM Portal, focusing on solidifying the business logic layer. A key part of this has involved defining robust Data Transfer Objects (DTOs) and implementing validation using Zod. This ensures data consistency and reduces errors throughout the application.

Business Model and DTOs

Our approach begins with a well-defined business model that represents the core entities within the system. For example, consider a simplified User model:

interface User {
  id: string;
  name: string;
  email: string;
  age: number;
}

To transfer user data between different layers of the application (e.g., from the database to the API response), we use DTOs. DTOs are plain objects that contain only the data needed for a specific operation. This helps to decouple the data representation from the underlying model and provides flexibility for API evolution.

Here's an example of a UserResponseDTO:

interface UserResponseDTO {
  id: string;
  name: string;
  email: string;
}

Notice how the age field is excluded from the DTO. This might be done for privacy reasons or because the age is not relevant in certain contexts.

Zod Validation

To ensure data integrity, we've integrated Zod for data validation. Zod allows us to define schemas that specify the expected structure and type of data. This is especially useful when receiving data from external sources, such as API requests.

Here's how we can define a Zod schema for validating user data:

import { z } from 'zod';

const UserSchema = z.object({
  id: z.string().uuid(),
  name: z.string().min(2),
  email: z.string().email(),
  age: z.number().min(0).max(120),
});

type User = z.infer<typeof UserSchema>;

This schema specifies that the id must be a UUID, the name must be a string with at least 2 characters, the email must be a valid email address, and the age must be a number between 0 and 120. Using z.infer, we can derive a TypeScript type from the schema, providing compile-time type safety.

Benefits of this Approach

  • Data Consistency: Zod validation ensures that data conforms to the expected format, reducing the risk of errors.
  • Decoupling: DTOs decouple the data representation from the underlying model, allowing for flexibility in API design.
  • Type Safety: TypeScript and Zod provide compile-time type safety, catching errors early in the development process.

Conclusion

By combining DTOs and Zod validation, we've created a more robust and maintainable backend for our portal. This approach not only ensures data quality but also provides a clear separation of concerns, making the codebase easier to understand and evolve.


Generated with Gitvlg.com

Streamlining Business Logic with DTOs and Zod Validation in Our Portal Backend
J

Johandev

Author

Share: