-
Notifications
You must be signed in to change notification settings - Fork 85
/
context.ts
111 lines (83 loc) · 2.48 KB
/
context.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
import { inspectable } from 'inspectable';
import type { API } from '../../api';
import type { Upload } from '../../upload';
import { type UpdateSource, kSerializeData } from '../../utils/constants';
export type ContextDefaultState = Record<string, any>;
export interface IContextOptions<P, S, Type extends string = string, SubType extends string = string> {
api: API;
upload: Upload;
type: Type;
subTypes: SubType[];
payload: P;
state?: S;
source: UpdateSource;
updateType: string | number;
groupId?: number;
}
export type ContextFactoryOptions<P, S> = Omit<IContextOptions<P, S>, 'type' | 'subTypes'>;
export class Context<
P = object,
S = ContextDefaultState,
Type extends string = string,
SubType extends string = string,
> {
public type: Type;
public subTypes: SubType[];
public state: S;
protected api: API;
protected upload: Upload;
public $groupId?: number;
protected payload: P;
[key: string]: any;
/**
* Constructor
*/
public constructor(options: IContextOptions<P, S, Type, SubType>) {
this.api = options.api;
this.upload = options.upload;
this.type = options.type;
this.subTypes = options.subTypes;
this.payload = options.payload;
this.state = options.state || ({} as S);
this.$groupId = options.groupId;
}
/**
* Returns custom tag
*/
public get [Symbol.toStringTag](): string {
return this.constructor.name;
}
/**
* Checks whether the context of some of these types
*/
public is(rawTypes: (Type | SubType)[]): boolean {
const types = !Array.isArray(rawTypes) ? [rawTypes] : rawTypes;
if (types.includes(this.type)) {
return true;
}
return this.subTypes.some((type): boolean => types.includes(type));
}
/**
* Returns data for JSON
*/
public toJSON(): object {
return {
...this[kSerializeData](),
type: this.type,
subTypes: this.subTypes,
state: this.state,
};
}
/**
* Returns the custom data
*/
public [kSerializeData](): object {
const { api, upload, ...payload } = this;
return payload;
}
}
inspectable(Context, {
serialize: instance => instance.toJSON(),
stringify: (instance, payload, context): string =>
`${context.stylize(instance.constructor.name, 'special')} ${context.inspect(payload)}`,
});