Skip to content

Commit 2592c17

Browse files
committed
feat(JsonView): add JsonView decorator to expose object properties
1 parent 48a6ef2 commit 2592c17

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

src/decorators.ts

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { ClassTransformer } from './ClassTransformer';
12
import {defaultMetadataStorage} from "./storage";
23
import {TypeMetadata} from "./metadata/TypeMetadata";
34
import {ExposeMetadata} from "./metadata/ExposeMetadata";
@@ -48,4 +49,30 @@ export function Exclude(options?: ExcludeOptions) {
4849
const metadata = new ExcludeMetadata(object instanceof Function ? object : object.constructor, propertyName, options || {});
4950
defaultMetadataStorage.addExcludeMetadata(metadata);
5051
};
52+
}
53+
54+
/**
55+
* Return the object with the exposed properties only.
56+
*/
57+
export function JsonView(params: {}, method?: string): Function {
58+
59+
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
60+
const classTransformer: any = new ClassTransformer();
61+
const originalMethod = descriptor.value;
62+
63+
descriptor.value = function(...args: any[]) {
64+
let result: any = originalMethod.apply(this, args);
65+
66+
let transformer: Function;
67+
if (typeof method === 'string' && method) {
68+
transformer = classTransformer[method];
69+
}
70+
else {
71+
transformer = classTransformer.classToPlain;
72+
}
73+
74+
result = transformer(result, params);
75+
return result;
76+
}
77+
}
5178
}

0 commit comments

Comments
 (0)