Git Product home page Git Product logo

automapper-transformer-plugin's Introduction

AutoMapper Transformer Plugin

This plugin is to support @nartc/automapper in order to enhance DX by reducing boilerplate code.

travis bundlephobia downloads npm license Known Vulnerabilities

How it works

class Profile {
  bio: string;
  age: number;
}

class User {
  firstName: string;
  lastName: string;
  profile: Profile;
}

The above TS code will be compiled to:

class Profile {}
class User {}

We need to decorate the field declarations with @AutoMap() in order for @nartc/automapper to work properly.

class Profile {
  @AutoMap()
  bio: string;
  @AutoMap()
  age: number;
}

class User {
  @AutoMap()
  firstName: string;
  @AutoMap()
  lastName: string;
  @AutoMap(() => Profile)
  profile: Profile;
}

That will get very verbose very soon. @nartc/automapper-transformer-plugin can help that.

This plugin utilizes Abstract Syntax Tree (AST) to run a before transformer. The plugin will look at files that end with *.model.ts and *.vm.ts and keep the metadata of the classes in a form of a static function. @nartc/automapper-transformer-plugin keeps the metadata as follow:

class Profile {
  static __NARTC_AUTOMAPPER_METADATA_FACTORY() {
    return { bio: () => String, age: () => Number };
  }
}

class User {
  static __NARTC_AUTOMAPPER_METADATA_FACTORY() {
    return { firstName: () => String, lastName: () => String, profile: () => Profile };
  }
}

This allows @nartc/automapper to look at these models and run the static function to hold the metadata for each model, exactly like what @AutoMap() would do for you. In fact, internally, @nartc/automapper calls the static function and iterates over the result then calls AutoMap() directly.

Limitations

Transformers bring great value to developers but they are an experimental feature in TypeScript. Hence, to use it, you'd need to modify your build steps directly and each build tool has different setup.

@nartc/automapper-transformer-plugin will only add the minimum amount of code relating to the @AutoMap() decorator. If you want to have extra options (options from class-transformer library), you'd want to still decorate the fields manually.

  • Union: Currently, @nartc/automapper-transformer-plugin will handle most Nullable (type | null) and Maybe (propKey?: type) cases. However, for complex cases where you have unions with different types (string | number | boolean or ClassA | ClassB), please consider decorate the property (field) manually with @AutoMap() decorator.

Installation

npm install @nartc/automapper-transformer-plugin --save-dev
# or shorthand version
npm i -D @nartc/automapper-transformer-plugin

Usage

@nartc/automapper-transformer-plugin only has one configuration option for now

interface TsAutoMapperPluginOptions {
  modelFileNameSuffix?: string[];
}

modelFileNameSuffix is default to ['.model.ts', '.vm.ts']

Webpack

I hope you are using ts-loader or some form of ts-loader forks. Configure your webpack.config.js as follows to turn on the plugin

...
const tsAutoMapperPlugin = require('@nartc/automapper-transformer-plugin');
const pluginOptions = {
  modelFileNameSuffix: [...]
};

module.exports = {
  ...
  module: {
    rules: [
      ...
      {
        test: /\.tsx?$/,
        loader: 'ts-loader',
        options: {
          getCustomTransformers: program => ({
            before: [tsAutoMapperPlugin(program, pluginOptions).before]
          })
        }
      }
      ...
    ]
  }
  ...
};

Rollup

Use rollup-plugin-typescript2 as it has tranformers capability.

import tsAutomapperPlugin from '@nartc/automapper-transformer-plugin';
import typescript from 'rollup-plugin-typescript2';
const pluginOptions = {
  modelFileNameSuffix: [...]
};

export default {
  ...
  preserveModules: true, // <-- turn on preserveModules
  plugins: [
    ...
    typescript({
      transformers: [service => ({
        before: [tsAutomapperPlugin(service.getProgram(), pluginOptions).before]
      })]
    }),
    ...
  ]
}

ttypescript

ttypescript patches typescript in order to use transformers in tsconfig.json. See ttypescript's README for how to use this with module bundlers such as webpack or Rollup.

{
  "compilerOptions": {
    ...,
    "plugins": [
        {
            "transform": "@nartc/automapper-transformer-plugin",
            "modelFileNameSuffix": [...]
        }
    ],
    ...
  }
}

Check out this Examples Repo out.

Contribution

All contributions of any kind are welcomed.

License

MIT

automapper-transformer-plugin's People

Contributors

greenkeeper[bot] avatar gvgoodpaster avatar nartc avatar renovate-bot avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

automapper-transformer-plugin's Issues

