-
Notifications
You must be signed in to change notification settings - Fork 306
Expand file tree
/
Copy pathclient.ts
More file actions
153 lines (129 loc) · 4.45 KB
/
client.ts
File metadata and controls
153 lines (129 loc) · 4.45 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
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
// eslint-disable-next-line no-restricted-syntax
import { createHash } from 'crypto'
import type { ModifiedResponse } from '@segment/actions-core'
import { RequestClient, IntegrationError } from '@segment/actions-core'
import { Payload } from './generated-types'
import { AudienceSettings, Settings } from '../generated-types'
import { TABOOLA_API_VERSION } from '../versioning-info'
interface ClusterItem {
user_id: string
type: string
is_hashed: boolean
}
type Cluster = { cluster: ClusterItem[] } | null
interface TaboolaPayload {
operation: 'ADD' | 'REMOVE'
audience_id: number
identities: Cluster[]
integration_source?: string
}
interface RefreshTokenResponse {
access_token: string
}
export class TaboolaClient {
request: RequestClient
payloads: Payload[]
audienceSettings?: AudienceSettings
constructor(request: RequestClient, payloads: Payload[], audienceSettings?: AudienceSettings) {
this.request = request
this.payloads = payloads
this.audienceSettings = audienceSettings
if (!this.audienceSettings) {
throw new IntegrationError('Bad Request: no audienceSettings found.', 'INVALID_REQUEST_DATA', 400)
}
if (!this.audienceSettings.account_id) {
throw new IntegrationError('Bad Request: no audienceSettings.account_id found.', 'INVALID_REQUEST_DATA', 400)
}
}
static async refreshAccessToken(request: RequestClient, settings: Settings) {
const res = await request<RefreshTokenResponse>('https://backstage.taboola.com/backstage/oauth/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: String(
new URLSearchParams({
client_id: settings.client_id,
client_secret: settings.client_secret,
grant_type: 'client_credentials'
})
)
})
return { accessToken: res.data.access_token }
}
async sendToTaboola() {
this.payloads.forEach((payload) => {
payload.action = payload.traits_or_props[payload.segment_computation_key] ? 'ADD' : 'REMOVE'
})
const actionMap = new Map<string, Map<string, Payload[]>>()
this.payloads.forEach((payload) => {
if (!actionMap.has(payload.action as string)) {
actionMap.set(payload.action as string, new Map<string, Payload[]>())
}
const audienceMap = actionMap.get(payload.action as string) as Map<string, Payload[]>
if (!audienceMap.has(payload.external_audience_id)) {
audienceMap.set(payload.external_audience_id, [])
}
audienceMap.get(payload.external_audience_id)?.push(payload)
})
const taboolaRequests: Promise<ModifiedResponse<Response>>[] = []
actionMap.forEach((audienceMap, action) => {
audienceMap.forEach((payloads, external_audience_id) => {
const identities = payloads.map((payload) => this.createCluster(payload)).filter((cluster) => cluster !== null)
if (identities.length > 0) {
taboolaRequests.push(
this.request(
`https://backstage.taboola.com/backstage/api/${TABOOLA_API_VERSION}/${
this.audienceSettings?.account_id as string
}/audience_onboarding`,
{
method: 'POST',
json: {
operation: action as 'ADD' | 'REMOVE',
audience_id: Number(external_audience_id),
identities,
integration_source: 'segment.com'
} as TaboolaPayload
}
)
)
}
})
})
if (taboolaRequests.length === 0) {
throw new IntegrationError('No valid payloads found to sync.', 'INVALID_REQUEST_DATA', 400)
}
return await Promise.all(taboolaRequests)
}
hashEmail(email: string): string {
const sha256HashedRegex = /^[a-f0-9]{64}$/i
const isSHA256Hash = sha256HashedRegex.test(email)
if (!isSHA256Hash) {
email = createHash('sha256').update(email).digest('hex')
}
return email
}
createCluster(payload: Payload): Cluster {
if (!payload.user_email && !payload.device_id) {
return null
}
let email = payload.user_email
const cluster = []
if (email) {
email = this.hashEmail(email)
cluster.push({
user_id: email,
type: 'EMAIL_ID',
is_hashed: true
})
}
if (payload.device_id) {
cluster.push({
user_id: payload.device_id,
type: 'DEVICE_ID',
is_hashed: false
})
}
return { cluster }
}
}