forked from mobxjs/serializr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
serializeAll.ts
83 lines (82 loc) · 2.53 KB
/
serializeAll.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
83
import { invariant, isPropSchema } from "../utils/utils"
import createModelSchema from "../api/createModelSchema"
import getDefaultModelSchema from "../api/getDefaultModelSchema"
import setDefaultModelSchema from "../api/setDefaultModelSchema"
import object from "../types/object"
import { Clazz, ModelSchema, PropDef } from "../api/types"
import { _defaultPrimitiveProp } from "../constants"
/**
* The `serializeAll` decorator can used on a class to signal that all primitive properties,
* or complex properties with a name matching a `pattern`, should be serialized automatically.
*
* @example
* \@serializeAll
* class Store {
* a = 3
* b
* }
*
* const store = new Store()
* store.c = 5
* store.d = {}
* serialize(store) // { "c": 5 }
*
* @example
* class DataType {
* \@serializable
* x
* \@serializable
* y
* }
*
* \@serializeAll(/^[a-z]$/, DataType)
* class ComplexStore {
* }
*
* const store = new ComplexStore()
* store.a = {x: 1, y: 2}
* store.b = {}
* store.somethingElse = 5
* serialize(store) // { a: {x: 1, y: 2}, b: { x: undefined, y: undefined } }
*/
export default function serializeAll<T>(clazz: Clazz<T>): Clazz<T>
export default function serializeAll(
pattern: RegExp,
propertyType: PropDef | Clazz<any>
): (clazz: Clazz<any>) => Clazz<any>
export default function serializeAll(
targetOrPattern: Clazz<any> | RegExp,
propertyType?: PropDef | Clazz<any>
) {
let propSchema: PropDef
if (arguments.length === 1) {
propSchema = true
return decorator(targetOrPattern as Clazz<any>)
} else {
invariant(
typeof targetOrPattern === "object" && targetOrPattern.test,
"@serializeAll pattern doesn't have test"
)
if (typeof propertyType === "function") {
propertyType = object(propertyType)
}
if (true === propertyType) {
propertyType = _defaultPrimitiveProp
}
invariant(isPropSchema(propertyType), "couldn't resolve schema")
propSchema = Object.assign({}, propertyType, {
pattern: targetOrPattern
})
}
function decorator(target: Clazz<any>) {
invariant(typeof target === "function", "@serializeAll can only be used as class decorator")
let info: ModelSchema<any> | undefined = getDefaultModelSchema(target)
if (!info) {
info = createModelSchema(target, {})
setDefaultModelSchema(target, info)
}
info.props["*"] = propSchema
return target
}
return decorator
}