How to use typescript automapper(nartc/mapper) with Prisma js?

2 min read 05-10-2024
How to use typescript automapper(nartc/mapper) with Prisma js?


Mapping Prisma Models with AutoMapper in TypeScript

Efficiently handling data transformations between different data structures is a common task in software development. TypeScript's powerful type system, combined with Prisma's elegant ORM, provides a solid foundation for this process. However, when dealing with complex object hierarchies and numerous mapping rules, manual data mapping can become tedious and error-prone. This is where AutoMapper, a popular library for object mapping, shines.

The Problem: Manual Data Mapping

Imagine you have a Prisma model representing a user in your database:

// Prisma Model
export type User = {
  id: number;
  firstName: string;
  lastName: string;
  email: string;
};

Now, you need to expose a simplified user representation through your API:

// API Response
export interface UserDto {
  id: number;
  name: string;
  email: string;
}

Manually mapping between these two structures would require writing repetitive boilerplate code:

function mapUserToDto(user: User): UserDto {
  return {
    id: user.id,
    name: `${user.firstName} ${user.lastName}`,
    email: user.email,
  };
}

Enter AutoMapper: Streamlining Data Transformations

AutoMapper simplifies this process by providing a declarative way to define mapping rules. Let's see how to use it with Prisma:

1. Install AutoMapper:

npm install @nartc/mapper

2. Configure AutoMapper:

import { Mapper } from "@nartc/mapper";

const mapper = new Mapper();

// Define mapping rule from User to UserDto
mapper.createMap<User, UserDto>()
  .forMember(dest => dest.name, opt => opt.mapFrom(src => `${src.firstName} ${src.lastName}`));

// Optional: Add more mapping rules for other entities

3. Use the Mapper:

const user: User = {
  id: 1,
  firstName: "John",
  lastName: "Doe",
  email: "[email protected]",
};

const userDto = mapper.map<User, UserDto>(user);

// userDto will now hold the mapped data
console.log(userDto); // { id: 1, name: "John Doe", email: "[email protected]" }

Benefits of Using AutoMapper with Prisma

  • Reduced Boilerplate: No more manual mapping code, simplifying your data transformation logic.
  • Improved Maintainability: Changes to your data models are automatically reflected in your mapping rules.
  • Enhanced Type Safety: TypeScript's strong typing system ensures mapping errors are caught early.
  • Reusable Mappings: Define mappings once and use them throughout your application.

Beyond Basic Mapping

AutoMapper offers a powerful set of features for complex mapping scenarios:

  • Nested Object Mapping: Easily map between nested objects and arrays.
  • Custom Mapping Logic: Define custom mapping functions for complex transformations.
  • Conditional Mapping: Apply different mappings based on specific conditions.
  • Value Conversion: Convert data types between different formats (e.g., date to string).

Conclusion

AutoMapper provides a powerful and flexible solution for mapping Prisma models in TypeScript. By leveraging its declarative mapping approach, you can streamline data transformations, reduce code complexity, and improve the maintainability of your applications. Explore the full capabilities of AutoMapper to efficiently manage data mapping within your TypeScript projects.

References: