forked from adobecom/milo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wcs.js
203 lines (195 loc) · 7.37 KB
/
wcs.js
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
import {
ERROR_MESSAGE_BAD_REQUEST,
ERROR_MESSAGE_OFFER_NOT_FOUND,
} from './constants.js';
import {
Env,
WcsCommitment,
WcsPlanType,
WcsTerm,
applyPlanType,
} from './external.js';
import { Log } from './log.js';
/**
* @typedef {Map<string, {
* resolve: (offers: Commerce.Wcs.Offer[]) => void,
* reject: (reason: Error) => void
* }>} WcsPromises
*/
/**
* @param {{ settings: Commerce.Wcs.Settings }} params
* @returns {Commerce.Wcs.Client}
*/
export function Wcs({ settings }) {
const log = Log.module('wcs');
const { env, wcsApiKey: apiKey } = settings;
/**
* Cache of promises resolving to arrays of Wcs offers grouped by osi-based keys.
* @type {Map<string, Promise<Commerce.Wcs.Offer[]>>}
*/
const cache = new Map();
/**
* Queue of pending requests to Wcs grouped by locale and promo.
* @type {Map<string, { options, promises: WcsPromises }>}
*/
const queue = new Map();
let timer;
/**
* Accepts list of OSIs having same locale and map of pending promises, grouped by OSI.
* Sends one or more requests to WCS endpoint to provide required offers.
* Resolves each pending promise with array of provided offers.
* If WCS does not provide an offer for particular osi,
* its pending promise will be rejected with "not found".
* In case of any other Wcs/Network error, promises are rejected with "bad request".
* @param options
* @param {WcsPromises} promises
* @param reject - used for recursion, prevents rejection of promises with missing offers
*/
async function resolveWcsOffers(options, promises, reject = true) {
let message = ERROR_MESSAGE_OFFER_NOT_FOUND;
log.debug('Fetching:', options);
try {
options.offerSelectorIds = options.offerSelectorIds.sort();
const url = new URL(settings.wcsURL);
url.searchParams.set('offer_selector_ids', options.offerSelectorIds.join(','));
url.searchParams.set('country', options.country);
url.searchParams.set('locale', options.locale);
url.searchParams.set('landscape', env === Env.STAGE ? 'ALL' : settings.landscape);
url.searchParams.set('api_key', apiKey);
// language can be undefined if its a UK offer
if (options.language) {
url.searchParams.set('language', options.language);
}
if (options.promotionCode) {
url.searchParams.set('promotion_code', options.promotionCode);
}
if (options.currency) {
url.searchParams.set('currency', options.currency);
}
const response = await fetch(url.toString(), {
credentials: 'omit'
});
if (response.ok) {
const data = await response.json();
log.debug('Fetched:', options, data);
let offers = data.resolvedOffers ?? [];
offers = offers.map(applyPlanType);
// resolve all promises that have offers
promises.forEach(({ resolve }, offerSelectorId) => {
// select offers with current OSI
const resolved = offers
.filter(({ offerSelectorIds }) =>
offerSelectorIds.includes(offerSelectorId),
)
.flat();
// resolve current promise if at least 1 offer is present
if (resolved.length) {
promises.delete(offerSelectorId);
resolve(resolved);
}
});
}
// in case of 404 WCS error caused by a request with multiple osis,
// fallback to `fetch-by-one` strategy
else if (response.status === 404 && options.offerSelectorIds.length > 1) {
log.debug('Multi-osi 404, fallback to fetch-by-one strategy');
await Promise.allSettled(
options.offerSelectorIds.map((offerSelectorId) =>
resolveWcsOffers(
{ ...options, offerSelectorIds: [offerSelectorId] },
promises,
false, // do not reject promises for missing offers, this will be done below
),
),
);
} else {
message = ERROR_MESSAGE_BAD_REQUEST;
log.error(message, options);
}
} catch (e) {
message = ERROR_MESSAGE_BAD_REQUEST;
log.error(message, options, e);
}
if (reject && promises.size) {
// reject pending promises, their offers weren't provided by WCS
log.debug('Missing:', { offerSelectorIds: [...promises.keys()] });
promises.forEach((promise) => {
promise.reject(new Error(message));
});
}
}
/**
* Trigger resolution of all accumulated promises by requesting their associated OSIs.
*/
function flushQueue() {
clearTimeout(timer);
const pending = [...queue.values()];
queue.clear();
pending.forEach(({ options, promises }) =>
resolveWcsOffers(options, promises),
);
}
function resolveOfferSelectors({
country,
language,
perpetual = false,
promotionCode = '',
wcsOsi = [],
}) {
const locale = `${language}_${country}`;
if (country !== 'GB') language = perpetual ? 'EN' : 'MULT';
const groupKey = [country, language, promotionCode]
.filter((val) => val)
.join('-')
.toLowerCase();
return wcsOsi.map((osi) => {
const cacheKey = `${osi}-${groupKey}`;
if (!cache.has(cacheKey)) {
const promise = new Promise((resolve, reject) => {
let group = queue.get(groupKey);
if (!group) {
const options = {
country,
locale,
offerSelectorIds: [],
};
if (country !== 'GB') options.language = language;
const promises = new Map();
group = { options, promises };
queue.set(groupKey, group);
}
if (promotionCode) {
group.options.promotionCode = promotionCode;
}
group.options.offerSelectorIds.push(osi);
group.promises.set(osi, {
resolve,
reject,
});
if (
group.options.offerSelectorIds.length >=
settings.wcsBufferLimit
) {
flushQueue();
} else {
log.debug('Queued:', group.options);
if (!timer) {
timer = setTimeout(
flushQueue,
settings.wcsBufferDelay,
);
}
}
});
cache.set(cacheKey, promise);
}
return cache.get(cacheKey);
});
}
return {
WcsCommitment,
WcsPlanType,
WcsTerm,
resolveOfferSelectors,
};
}