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 🙏

© 2024 – Pkg Stats / Ryan Hefner

fast-mapper

v1.0.0-beta.0

Published

A JIT & decorator based class mapper focusing on performance

Downloads

1

Readme

fast-mapper makes it easy to map classes to plain objects and back using @decorators.

Why? Because solutions like class-transformer are verrrryyy slow when hydrating a lot of documents, and we want to do better... so use this instead!

Features

  • Extremely simply @Decorator() based document mapping
  • Very fast 🚀! (thanks to JIT compilation)
  • Discriminator mapping
  • & more!

Planned Features

  • [ ] Validation
  • [ ] Create more common types
  • [ ] Figure out what else should be added

How to use

import { Property, map } from 'fast-mapper';
import { ObjectId } from 'mongodb';

abstract class Base {
  @Property({ type: ObjectIdType })
  _id: ObjectId;

  get id(): string {
    return this._id.toHexString();
  }

  @Property()
  createdAt: Date = new Date();

  @Property()
  updatedAt: Date = new Date();
}

Now create our document class with some fields.

import { Property } from 'fast-mapper';
import { BaseDocument, Address, Pet } from './models';

class User extends Base {
  @Property()
  name: string;

  @Property(() => Address)
  address: Address; // single embedded document

  @Property(() => [Address])
  addresses: Address[] = []; // array of embedded documents

  @Property(() => [Pet])
  pets: Pet[] = []; // array of discriminator mapped documents

  @Property(() => Pet)
  favoritePet: Pet; // single discriminator mapped document
  
  @Property({ type: 'date' }) // "type" needs to be specified here due to reflection not seeing the Date[] since it's an array.
  dates: Date[];
}

and here's the nested Address document.

import { Property } from 'fast-mapper';

class Address {
  @Property()
  city: string;

  @Property()
  state: string;
}

Now let's do some mapping...

import { map } from 'fast-mapper';
import { User } from './models';

const user = new User();
user.name = 'John Doe';
// ... populate the rest


/**
 * Plain mapping (converts to destination mapping, including names)
 */

// converting to the mapped value as a plain object
const plain = map(User).toPlain(user);

// .. and convert back
const user = map(User).fromPlain(plain);


/**
 * JSON mapping (keeps original property names)
 */

// convert to a JSON compatible type (useful for micro-service communication as an example)
const json = map(User).toJSON(user);

// .. and convert back
const user = map(User).fromJSON(json);


/**
 * Instance Property Mapping (keeps original property names)
 */

// Alternatively, you can create a user via mapping:
const user = map(User).fromProps({ name: 'John Doe', /* ... */ });

// and if you want to convert a user to it's props (unmapped field names)
const props = map(User).toProps(user);

Property Types

Types can be automatically discovered using reflection (reflect-metadata) and the Type.prototype.isType property, however, if your property is an array, you must specify the type manually using @Property({ type: 'date' }) dates: Date[] otherwise the values will not be mapped.

You can also create a custom type that extends Type (See types/DateType as an example).

To register your custom type, see the example below (these are also in tests/__fixtures__).

registerType(new ObjectIdType());
registerType(new UUIDType());

Discriminator Mapping

fast-mapper also has support for discriminator mapping (polymorphism). You do this by creating a base class mapped by @Discriminator({ property: '...' }) with a @Property() with the name of the "property". Then decorate discriminator types with @Discriminator({ value: '...' }) and fast-mapper takes care of the rest.

import { Discriminator, Property } from 'fast-mapper';

@Discriminator({ property: 'type' })
abstract class Pet {
  @Property()
  abstract type: string;

  @Property()
  abstract sound: string;

  speak(): string {
    return this.sound;
  }
}

@Discriminator({ value: 'dog' })
class Dog extends Pet {
  type: string = 'dog';
  sound: string = 'ruff';

  // dog specific fields & methods
}

@Discriminator({ value: 'cat' })
class Cat extends Pet {
  type: string = 'cat';
  sound: string = 'meow';

  // cat specific fields & methods
}

And now, lets see the magic!

import { map } from 'fast-mapper';
import { User } from './models';

async () => {
  const user = map(User).create({
    name: 'John Doe',
    address: {
      city: 'San Diego',
      state: 'CA'
    },
    addresses: [
      {
        city: 'San Diego',
        state: 'CA'
      }
    ],
    pets: [{ type: 'dog', sound: 'ruff' }],
    favoritePet: { type: 'dog', sound: 'ruff' }
  });
  
  console.log(user instanceof User); // true

  const mapped = map(User).toPlain(user);

  console.log(user instanceof User); // false
};

Want to use this in a library / ORM?

We wanted to make sure to keep library and user-land mapping separated, so consuming libraries can have their own mapping and type registration separate from a user's.

All you have to do to add mapping to your library is:

import { Mapper } from 'fast-mapper';

const mapper = new Mapper();

function Field(/* your options */): PropertyDecorator {
  return (target: any, propertyName: string) => {
    mapper.decorators.Property(/* map your options to Property options */)(target, propertyName);
  }
}

Examples

For more advanced usage and examples, check out the tests.