forked from mobxjs/mobx
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecorate.ts
More file actions
45 lines (44 loc) · 1.6 KB
/
Copy pathdecorate.ts
File metadata and controls
45 lines (44 loc) · 1.6 KB
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
import { invariant, isPlainObject } from "../internal"
export function decorate<T>(
clazz: new (...args: any[]) => T,
decorators: {
[P in keyof T]?:
| MethodDecorator
| PropertyDecorator
| Array<MethodDecorator>
| Array<PropertyDecorator>
}
): void
export function decorate<T>(
object: T,
decorators: {
[P in keyof T]?:
| MethodDecorator
| PropertyDecorator
| Array<MethodDecorator>
| Array<PropertyDecorator>
}
): T
export function decorate(thing: any, decorators: any) {
process.env.NODE_ENV !== "production" &&
invariant(isPlainObject(decorators), "Decorators should be a key value map")
const target = typeof thing === "function" ? thing.prototype : thing
for (let prop in decorators) {
let propertyDecorators = decorators[prop]
if (!Array.isArray(propertyDecorators)) {
propertyDecorators = [propertyDecorators]
}
process.env.NODE_ENV !== "production" &&
invariant(
propertyDecorators.every(decorator => typeof decorator === "function"),
`Decorate: expected a decorator function or array of decorator functions for '${prop}'`
)
const descriptor = Object.getOwnPropertyDescriptor(target, prop)
const newDescriptor = propertyDecorators.reduce(
(accDescriptor, decorator) => decorator(target, prop, accDescriptor),
descriptor
)
if (newDescriptor) Object.defineProperty(target, prop, newDescriptor)
}
return thing
}