Giter Site home page Giter Site logo

nestjsx / automapper Goto Github PK

View Code? Open in Web Editor NEW
121.0 121.0 7.0 1.38 MB

An Object-Object AutoMapper module for NestJS.

Home Page: https://nestjsx.github.io/automapper/

License: MIT License

TypeScript 98.01% JavaScript 1.99%
automapper nestjs typescript

automapper's Introduction

Nestjsx Logo

A set of opinionated NestJS extensions and modules

Travis Coverage Status

Packages

  • @nestjsx/common - A set of NestJs decorators, interfaces and configuration for application modules bootstraping.

Tests

npm run test

automapper's People

Contributors

bashleigh avatar dependabot-preview[bot] avatar dependabot[bot] avatar greenkeeper[bot] avatar nartc avatar

Stargazers

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

Watchers

 avatar  avatar  avatar  avatar  avatar

automapper's Issues

An in-range update of @nestjs/testing is breaking the build 🚨

The devDependency @nestjs/testing was updated from 6.10.5 to 6.10.6.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@nestjs/testing is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • βœ… continuous-integration/travis-ci/push: The Travis CI build passed (Details).
  • ❌ Travis CI - Branch: The build errored.

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Mongoose schemas do not map automatically for matching properties

I have a Mongoose schema:

import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document, Types } from 'mongoose';

@Schema({
  collection: 'user-profiles',
  timestamps: true,
  toJSON: {
    getters: true,
    virtuals: true,
  },
})
export class UserProfile {
  @Prop({
    type: String,
    required: true,
    unique: true,
    index: true,
  })
  public email: string;

  static get schema() {
    return SchemaFactory.createForClass(UserProfile);
  }

  static get modelName(): string {
    return this.name;
  }
}

export type UserProfileDocument = UserProfile & Document;

I have a view model:

import { ApiProperty } from '@nestjs/swagger';

export class UserProfileVM {
  @ApiProperty()
  email: string;
}

And a automapper profile:

import { Profile, ProfileBase, AutoMapper } from 'nestjsx-automapper';
import { UserProfile } from '../mongo/user-profile.schema';
import { UserProfileVM } from './user-profile.vm';

@Profile()
class UserProfileProfile extends ProfileBase {
  constructor(mapper: AutoMapper) {
    super();
    mapper.createMap(UserProfile, UserProfileVM);
  }
}

I configured everything according to the docs. But mapping does not work. If I set forMember for every field - than everything works fine. But why doesn't conventional mapping work?

Also if I set @AutoMap decorator on email field - I got the error:

Error mapping:
- Source: class UserProfile {
}
- Destination: class UserProfileVM {
}

Unmapped properties:

fireID

I have a theory that this automapper does not work well with Mongoose schemas. What would you advice me to do?

Thanks in advance!

An in-range update of @types/jest is breaking the build 🚨

The devDependency @types/jest was updated from 25.1.1 to 25.1.2.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@types/jest is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • βœ… continuous-integration/travis-ci/push: The Travis CI build passed (Details).
  • ❌ Travis CI - Branch: The build errored.

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Testing module does not register profiles?

I am trying to test a controller which uses AutoMapper. Here is a code snippet.

import './label.profile';
import { AutomapperModule } from 'nestjsx-automapper';


describe('LabelController', () => {
	let controller: LabelController;

	beforeEach(async () => {
		const module: TestingModule = await Test.createTestingModule({
			imports: [AutomapperModule.withMapper()],
			controllers: [LabelController],
			providers: [LabelRepository, LabelService],
		}).compile();

		controller = module.get<LabelController>(LabelController);
	});
	
	it('should get all labels', () => {
		return controller.getLabels().then(labels => {
			return expect(labels.length).toBe(2);
		});
	});
});

The part where I put the Profile decorator:


@Profile()
export class LabelProfile extends ProfileBase {
	constructor(mapper: AutoMapper) {
		super();
		mapper.createMap(Label, LabelDto).reverseMap();
	}
}

The error I get is

   Mapping not found for source class Label {
    } and destination class LabelDto {
        constructor(type, description) {
            this.type = type;
            this.description = description;
        }
    }

How could I map array properties between classes?

Hi. I have class with an array property:

export class DocumentDto {
    @AutoMap()
    name: string;

    @AutoMap(() => UsbDto)
    usbs: UsbDto[];
}

and I want to map it to the next class:

export class DocumentModel {
    @AutoMap()
    name: string;

    @AutoMap(() => UsbModel)
    usbs: UsbModel[];
}

How could I map the usbs property?

Thanks.

An in-range update of nestjs is breaking the build 🚨

There have been updates to the nestjs monorepo:

  • The devDependency @nestjs/core was updated from 6.10.2 to 6.10.3.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

This monorepo update includes releases of one or more dependencies which all belong to the nestjs group definition.

