-
Notifications
You must be signed in to change notification settings - Fork 58
Expand file tree
/
Copy pathidentityApiClient.ts
More file actions
350 lines (299 loc) · 12.8 KB
/
Copy pathidentityApiClient.ts
File metadata and controls
350 lines (299 loc) · 12.8 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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
import Constants, { HTTP_ACCEPTED, HTTP_BAD_REQUEST, HTTP_OK } from './constants';
import {
AsyncUploader,
FetchUploader,
XHRUploader,
IFetchPayload,
} from './uploaders';
import { CACHE_HEADER } from './identity-utils';
import { parseNumber, valueof } from './utils';
import {
IAliasCallback,
IAliasRequest,
IdentityAPIMethod,
IIdentity,
IIdentityAPIRequestData,
} from './identity.interfaces';
import {
IdentityApiData,
MPID,
UserIdentities,
} from '@mparticle/web-sdk';
import {
IdentityCallback,
IdentityResultBody,
IIdentityResponse,
} from './identity-user-interfaces';
import { IMParticleWebSDKInstance } from './mp-instance';
const { HTTPCodes, Messages, IdentityMethods } = Constants;
const { Modify } = IdentityMethods;
export interface IIdentityApiClient {
sendAliasRequest: (
aliasRequest: IAliasRequest,
aliasCallback: IAliasCallback
) => Promise<void>;
sendIdentityRequest: (
identityApiRequest: IIdentityAPIRequestData,
method: IdentityAPIMethod,
callback: IdentityCallback,
originalIdentityApiData: IdentityApiData,
parseIdentityResponse: IIdentity['parseIdentityResponse'],
mpid: MPID,
knownIdentities: UserIdentities
) => Promise<void>;
getUploadUrl: (method: IdentityAPIMethod, mpid: MPID) => string;
getIdentityResponseFromFetch: (
response: Response,
responseBody: IdentityResultBody
) => IIdentityResponse;
getIdentityResponseFromXHR: (response: XMLHttpRequest) => IIdentityResponse;
}
// A successfull Alias request will return a 202 with no body
export interface IAliasResponseBody {}
interface IdentityApiRequestPayload extends IFetchPayload {
headers: {
Accept: string;
'Content-Type': string;
'x-mp-key': string;
};
}
type HTTP_STATUS_CODES = typeof HTTP_OK | typeof HTTP_ACCEPTED;
interface IdentityApiError {
code: string;
message: string;
}
interface IdentityApiErrorResponse {
Errors: IdentityApiError[],
ErrorCode: string,
StatusCode: valueof<HTTP_STATUS_CODES>;
RequestId: string;
}
// All Identity Api Responses have the same structure, except for Alias
interface IAliasErrorResponse extends IdentityApiError {}
export default function IdentityAPIClient(
this: IIdentityApiClient,
mpInstance: IMParticleWebSDKInstance
) {
this.sendAliasRequest = async function(
aliasRequest: IAliasRequest,
aliasCallback: IAliasCallback
) {
const { Logger } = mpInstance;
const { invokeAliasCallback } = mpInstance._Helpers;
const { aliasUrl } = mpInstance._Store.SDKConfig;
const { devToken: apiKey } = mpInstance._Store;
Logger.verbose(Messages.InformationMessages.SendAliasHttp);
// https://go.mparticle.com/work/SQDSDKS-6750
const uploadUrl = `https://${aliasUrl}${apiKey}/Alias`;
const uploader: AsyncUploader = window.fetch
? new FetchUploader(uploadUrl)
: new XHRUploader(uploadUrl);
// https://go.mparticle.com/work/SQDSDKS-6568
const uploadPayload: IFetchPayload = {
method: 'post',
headers: {
Accept: 'text/plain;charset=UTF-8',
'Content-Type': 'application/json',
},
body: JSON.stringify(aliasRequest),
};
try {
const response: Response = await uploader.upload(uploadPayload);
let aliasResponseBody: IAliasResponseBody;
let message: string;
let errorMessage: string;
switch (response.status) {
// A successfull Alias request will return without a body
case HTTP_ACCEPTED:
case HTTP_OK:
// https://go.mparticle.com/work/SQDSDKS-6670
message = 'Received Alias Response from server: ' + JSON.stringify(response.status);
break;
// Our Alias Request API will 400 if there is an issue with the request body (ie timestamps are too far
// in the past or MPIDs don't exist).
// A 400 will return an error in the response body and will go through the happy path to report the error
case HTTP_BAD_REQUEST:
// response.json will always exist on a fetch, but can only be await-ed when the
// response is not empty, otherwise it will throw an error.
if (response.json) {
try {
aliasResponseBody = await response.json();
} catch (e) {
Logger.verbose('The request has no response body');
}
} else {
// https://go.mparticle.com/work/SQDSDKS-6568
// XHRUploader returns the response as a string that we need to parse
const xhrResponse = (response as unknown) as XMLHttpRequest;
aliasResponseBody = xhrResponse.responseText
? JSON.parse(xhrResponse.responseText)
: '';
}
const errorResponse: IAliasErrorResponse = aliasResponseBody as unknown as IAliasErrorResponse;
if (errorResponse?.message) {
errorMessage = errorResponse.message;
}
message =
'Issue with sending Alias Request to mParticle Servers, received HTTP Code of ' +
response.status;
if (errorResponse?.code) {
message += ' - ' + errorResponse.code;
}
break;
// Any unhandled errors, such as 500 or 429, will be caught here as well
default: {
throw new Error('Received HTTP Code of ' + response.status);
}
}
Logger.verbose(message);
invokeAliasCallback(aliasCallback, response.status, errorMessage);
} catch (e) {
const errorMessage = (e as Error).message || e.toString();
Logger.error('Error sending alias request to mParticle servers. ' + errorMessage);
invokeAliasCallback(
aliasCallback,
HTTPCodes.noHttpCoverage,
errorMessage,
);
}
};
this.sendIdentityRequest = async function(
identityApiRequest: IIdentityAPIRequestData,
method: IdentityAPIMethod,
callback: IdentityCallback,
originalIdentityApiData: IdentityApiData,
parseIdentityResponse: IIdentity['parseIdentityResponse'],
mpid: MPID,
knownIdentities: UserIdentities
) {
const { invokeCallback } = mpInstance._Helpers;
const { Logger } = mpInstance;
Logger.verbose(Messages.InformationMessages.SendIdentityBegin);
if (!identityApiRequest) {
Logger.error(Messages.ErrorMessages.APIRequestEmpty);
return;
}
Logger.verbose(Messages.InformationMessages.SendIdentityHttp);
if (mpInstance._Store.identityCallInFlight) {
invokeCallback(
callback,
HTTPCodes.activeIdentityRequest,
'There is currently an Identity request processing. Please wait for this to return before requesting again'
);
return;
}
const previousMPID = mpid || null;
const uploadUrl = this.getUploadUrl(method, mpid);
const uploader: AsyncUploader = window.fetch
? new FetchUploader(uploadUrl)
: new XHRUploader(uploadUrl);
// https://go.mparticle.com/work/SQDSDKS-6568
const fetchPayload: IdentityApiRequestPayload = {
method: 'post',
headers: {
Accept: 'text/plain;charset=UTF-8',
'Content-Type': 'application/json',
'x-mp-key': mpInstance._Store.devToken,
},
body: JSON.stringify(identityApiRequest),
};
mpInstance._Store.identityCallInFlight = true;
try {
const response: Response = await uploader.upload(fetchPayload);
let identityResponse: IIdentityResponse;
let message: string;
switch (response.status) {
case HTTP_ACCEPTED:
case HTTP_OK:
// Our Identity API will return a 400 error if there is an issue with the requeest body
// such as if the body is empty or one of the attributes is missing or malformed
// A 400 will return an error in the response body and will go through the happy path to report the error
case HTTP_BAD_REQUEST:
// FetchUploader returns the response as a JSON object that we have to await
if (response.json) {
// https://go.mparticle.com/work/SQDSDKS-6568
// FetchUploader returns the response as a JSON object that we have to await
const responseBody: IdentityResultBody = await response.json();
identityResponse = this.getIdentityResponseFromFetch(
response,
responseBody
);
} else {
identityResponse = this.getIdentityResponseFromXHR(
(response as unknown) as XMLHttpRequest
);
}
if (identityResponse.status === HTTP_BAD_REQUEST) {
const errorResponse: IdentityApiErrorResponse = identityResponse.responseText as unknown as IdentityApiErrorResponse;
message = 'Issue with sending Identity Request to mParticle Servers, received HTTP Code of ' + identityResponse.status;
if (errorResponse?.Errors) {
const errorMessage = errorResponse.Errors.map((error) => error.message).join(', ');
message += ' - ' + errorMessage;
}
} else {
message = 'Received Identity Response from server: ';
message += JSON.stringify(identityResponse.responseText);
}
break;
// Our Identity API will return:
// - 401 if the `x-mp-key` is incorrect or missing
// - 403 if the there is a permission or account issue related to the `x-mp-key`
// 401 and 403 have no response bodies and should be rejected outright
default: {
throw new Error('Received HTTP Code of ' + response.status);
}
}
mpInstance._Store.identityCallInFlight = false;
Logger.verbose(message);
parseIdentityResponse(
identityResponse,
previousMPID,
callback,
originalIdentityApiData,
method,
knownIdentities,
false
);
} catch (err) {
mpInstance._Store.identityCallInFlight = false;
const errorMessage = (err as Error).message || err.toString();
Logger.error('Error sending identity request to servers' + ' - ' + errorMessage);
invokeCallback(
callback,
HTTPCodes.noHttpCoverage,
errorMessage,
);
}
};
this.getUploadUrl = (method: IdentityAPIMethod, mpid: MPID) => {
const uploadServiceUrl: string = mpInstance._Helpers.createServiceUrl(
mpInstance._Store.SDKConfig.identityUrl
);
const uploadUrl: string =
method === Modify
? uploadServiceUrl + mpid + '/' + method
: uploadServiceUrl + method;
return uploadUrl;
};
this.getIdentityResponseFromFetch = (
response: Response,
responseBody: IdentityResultBody
): IIdentityResponse => ({
status: response.status,
responseText: responseBody,
cacheMaxAge: parseInt(response.headers.get(CACHE_HEADER)) || 0,
expireTimestamp: 0,
});
this.getIdentityResponseFromXHR = (
response: XMLHttpRequest
): IIdentityResponse => ({
status: response.status,
responseText: response.responseText
? JSON.parse(response.responseText)
: {},
cacheMaxAge: parseNumber(
response.getResponseHeader(CACHE_HEADER) || ''
),
expireTimestamp: 0,
});
}