How to use automapper transformer plugin for End-to-end testing

I'm working on NestJs application and writing e2e testing.
We are using autompper transformer plugin to avoid property decorator require with @automapper/classes. It is working with build and unit test case but doesn't support the e2e testing. we have follow below nestJs document to configure or write e2e testing:

https://docs.nestjs.com/fundamentals/testing

Change to add transformer plugin:

Added transformer-plugin entry to nestCLI and dependency in package.json
"plugins": ["@automapper/classes/transformer-plugin"],

does anyone get this issue? does it require any configuration?

Add supporting optional and nullable properties.

Hey, I continue testing the plugin :) some additional moments from my side.
In all cases, I've used your webpack example

ts-loaded can't understand nullable properties.

Let's modify the example to use primitive nullable property there.

export class Address {
  street!: string;
  zipCode!: string | null;
}

export class AddressVm {
  formattedStreet!: string;
  zipCode!: string | null;
}

If you build the app, you will see an exception "TypeError: Cannot read property 'transformFlags' of undefined".
The same effect with classes. Let's mark the profile property as nullable.

export class User {
  firstName!: string;
  lastName!: string;
  profile!: Profile | null;
  addresses!: Address[];
}

export class UserVm {
  first!: string;
  last!: string;
  full!: string;
  profile!: ProfileVm | null;
  addresses!: AddressVm[];
}

Build exception "TypeError: Cannot read property 'transformFlags' of undefined".

ts-loaded can't understand optional properties.

I've added test property to the User model. The property can be marked as undefined. If you build the app, you will see an exception "TypeError: Cannot read property 'transformFlags' of undefined".
The same situation with class types.

export class User {
  firstName!: string;
  lastName!: string;
  profile!: Profile;
  addresses!: Address[];
  test?: number;
}

export class UserVm {
  first!: string;
  last!: string;
  full!: string;
  profile!: ProfileVm;
  addresses!: AddressVm[];
  test?: number;
}

If I used the decorator, all examples would work well.
It would be great if you could find a solution to how to fix these issues easily... and sorry for my importunity :))

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on Greenkeeper branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because it uses your CI build statuses to figure out when to notify you about breaking changes.

Since we didn’t receive a CI status on the greenkeeper/initial branch, it’s possible that you don’t have CI set up yet.
We recommend using:

If you have already set up a CI for this repository, you might need to check how it’s configured. Make sure it is set to run on all new branches. If you don’t want it to run on absolutely every branch, you can whitelist branches starting with greenkeeper/.

Once you have installed and configured CI on this repository correctly, you’ll need to re-trigger Greenkeeper’s initial pull request. To do this, please click the 'fix repo' button on account.greenkeeper.io.

Can't Resolve classes in a different .ts file

I am facing an issue when using the automapper transformer plugin with nestjsx-automapper.
I have added the plugin info in nest-cli.json file.

Transformer Plugin unable to resolve class defined in a separate .ts file.

Details

Versions:
NestJs: 7.4.2
nestjsx-automapper: 3.1.2
@nartc/automapper-transformer-plugin: 1.0.21
typescript: 3.7.4

Example.
There is profile.ts file with following.

export class Profile {
  bio: string;
  age: number;
}

and there is user.ts file with

import { Profile } from './profile'
export class User {
  firstName: string;
  lastName: string;
  profile: Profile;
}

when building the project, error is thrown stating, Can't Resolve Profile from the User Class.

Please advise.

Thanks,

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Rate-Limited

These updates are currently rate-limited. Click on a checkbox below to force their creation now.

  • chore(deps): update dependency @types/jest to v27.5.2
  • chore(deps): update dependency eslint-plugin-prettier to v4.2.1
  • chore(deps): update dependency tslib to v2.6.2
  • chore(deps): update dependency @types/jest to v29
  • chore(deps): update dependency eslint-plugin-prettier to v5
  • chore(deps): update dependency husky to v9
  • chore(deps): update dependency lint-staged to v15
  • chore(deps): update dependency prettier to v3
  • chore(deps): update dependency typescript to v5
  • 🔐 Create all rate-limited PRs at once 🔐

Edited/Blocked

These updates have been manually edited so Renovate will no longer make changes. To discard all commits and start over, click on a checkbox.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

