Skip to content

Commit

Permalink
fix: make transformers order deterministic
Browse files Browse the repository at this point in the history
When several trasnformers are applied to the same property the order is reversed
every time plainToClass is called.

This fix make the transfomers orders consistent across multiple `plainToClass()`
calls.

Fixes typestack#231
  • Loading branch information
leon19 committed Jul 21, 2020
1 parent eaf5412 commit 0dcc2c1
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/metadata/MetadataStorage.ts
Expand Up @@ -215,7 +215,7 @@ export class MetadataStorage {
}
}
}
return (metadataFromAncestorsTarget).reverse().concat((metadataFromTarget || []).reverse());
return (metadataFromAncestorsTarget).slice().reverse().concat((metadataFromTarget || []).slice().reverse());
}

private getAncestors(target: Function): Function[] {
Expand Down
25 changes: 25 additions & 0 deletions test/functional/transformer-order.spec.ts
@@ -0,0 +1,25 @@
import "reflect-metadata";
import { classToPlain, plainToClass } from "../../src/index";
import { defaultMetadataStorage } from "../../src/storage";
import { Exclude, Expose, Transform } from "../../src/decorators";

describe("applying several transformations", () => {
it("should keep the order of the applied decorators after several plainToClass() calls", () => {
class User {
@Transform(() => "Jonathan")
@Transform(() => "John")
@Expose()
name: string;
}

const firstUser = plainToClass(User, { name: "Joe" });
expect(firstUser.name).toEqual("John");

// Prior to this pull request [#355](https://github.com/typestack/class-transformer/pull/355)
// the order of the transformations was reversed after every `plainToClass()` call
// So after consecutive calls `User#name` would be "John" - "Jonathan" - "John" - "Jonathan"...
// This test ensures the last transformation is always the last one to be applied
const secondUser = plainToClass(User, { name: "Joe" });
expect(secondUser.name).toEqual("John");
});
});

0 comments on commit 0dcc2c1

Please sign in to comment.