forked from outfoxx/jackson-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
JsonFilter.ts
executable file
·82 lines (79 loc) · 2.54 KB
/
JsonFilter.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/**
* @packageDocumentation
* @module Decorators
*/
import {defineMetadata, makeJacksonDecorator} from '../util';
import {
JsonFilterDecorator,
JsonFilterOptions
} from '../@types';
/**
* {@link JsonFilter} type used to determine whether to serialize property as is, or to filter it out.
*/
export enum JsonFilterType {
/**
* Serialize all properties that are given, and filter out nothing.
*/
SERIALIZE_ALL,
/**
* Serialize all properties except ones includes in {@link JsonStringifierFilterOptions.values}
*/
SERIALIZE_ALL_EXCEPT,
/**
* Filters out all properties except ones includes in {@link JsonStringifierFilterOptions.values}
*/
FILTER_OUT_ALL_EXCEPT
}
/**
* Decorator used to indicate which logical filter is to be used for filtering out properties of type (class) decorated.
* Association made by this decorator declaring ids of filters,
* and {@link JsonStringifierContext} providing matching filters by id.
*
* When used for properties (fields, methods), this decorator applies to values:
* so when applied to Iterables and Maps, it will apply to contained values, not the container.
*
* @example
* ```typescript
* @JsonFilter({value: 'studentFilter'})
* class Student {
* @JsonProperty({value: 'stdName'}) @JsonClassType({type: () => [String]})
* name: string;
* @JsonProperty() @JsonClassType({type: () => [Number]})
* age: number;
* @JsonProperty() @JsonClassType({type: () => [String]})
* college: string;
* @JsonProperty() @JsonClassType({type: () => [String]})
* city: string;
*
* constructor(name: string, age: number, college: string, city: string) {
* this.name = name;
* this.age = age;
* this.college = college;
* this.city = city;
* }
* }
* const student = new Student('Mohit', 30, 'ABCD', 'Varanasi');
*
* const objectMapper = new ObjectMapper();
*
* const jsonData = objectMapper.stringify<Student>(student, {
* filters: {
* studentFilter: {
* type: JsonFilterType.SERIALIZE_ALL_EXCEPT,
* values: ['stdName', 'city']
* }
* }
* });
* ```
*/
export const JsonFilter: JsonFilterDecorator = makeJacksonDecorator(
(o: JsonFilterOptions): JsonFilterOptions => ({enabled: true, ...o }),
(options: JsonFilterOptions, target, propertyKey, descriptorOrParamIndex) => {
if (descriptorOrParamIndex == null && propertyKey == null) {
defineMetadata('JsonFilter', options, target);
return target;
}
if (propertyKey != null) {
defineMetadata('JsonFilter', options, target.constructor, propertyKey);
}
});