nestjs is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).
  • ❌ Travis CI - Branch: The build errored.

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Mapper is not working with Profiles

Hi, I'm using the automapper in this way:

app.module.ts
@module({
imports: [
AutomapperModule.withMapper()
],
controllers: [],
providers: []
})
export class AppModule {}

queue.profile.ts
@Profile()
export class QueueProfile extends ProfileBase {
constructor(mapper: AutoMapper) {
super();
mapper.createMap(Queue, CreateMessageDto).reverseMap();
}
}

queue.controller.ts
@controller()
export class QueueController {
constructor(
@InjectMapper() private readonly mapper: AutoMapper
) {}

@post()
@httpcode(HttpStatus.CREATED)
createMessage(@Body() message: CreateMessageDto): void {
try {
const queue = this.mapper.map(message, Queue);
} catch (error) {
throw new InternalServerErrorException(error);
}
}
}

queue.ts
export class Queue {
filePath: string;
pageNumber: number;
containerName: string;
resultPath: string;
language: string;
}

create-message.dto.ts
export class CreateMessageDto {
@IsString()
readonly filePath: string;

@IsNumber()
readonly pageNumber?: number = 1;

@IsString()
readonly containerName: string;

@IsString()
readonly resultPath?: string;

@IsString()
readonly language?: string = 'fr-FR';
}

My problem is that when I call to the controller queue contains only a proto field

It seems that the mapping is not working quite well.

Thanks

An in-range update of @nartc/automapper is breaking the build 🚨

The dependency @nartc/automapper was updated from 2.0.2 to 2.1.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@nartc/automapper is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).
  • ❌ Travis CI - Branch: The build failed.

Release Notes for v2.1.0

2.1.0 (2019-12-05)

Bug Fixes

  • mapperasync.ts: test async (2229d3c)
  • travis.yml: fix script (d949a46)
  • travis.yml: modify script (c4f3f85)
  • travis.yml: modify script (87044ad)
  • travis.yml: remove node 10 (8f91c7b)

Features

  • mapperasync.ts: test async (6b4d47a)
Commits

The new version differs by 26 commits.

  • d949a46 fix(travis.yml): fix script
  • c4f3f85 fix(travis.yml): modify script
  • 87044ad fix(travis.yml): modify script
  • 2229d3c fix(mapperasync.ts): test async
  • 8f91c7b fix(travis.yml): remove node 10
  • 6b4d47a feat(mapperasync.ts): test async
  • bcd13bc test async
  • dc702c2 Merge branch 'master' of https://github.com/nartc/mapper
  • 510d794 chore(automapper.ts): minor clean up
  • 276f77b Merge pull request #21 from nartc/greenkeeper/ts-node-8.5.4
  • 44f4cc2 chore(package): update lockfile yarn.lock
  • d38a1f2 chore(package): update ts-node to version 8.5.4
  • 94f90fa Merge pull request #20 from nartc/greenkeeper/ts-node-8.5.3
  • a3ad8e9 chore(package): update lockfile yarn.lock
  • 90bcf56 chore(package): update ts-node to version 8.5.3

There are 26 commits in total.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Unit test with jest and AutoMapper

Hi. I have a controller that uses a mapper. I want to test its methods. I'm using jest, but when I run the tests, I have this error message:

TypeError: decorator is not a function

      2 | 
      3 | export class BlobMessage {
    > 4 |   @AutoMap()
        |                                 ^
      5 |   filePath: string;
      6 | 
      7 |   @AutoMap()

      at DecorateProperty (node_modules/reflect-metadata/Reflect.js:553:33)
      at Object.decorate (node_modules/reflect-metadata/Reflect.js:123:24)
      at __decorate (src/models/blob-message.ts:4:92)
      at Object.<anonymous> (src/models/blob-message.ts:5:3)
      at Object.<anonymous> (test/controllers/consumer/consumer.controller.spec.ts:4:1)

This is my test file:

import { Test, TestingModule } from '@nestjs/testing';

import { Logger } from '@nestjs/common';

jest.mock('@services/consumer/consumer.service');
jest.mock('nestjsx-automapper');

let controller: Controller;
let service: Service;

describe('ConsumerController', () => {
  let testingModule: TestingModule;

  beforeAll(async () => {
    testingModule = await Test.createTestingModule({
      controllers: [Controller],
      providers: [Service, Logger],
    }).compile();

    controller = testingModule.get<Controller>(Controller);
    service = testingModule.get<Service>(Service);
  });

  it('should be defined', () => {
    expect(controller).toBeDefined();
    expect(service).toBeDefined();
  });

Any ideas?

Missing definition files

Hi,

I was looking for a mapper library for my NestJS project and found this project.

But I ran into an issue during setup. When I added the module to my main module, VS Code was not able to auto import this module.

Then I looked in node_modules/nestjs-automapper and saw that there were only js files:

image

The typescript definition files seems to be missing.

Metadata for XXXX is a primitive or Array.

Hi. I have a dto class and a model class that have an array property defined like this:

@AutoMap()
params: any[]

When I try to map them, I have the following error:

"Metadata for params is a primitive or Array. Consider manual map this property"

Is there any solution for that or do I need to map this property manually?

Mapping recursively problem

Hi, I have the next dto object:

{
            type: 'html',
            data: [
                {
                    type: 'body',
                    data: [
                        {
                            type: 'div',
                            data: [
                                {
                                    text: 'This is the text of the div',
                                    inlineStyleRange: [],
                                    truth: true,
                                    data: [],
                                    id: 'fd90dbdb-7f1b-49d5-8ee6-9178d2bb96a5',
                                },
                            ],
                            blockKey: 'v8z2j_0',
                        },
                    ],
                    blockKey: 'wiyy6_109',
                },
            ],
            blockKey: 'at9qq_0',
        }

I want to map this json object to a model class. I use this profile:

@Profile()
export class SectionProfile extends ProfileBase {
    constructor() {
        super();
    }

    configure(mapper: AutoMapper) {
        mapper
            .createMap(Section, SectionDto)
            .reverseMap();
    }
}

But, when I try to map it, it throws an error with the next message:
Metadata for data is a primitive or Array. Consider manual map this property

Any solutions?

You can find the code in the https://github.com/anrolmar/automapper-recursively

Transformer Plugin doesn't detect fields in parent classes

I'm submitting a...


[ ] Regression
[x] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request

Current behavior

When implementing a simple inheritance and later mapping the subclass, the plugin doesn't detect the fields from the parent class. They need be annotated with @AutoMap to work properly.

Expected behavior

Transformer Plugin should detect parent properties automatically, and map them transparently.

Minimal reproduction of the problem with instructions

Here are the classes which I implemented:

// base-entity.entity.ts
export class BaseEntity {
  @PrimaryGeneratedColumn('uuid')
  id!: string;

  @CreateDateColumn({ name: 'create_date' })
  createDate!: Date;

  @UpdateDateColumn({ name: 'update_date' })
  updateDate!: Date;

  @DeleteDateColumn({ name: 'delete_date' })
  deleteDate?: Date;

  @VersionColumn()
  version!: number;
}

// response-base-entity.dto.ts
export class ResponseBaseEntity {
  id!: string;
}

// base-entity.profile.ts
@Profile()
export class BaseEntityProfile extends ProfileBase {
  constructor(mapper: AutoMapper) {
    super();
    mapper.createMap(BaseEntity, ResponseBaseEntity);
  }
}
// career.entity.ts
@Entity()
export class Career extends BaseEntity {
  name!: string;
}

// response-career.dto.ts
export class ResponseCareerDto extends ResponseBaseEntity {
  name!: string;
}

// career.profile.ts
@Profile()
export class CareerProfile extends ProfileBase {
  constructor(mapper: AutoMapper) {
    super();
    mapper.createMap(Career, ResponseCareerDto, { includeBase: [BaseEntity, ResponseBaseEntity] });
  }
}

All profiles are imported in a module (not the same but doesn't matter).

// nest-cli.json
{
  "language": "ts",
  "collection": "@nestjs/schematics",
  "sourceRoot": "src",
  "compilerOptions": {
    "plugins": [
      {
        "name": "@nartc/automapper-transformer-plugin",
        "options": {
          "modelFileNameSuffix": [".entity.ts", ".dto.ts"]
        }
      }
    ]
  }
}

What is the motivation / use case for changing the behavior?

Plugin should work without need to explicit which properties should detect and map.

Environment


"nestjsx-automapper": "^3.0.23",
"@nartc/automapper-transformer-plugin": "^1.0.20",
 
- Node version: v12.18.3
- Platform:  Windows

Conflict between @Profile decorator and Hot Reload feature of NestJS

The problem appears when HMR is enabled and profiles are imported. Either using the @Profile decorator and importing the class in the respective module or injecting the mapper and adding the profile manually, from time to time the hot reload fails.

The root of the problem is that, in the particular case of using the decorator, a new profile is tried to be imported and fails because there's already one prior to the hot reload. Being unable to change anything with this configuration, I tried to add the profile manually:

@Controller ('careers')
export class CareersController {
  constructor (private readonly careersService: CareersService, @InjectMapper () private readonly mapper: AutoMapper) {
    if (! mapper.getMapping (Career, ResponseCareerDto)) {// <- If profile wasn't already added
      mapper.addProfile (CareerProfile);
    }
  }

  // Rest of request handlers
}

However, the same situation happens again, receiving the error that a profile with the same source and destination was already added. This way, every time that the problem arises I must restart the whole application, which is a real pain.

Is there any way to avoid this situation, perhaps modifying some of the logic in which @Profile works?

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.