Skip to content

Commit

Permalink
fix: incorrect inherit _transformmetadatas nestjs#1224
Browse files Browse the repository at this point in the history
  • Loading branch information
KuanWenChen committed Nov 14, 2023
1 parent d98e446 commit 8bbc2c3
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 2 deletions.
9 changes: 8 additions & 1 deletion lib/type-helpers.utils.ts
Expand Up @@ -151,11 +151,18 @@ function inheritTransformerMetadata(

if (metadataMap.has(targetClass)) {
const existingRules = metadataMap.get(targetClass)!.entries();
// _transformMetadatas is array, should merge not overwrite
const mergeMap = new Map<string, any[]>();
[existingRules, targetMetadataEntries].forEach((entries) => {
for (const [valueKey, value] of entries) {
if (mergeMap.has(valueKey)) {
mergeMap.get(valueKey)!.push(...value);
if (Array.isArray(mergeMap.get(valueKey))) {
mergeMap
.get(valueKey)!
.push(...(Array.isArray(value) ? value : [value])); // merge, if value is not array, transfer to Array
} else {
mergeMap.set(valueKey, value); // overwrite
}
} else {
mergeMap.set(valueKey, value);
}
Expand Down
52 changes: 51 additions & 1 deletion tests/omit-type.helper.spec.ts
@@ -1,4 +1,10 @@
import { instanceToInstance, Transform } from 'class-transformer';
import {
Expose,
instanceToInstance,
plainToInstance,
Transform,
Type,
} from 'class-transformer';
import { MinLength, validate } from 'class-validator';
import { OmitType } from '../lib';
import { getValidationMetadataByTarget } from './type-helpers.test-utils';
Expand Down Expand Up @@ -58,6 +64,50 @@ describe('OmitType', () => {
const transformedDto = instanceToInstance(updateDto);
expect(transformedDto.password).toEqual(password + '_transformed');
});

it('should inherit expose and type transformer metadata', () => {
class Parent {
@Expose()
a!: string | number;

@Expose()
@Type(() => Number)
b!: string | number;
}
class Children extends Parent {
@Expose()
b!: string | number;
c!: string; // not expose

@Type(() => Number)
d!: string | number;
}
class ChildrenOmit extends OmitType(Children, ['a']) {
@Expose()
@Type(() => String)
b!: string;

@Expose()
@Type(() => String)
d!: string;
}

const childrenOmitInstance = plainToInstance(
ChildrenOmit,
{ a: 'a', b: 'b', c: 'c', d: 'd' },
{ excludeExtraneousValues: true },
);

const expectKeySet = new Set(['b', 'd']);
const concreteKeyList = Object.keys(childrenOmitInstance);
for (let i = 0; i < concreteKeyList.length; i++) {
expect(expectKeySet.has(concreteKeyList[i])).toEqual(true);
}
expect(concreteKeyList.length).toEqual(expectKeySet.size);
expect(typeof childrenOmitInstance.b).toEqual('string');
expect(typeof childrenOmitInstance.d).toEqual('string');
expect(childrenOmitInstance.b).toEqual('b');
});
});

describe('Property initializers', () => {
Expand Down

0 comments on commit 8bbc2c3

Please sign in to comment.