npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

custom-automapper

v1.0.11

Published

A powerful, type-safe object mapping library for TypeScript and NestJS

Readme

@custom-automapper

A powerful, type-safe, extensible object mapping library for TypeScript and NestJS, built for real-world production use.
It supports decorators, caching, async mapping, validation, and more — all without the @automapper/core dependency.


✨ Features

  • 🧩 Automatic mapping of DTOs using decorators
  • Caching support for high-performance repeated mappings
  • 🌀 Async & sync mapping support
  • 🧠 Type-safe mapping configurations
  • 🪄 Deep clone and transformation utilities
  • 🏗️ Nested, array, and enum mapping
  • 💉 NestJS-friendly integration
  • 🛠️ Mapper helpers (mapFrom, ignore, transform, etc.)
  • 🧰 Validation rules per property

📦 Installation

npm install @custom-automapper
# or
yarn add @custom-automapper

⚙️ Basic Usage

import { Mapper, AutoMap } from '@custom-automapper';

// DTOs
class SourceDTO {
  @AutoMap()
  name: string;

  @AutoMap()
  age: number;
}

class TargetDTO {
  @AutoMap()
  name: string;

  @AutoMap()
  age: number;
}

// Mapper
const mapper = new Mapper();
mapper.createMap(SourceDTO, TargetDTO);

const source = new SourceDTO();
source.name = 'John';
source.age = 30;

const target = mapper.map(source, TargetDTO);

console.log(target); // { name: 'John', age: 30 }

🧠 Advanced Usage

1️⃣ Configuring Mapper in Constructor

You can configure global options like caching, cloning, or naming conventions in the constructor:

import { Mapper } from '@custom-automapper';

const mapper = new Mapper({
  globalOptions: {
    deepClone: true,
    skipUndefined: true,
  },
  cache: {
    enabled: true,          // Enable caching globally
    strategy: 'memory',     // 'memory' (default) or custom
  }
});

2️⃣ Enabling or Disabling Cache at Runtime

mapper.setCacheEnabled(true);
console.log(mapper.isGlobalCacheEnabled()); // true

mapper.setCacheEnabled(false);

🧩 Custom Mappings

You can explicitly define property mappings using mapFrom:

mapper.createMap(SourceDTO, TargetDTO, {
  name: mapper.mapFrom(src => src.name.toUpperCase()), // transform source value
  age: mapper.mapFrom('age') // map directly by key
});

🔁 Reverse Mapping

Generate reverse mapping automatically:

mapper.createMap(SourceDTO, TargetDTO, {
  name: src => src.name,
  age: src => src.age,
});

// Create reverse mapping (TargetDTO → SourceDTO)
mapper.createReverseMap(SourceDTO, TargetDTO);

⚡ Async Mapping

When mapping data that involves async transforms (e.g., fetching data or calling async functions):

await mapper.createMap(UserEntity, UserDTO, {
  profileUrl: async src => await getProfileUrl(src.id)
});

const result = await mapper.mapAsync(userEntity, UserDTO);

🧱 Array Mapping

const users = [user1, user2, user3];
const dtos = mapper.mapArray(users, UserDTO);

// Or async version
const dtosAsync = await mapper.mapArrayAsync(users, UserDTO);

🧩 Conditional Mapping

Apply conditional mapping logic dynamically:

const target = mapper.mapConditional(source, TargetDTO, [
  {
    condition: src => src.age > 18,
    map: src => ({ status: 'Adult' })
  },
  {
    condition: src => src.age <= 18,
    map: src => ({ status: 'Minor' })
  }
]);

✅ Validation Rules

Attach validation rules per class property and validate mapped objects.

mapper.addValidation(UserDTO, 'email', {
  validate: value => value.includes('@'),
  message: 'Email must contain @ symbol'
});

await mapper.validate(new UserDTO()); // throws if invalid

🧠 Metadata Mapping with Decorators

Decorators like @AutoMap, @MapFrom, and @MapTo automatically handle property mapping.

class AddressDTO {
  @AutoMap()
  city: string;
}

class UserDTO {
  @AutoMap()
  name: string;

  @AutoMap(() => AddressDTO)
  address: AddressDTO;
}

🪄 Map with Metadata Summary

Get detailed insights into which properties were mapped or skipped.

const result = mapper.mapWithMetadata(source, TargetDTO);

console.log(result.metadata);
/*
{
  mappedProperties: ['name', 'age'],
  skippedProperties: [],
  errors: [],
  executionTime: 2
}
*/

🔥 Cache Behavior

Each mapped source object is cached by reference using a WeakMap, minimizing re-computation on repeated mapping calls.

Example:

mapper.setCacheEnabled(true);

const src = new SourceDTO();
src.name = 'Cached User';
src.age = 25;

const first = mapper.map(src, TargetDTO);
const second = mapper.map(src, TargetDTO); // served from cache

🧹 Utility Methods

| Method | Description | |--------|--------------| | map() | Maps an object synchronously | | mapAsync() | Maps asynchronously | | mapArray() | Maps an array synchronously | | mapArrayAsync() | Maps an array asynchronously | | createReverseMap() | Generates reverse mapping | | clear() | Clears registry and cache | | getMappings() | Lists registered mappings | | mapWithMetadata() | Maps with runtime metadata |


🧱 Example: Full Flow

class UserEntity {
  @AutoMap()
  id: number;

  @AutoMap()
  fullName: string;

  @AutoMap()
  email: string;
}

class UserDTO {
  @AutoMap()
  id: number;

  @AutoMap()
  name: string;

  @AutoMap()
  email: string;
}

const mapper = new Mapper({ cache: { enabled: true } });

mapper.createMap(UserEntity, UserDTO, {
  name: src => src.fullName
});

const entity = { id: 1, fullName: 'Nishit Shiv', email: '[email protected]' };

const dto = mapper.map(entity, UserDTO);
console.log(dto); // { id: 1, name: 'Nishit Shiv', email: '[email protected]' }

📊 Comparison with @automapper/core

| Feature | Custom AutoMapper | @automapper/core | |----------|------------------|------------------| | Decorator-driven mapping | ✅ | ✅ | | Nested object mapping | ✅ | ✅ | | Custom property mapping | ✅ | ✅ | | Async mapping | ✅ | ✅ | | Caching | ✅ | ❌ | | Validation | ✅ | ❌ | | DI integration | Manual | Built-in |


🧩 Future Roadmap

  • Enhanced polymorphic mapping with type inference
  • NestJS DI integration for singleton mappers
  • Profiles for multi-context mapping
  • Built-in transformations (formatDate, uppercase, etc.)

🤝 Contributing

Pull requests, discussions, and suggestions are welcome.
Open an issue or PR with a clear description of improvement.


🪪 License

MIT License
© 2025 Nishit Shiv