npm
package.json
  • lodash.compact 3.0.1
  • lodash.flatten 4.4.0
  • @commitlint/cli 12.1.4
  • @commitlint/config-conventional 12.1.4
  • @types/jest 27.0.1
  • @types/lodash.compact 3.0.6
  • @types/lodash.flatten 4.4.6
  • commitizen 4.2.2
  • cz-conventional-changelog 3.3.0
  • eslint-plugin-prettier 4.0.0
  • husky 7.0.2
  • lint-staged 11.1.2
  • prettier 2.3.2
  • semantic-release 17.3.7
  • tsdx 0.14.1
  • tslib 2.3.1
  • ttypescript 1.5.12
  • typescript 3.9.7
  • node >=8.0.0
travis
.travis.yml
  • node 10
  • node 12
  • node 12

  • Check this box to trigger a request for Renovate to run again on this repository

Add supporting of primitive arrays

Hi. I found an issue when the model uses an array with primitive types as a property.
I used your example for testing.
Please update User* models to use string array instead of the Address one.

export class User {
  firstName!: string;
  lastName!: string;
  profile!: Profile;
  addresses!: string[];
}

export class UserVm {
  first!: string;
  last!: string;
  full!: string;
  profile!: ProfileVm;
  addresses!: string[];
}

export class UserVm {
  first!: string;
  last!: string;
  full!: string;
  profile!: ProfileVm;
  addresses!: string[];
}

Then try to build the app, you will see an exception TypeError: Cannot read property 'transformFlags' of undefined.
I hope it wouldn't be very difficult to fix.

Class with Enum field leads to a TypeError

Hi @nartc,

currently I am using the automapper-transformer-plugin in combination with nestjs. It works great for all of my types as indended, but if I create a class with an enum type the compiler throws a TypeException.

Error:

 TypeError: Cannot read property 'transformFlags' of undefined

A workaround is to add the @AutoMap() annotation manually to the enum field.

Could you look into this issue.

Versions:
NestJs: 7.0.0
nestjsx-automapper: 3.1.0
@nartc/automapper-transformer-plugin: 1.0.20
typescript: 3.7.4

Not working example:

enum State {
  READY,
  STOPED
}

export class ExampleEntity {
  state: State;
  id: number;

  constructor() {
    this.state = State.READY;
  }
}

Working example:

enum State {
  READY,
  STOPED
}

export class ExampleEntity {
  @AutoMap() state: State;
  id: number;

  constructor() {
    this.state = State.READY;
  }
}

The plugin doesn't work correctly for plain objects and arrays.

Hi. Thanks for the wonderful idea to use custom transformers with the ts-loader to avoid some boilerplate code of using decorators. I really like it. Unfortunately, I found some issues there. In all cases, I used your example with the webpack build tool. Could you please take a look?

1. Using plain objects:

Changes in the index.ts file

...
const plainObj = JSON.parse(JSON.stringify(user));

const vm = Mapper.map(plainObj, UserVm, User);
console.log(vm);

When I run the command npm run build, I see the exception throw new Error("Mapping not found for source " + mappingName);. I guess the mapper couldn't find a rule to map the plain object of profile property to the Profile class. Then I added the directive to this property and it worked well.

export class User {
  firstName!: string;
  lastName!: string;
  @AutoMap(() => Profile)
  profile!: Profile;
}

The result has correct object types: UserVm for the class and ProfileVm for the property.

UserVm {
  first: 'Chau',
  last: 'Tran',
  full: 'Chau Tran',
  profile: ProfileVm { bioString: 'Developer', ageNumber: 28 } }

2. Using arrays of an object:

I modified a bit example to use an array of the Profile entity.

export class User {
  firstName!: string;
  lastName!: string;
  profiles!: Profile[];
}

export class UserVm {
  first!: string;
  last!: string;
  full!: string;
  profiles!: ProfileVm[];
}

When I run the example I see the exception: TypeError: Cannot read property 'transformFlags' of undefined.
Then I used the decorator, and it worked well.

export class User {
  firstName!: string;
  lastName!: string;
  @AutoMap(() => Profile)
  profiles!: Profile[];
}

export class UserVm {
  first!: string;
  last!: string;
  full!: string;
  @AutoMap(() => ProfileVm)
  profiles!: ProfileVm[];
}

// index.ts
const user = new User();
user.firstName = 'Chau';
user.lastName = 'Tran';
user.profiles = [new Profile()];
user.profiles[0].bio = 'Developer';
user.profiles[0].age = 28;

const plainObj = JSON.parse(JSON.stringify(user));

const vm = Mapper.map(plainObj, UserVm, User);
console.log(vm);

The result:

UserVm {
  profiles: [ ProfileVm { bioString: 'Developer', ageNumber: 28 } ],
  first: 'Chau',
  last: 'Tran',
  full: 'Chau Tran' }

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Error type: undefined. Note: this is a nested preset so please contact the preset author if you are unable to fix it yourself.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.