/
SDK.ts
512 lines (473 loc) · 14.3 KB
/
SDK.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
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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
import { fetcher } from "../helpers/fetcher";
import { Queue } from "./Queue";
import { Event } from "./Event";
import { EventManager } from "./EventManager";
import { StandardEvents } from "../types/events/StandardEvents";
import { Events } from "../types/events/Events";
import { Currency } from "../types/Currency";
import { SDKResponse } from "../types/SDKResponse";
import { FetchError } from "./FetchError";
import { ActionError } from "./ActionError";
import { PageError } from "./PageError";
import {
PageApi,
PageFolderListResponse,
PagePreviewResponse,
PageResponse,
} from "../types/api/page";
import { generateQueryString } from "../helpers/queryStringHelpers";
import { AcceptedQueryTypes } from "../types/Query";
import { ServerOptions } from "../types/cookieHandling/ServerOptions";
import {
DEFAULT_SESSION_LIFETIME,
SDK_NOT_CONFIGURED_ERROR_MESSAGE,
} from "../constants";
import { CookieManager } from "../types/cookieHandling/CookieManager";
import { dependencyContainer } from "./DependencyContainer";
import { CookieHandler } from "./CookieHandler";
type SDKConfig = {
locale: string;
currency: Currency;
endpoint: string;
useCurrencyInLocale?: boolean;
extensionVersion?: string;
sessionLifetime?: number;
cookieHandlingOverride?: CookieManager;
};
export class SDK<ExtensionEvents extends Events> extends EventManager<
StandardEvents & ExtensionEvents
> {
#hasBeenConfigured;
#endpoint!: string;
#locale!: Intl.Locale;
#currency!: Currency;
#useCurrencyInLocale!: boolean;
#extensionVersion!: string;
#actionQueue: Queue;
#sessionLifetime!: number;
set endpoint(url: string) {
url = this.#normaliseUrl(url);
if (url.indexOf("http") === -1) {
url = `https://${url}`;
// Note the below doesn't support websocket connections but much more work would
// be required for this anyway
console.warn(
`Protocol not supplied to endpoint, defaulting to https - ${url}`
);
}
// remove "/frontastic" if applied
this.#endpoint = url.split("/frontastic")[0];
}
/**
* The full url endpoint to be called, to be set within the {@link configure} method.
*/
get endpoint() {
return this.#endpoint;
}
set locale(locale: string) {
this.#locale = new Intl.Locale(locale);
}
/**
* The string representing the combination of the ISO 639-1 language and ISO 3166-1 country code, to be set within the {@link configure} method.
*/
get locale(): Intl.BCP47LanguageTag {
return this.#locale.baseName;
}
/**
* @deprecated The string representing the locale in the posix format to be used internally.
*/
get posixLocale(): string {
const apiFormattedLocale = this.locale.slice(0, 5).replace("-", "_");
if (this.#useCurrencyInLocale) {
return `${apiFormattedLocale}@${this.currency}`;
} else {
return apiFormattedLocale;
}
}
/**
* The string representing the locale formatted to be used when communicating with the backend.
*/
private get apiHubLocale(): string {
const apiFormattedLocale = this.locale.replace("-", "_");
if (this.#useCurrencyInLocale) {
return `${apiFormattedLocale}@${this.currency}`;
} else {
return apiFormattedLocale;
}
}
set currency(currency: Currency) {
this.#currency = currency;
}
/**
* The string representing the ISO 3-Letter Currency Code, to be set within the {@link configure} method.
*/
get currency() {
return this.#currency;
}
constructor() {
super();
this.#hasBeenConfigured = false;
this.#actionQueue = new Queue();
}
#throwIfNotConfigured() {
if (!this.#hasBeenConfigured) {
throw new Error(SDK_NOT_CONFIGURED_ERROR_MESSAGE);
}
}
#normaliseUrl = (url: string): string =>
url.split("//").reduce((previous, current) => {
if (current === "http:" || current === "https:") {
return (current += "/");
}
return `${previous}/${current}`;
}, "");
/**
* The method that must be called prior to any other methods to configure the connection to the backend. An error is throw if not called prior.
*
* @param {string} config.locale - A string representing the combination of the ISO 639-1 language and ISO 3166-1 country code. For example "en-DE" or "en_DE".
* @param {string} config.currency - A string representing the ISO 3-Letter Currency Code, for example EUR.
* @param {string} config.endpoint - A string representing the full URL of the endpoint to be called.
* @param {boolean} [config.useCurrencyInLocale=false] - An optional boolean, default false. To be set to true if currency is required in config.locale, for example en-GB@EUR.
* @param {string} [config.extensionVersion=""] - An optional string required for multitenancy projects, stored in the environment variable process.env.NEXT_PUBLIC_EXT_BUILD_ID to specify the extension version in which to connect.
* @param {string} [config.sessionLifetime=7776000000] - An optional number of milliseconds in which to persist the session lifeTime, to override the {@link DEFAULT_SESSION_LIFETIME} of 3 months.
* @param {CookieManager} [config.cookieHandlingOverride] - An optional cookie manager interface that contains all the cookie handling methods.
*
* @returns {void} Void.
*/
configure(config: SDKConfig) {
dependencyContainer().configure(
config.cookieHandlingOverride ?? new CookieHandler()
);
this.endpoint = config.endpoint;
this.configureLocale(config);
this.#useCurrencyInLocale = config.useCurrencyInLocale ?? false;
this.#extensionVersion = config.extensionVersion ?? "";
this.#sessionLifetime =
config.sessionLifetime ?? DEFAULT_SESSION_LIFETIME;
this.#hasBeenConfigured = true;
}
/**
* The method called to standardise the locale and currency inputs.
*
* @param {string} config.locale - A string representing the combination of the ISO 639-1 language and ISO 3166-1 country code. For example en-GB or en_GB.
* @param {string} config.currency - A string representing the ISO 3-Letter Currency Code, for example EUR.
*
* @returns {void} Void.
*/
configureLocale(config: Pick<SDKConfig, "locale" | "currency">) {
// currency present in locale (posix modifier)
const [locale, currency] = config.locale.split("@");
if (currency) {
this.currency = currency as Currency;
}
// explicitly defined currency overrides that
if (config.currency) {
this.currency = config.currency as Currency;
}
this.locale = locale.replace(/_/g, "-");
// set language, country
// const [language, country] = locale.split("-")
// this.country = country;
// this.language = language;
}
#triggerError(
error: ActionError | PageError,
frontasticRequestId?: string
) {
this.trigger(
// @ts-ignore
new Event({
eventName: "errorCaught",
data: {
frontasticRequestId,
error: error,
},
})
);
}
#handleError(
options:
| {
type: "ActionError";
frontasticRequestId?: string;
error: string | Error;
actionName: string;
}
| {
type: "PageError";
frontasticRequestId?: string;
error: string | Error;
path: string;
}
): {
isError: true;
tracing: {
frontasticRequestId?: string;
};
error: FetchError;
} {
let error: FetchError;
if (options.error instanceof FetchError) {
error = options.error;
} else {
error = new FetchError(<string | Error>options.error);
}
this.#triggerError(
options.type === "ActionError"
? new ActionError(options.actionName, error)
: new PageError(options.path, error),
options.frontasticRequestId
);
return {
isError: true,
tracing: {
frontasticRequestId: options.frontasticRequestId,
},
error: error,
};
}
#getDefaultAPIHeaders() {
return {
"Frontastic-Locale": this.apiHubLocale,
"Frontastic-Currency": this.currency,
...(this.#extensionVersion
? {
"Commercetools-Frontend-Extension-Version":
this.#extensionVersion,
}
: {}),
};
}
/**
* The method used to call extension actions.
*
* @param {string} options.actionName - The name of the action corresponding to the location of the extension, for example "product/getProduct".
* @param {unknown} [options.payload] - An optional key, value pair object payload to be serialised into the body of the request.
* @param {Object.<string, number, boolean, string[], number[], boolean[]>} [options.query] - An optional key, value pair object to be serialised into the url query.
* @param {boolean} [options.skipQueue] - An optional boolean, default false indicating whether or not to skip the action queue and execute fully asyncronously. May cause race conditions if used incorrectly.
* @param {Object} [options.serverOptions] - An optional object containing the res and req objects for ServerResponse and IncomingMessage with cookies respectively. Required for server-side rendering session management.
*
* @returns {PromiseLike<Object>} An object with a boolean isError property, and either an error or data property for true and false respectively. Type of data will match generic argument supplied to method.
*/
async callAction<ReturnData>(options: {
actionName: string;
payload?: unknown;
query?: AcceptedQueryTypes;
skipQueue?: boolean;
serverOptions?: ServerOptions;
}): Promise<SDKResponse<ReturnData>> {
this.#throwIfNotConfigured();
options.payload = options.payload ?? {};
const params = options.query ? generateQueryString(options.query) : "";
const fetcherOptions = {
method: "POST",
body: JSON.stringify(options.payload),
headers: this.#getDefaultAPIHeaders(),
};
let response: {
frontasticRequestId: string;
data: FetchError | ReturnData;
};
const action = () =>
fetcher<ReturnData>(
this.#normaliseUrl(
`${this.#endpoint}/frontastic/action/${
options.actionName
}${params}`
),
fetcherOptions,
options.serverOptions,
this.#sessionLifetime
);
try {
if (options.skipQueue) {
response = await action();
} else {
response = await this.#actionQueue.add<ReturnData | FetchError>(
action
);
}
} catch (error) {
return this.#handleError({
type: "ActionError",
frontasticRequestId: "",
error: <string | Error>error,
actionName: options.actionName,
});
}
if (response.data instanceof Error) {
return this.#handleError({
type: "ActionError",
frontasticRequestId: response.frontasticRequestId,
error: <string | Error>response.data.toString(),
actionName: options.actionName,
});
}
return {
isError: false,
tracing: {
frontasticRequestId: response.frontasticRequestId,
},
data: <ReturnData>response.data,
};
}
/**
* The domain to call page methods on the API hub.
*/
page: PageApi = {
getPage: async (options: {
path: string;
query?: AcceptedQueryTypes;
serverOptions?: ServerOptions;
}) => {
this.#throwIfNotConfigured();
const params = options.query
? generateQueryString(options.query)
: "";
const fetcherOptions = {
method: "POST",
headers: {
"Frontastic-Path": options.path,
...this.#getDefaultAPIHeaders(),
},
};
let response: {
frontasticRequestId: string;
data: FetchError | PageResponse;
};
try {
response = await fetcher<PageResponse>(
this.#normaliseUrl(
`${this.#endpoint}/frontastic/page${params}`
),
fetcherOptions,
options.serverOptions,
this.#sessionLifetime
);
} catch (error) {
return this.#handleError({
type: "PageError",
frontasticRequestId: "",
error: <string | Error>error,
path: options.path,
});
}
if (response.data instanceof Error) {
return this.#handleError({
type: "PageError",
frontasticRequestId: response.frontasticRequestId,
error: <string | Error>response.data.toString(),
path: options.path,
});
}
return {
isError: false,
tracing: {
frontasticRequestId: response.frontasticRequestId,
},
data: <PageResponse>response.data,
};
},
getPreview: async (options: {
previewId: string;
serverOptions?: ServerOptions;
}) => {
this.#throwIfNotConfigured();
const fetcherOptions = {
method: "POST",
headers: this.#getDefaultAPIHeaders(),
};
let response: {
frontasticRequestId: string;
data: FetchError | PagePreviewResponse;
};
const path = `/preview?previewId=${options.previewId}&locale=${this.apiHubLocale}`;
try {
response = await fetcher<PagePreviewResponse>(
this.#normaliseUrl(`${this.#endpoint}/frontastic${path}`),
fetcherOptions,
options.serverOptions,
this.#sessionLifetime
);
} catch (error) {
return this.#handleError({
type: "PageError",
frontasticRequestId: "",
error: <string | Error>error,
path: path,
});
}
if (response.data instanceof Error) {
return this.#handleError({
type: "PageError",
frontasticRequestId: response.frontasticRequestId,
error: <string | Error>response.data.toString(),
path: path,
});
}
return {
isError: false,
tracing: {
frontasticRequestId: response.frontasticRequestId,
},
data: <PagePreviewResponse>response.data,
};
},
getPages: async (
options: {
path?: string;
depth?: number;
types?: "static";
serverOptions?: ServerOptions;
} = {
depth: 16,
types: "static",
}
) => {
this.#throwIfNotConfigured();
options.depth = options.depth ?? 16;
options.types = options.types ?? "static";
const fetcherOptions = {
method: "POST",
headers: this.#getDefaultAPIHeaders(),
};
let response: {
frontasticRequestId: string;
data: FetchError | PageFolderListResponse;
};
const path = `/structure?locale=${this.apiHubLocale}${
options.path ? `&path=${options.path}` : ""
}&depth=${options.depth}`;
try {
response = await fetcher<PageFolderListResponse>(
this.#normaliseUrl(`${this.#endpoint}/frontastic${path}`),
fetcherOptions,
options.serverOptions,
this.#sessionLifetime
);
} catch (error) {
return this.#handleError({
type: "PageError",
frontasticRequestId: "",
error: <string | Error>error,
path: path,
});
}
if (response.data instanceof Error) {
return this.#handleError({
type: "PageError",
frontasticRequestId: response.frontasticRequestId,
error: <string | Error>response.data.toString(),
path: path,
});
}
return {
isError: false,
tracing: {
frontasticRequestId: response.frontasticRequestId,
},
data: <PageFolderListResponse>response.data,
};
},
};
}