-
Notifications
You must be signed in to change notification settings - Fork 78
/
Copy pathsegment.ts
88 lines (72 loc) · 2.28 KB
/
segment.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
import { StreamChat } from './client';
import {
DefaultGenerics,
ExtendableGenerics,
QuerySegmentTargetsFilter,
SegmentData,
SegmentResponse,
SortParam,
} from './types';
type SegmentType = 'user' | 'channel';
type SegmentUpdatableFields = {
description?: string;
filter?: {};
name?: string;
};
export class Segment<StreamChatGenerics extends ExtendableGenerics = DefaultGenerics> {
type: SegmentType;
id: string | null;
client: StreamChat<StreamChatGenerics>;
data?: SegmentData | SegmentResponse;
constructor(client: StreamChat<StreamChatGenerics>, type: SegmentType, id: string | null, data?: SegmentData) {
this.client = client;
this.type = type;
this.id = id;
this.data = data;
}
async create() {
const body = {
name: this.data?.name,
filter: this.data?.filter,
description: this.data?.description,
all_sender_channels: this.data?.all_sender_channels,
all_users: this.data?.all_users,
};
return this.client.createSegment(this.type, this.id, body);
}
verifySegmentId() {
if (!this.id) {
throw new Error(
'Segment id is missing. Either create the segment using segment.create() or set the id during instantiation - const segment = client.segment(id)',
);
}
}
async get() {
this.verifySegmentId();
return this.client.getSegment(this.id as string);
}
async update(data: Partial<SegmentUpdatableFields>) {
this.verifySegmentId();
return this.client.updateSegment(this.id as string, data);
}
async addTargets(targets: string[]) {
this.verifySegmentId();
return this.client.addSegmentTargets(this.id as string, targets);
}
async removeTargets(targets: string[]) {
this.verifySegmentId();
return this.client.removeSegmentTargets(this.id as string, targets);
}
async delete() {
this.verifySegmentId();
return this.client.deleteSegment(this.id as string);
}
async targetExists(targetId: string) {
this.verifySegmentId();
return this.client.segmentTargetExists(this.id as string, targetId);
}
async queryTargets(filter: QuerySegmentTargetsFilter | null = {}, sort: SortParam[] | null | [] = [], options = {}) {
this.verifySegmentId();
return this.client.querySegmentTargets(this.id as string, filter, sort, options);
}
}