forked from outfoxx/jackson-js
/
JsonAnySetter.ts
executable file
·50 lines (48 loc) · 1.95 KB
/
JsonAnySetter.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
/**
* @packageDocumentation
* @module Decorators
*/
import {defineMetadata, hasMetadata, makeJacksonDecorator} from '../util';
import {JsonAnySetterDecorator, JsonAnySetterOptions} from '../@types';
import {JacksonError} from '../core/JacksonError';
/**
* Decorator that can be used to define a logical "any setter" mutator using non-static two-argument method
* (first argument name of property, second value to set) to be used as a "fallback" handler
* for all otherwise unrecognized properties found from JSON content.
*
* If used, all otherwise unmapped key-value pairs from JSON Object values are added using mutator.
*
* As with {@link JsonAnyGetter}, only one property should be decorated with this decorator;
* if multiple methods are decorated, an exception may be thrown.
*
* @example
* ```typescript
* class ScreenInfo {
* @JsonProperty() @JsonClassType({type: () => [String]})
* id: string;
* @JsonProperty() @JsonClassType({type: () => [String]})
* title: string;
* @JsonProperty() @JsonClassType({type: () => [Number]})
* width: number;
* @JsonProperty() @JsonClassType({type: () => [Number]})
* height: number;
* @JsonProperty() @JsonClassType({type: () => [Map, [String, Object]]})
* otherInfo: Map<string, any> = new Map<string, any>();
*
* @JsonAnySetter()
* public setOtherInfo(propertyKey: string, value: any) {
* this.otherInfo.set(propertyKey, value);
* }
* }
* ```
*/
export const JsonAnySetter: JsonAnySetterDecorator = makeJacksonDecorator(
(o: JsonAnySetterOptions): JsonAnySetterOptions => ({enabled: true, ...o}),
(options: JsonAnySetterOptions, target, propertyKey) => {
if (propertyKey != null) {
if (hasMetadata('JsonAnySetter', target.constructor, null, {withContextGroups: options.contextGroups})) {
throw new JacksonError(`Multiple 'any-setters' defined for "${target.constructor.name}".`);
}
defineMetadata('JsonAnySetter', options, target.constructor);
}
});