@emilgroup/discount-sdk-node 1.12.1-beta.19 → 1.12.1-beta.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/base.ts CHANGED
@@ -82,6 +82,9 @@ export interface RequestArgs {
82
82
 
83
83
  const NETWORK_ERROR_MESSAGE = "Network Error";
84
84
 
85
+ // Refreshes in flight per configuration (BaseAPI.shareRefresh): SDK objects that share a configuration share its token.
86
+ const refreshesInFlight = new Map<Configuration, Promise<string>>();
87
+
85
88
  /**
86
89
  *
87
90
  * @export
@@ -92,6 +95,29 @@ export class BaseAPI {
92
95
  private username?: string;
93
96
  private password?: string;
94
97
 
98
+ // Marks each request with the account (username) of the SDK object that sent it: only SDK objects of that
99
+ // account refresh and resend it, never an object of another account in the same app.
100
+ private static readonly REQUEST_OWNER = '_emilSdkOwner';
101
+
102
+ private ownAccount(): string {
103
+ return (this.configuration.username || '').toLowerCase();
104
+ }
105
+
106
+ protected withOwner(options?: AxiosRequestConfig): AxiosRequestConfig {
107
+ // An object without a username cannot refresh itself: its requests stay unmarked, as before.
108
+ if (!this.ownAccount()) {
109
+ return { ...options };
110
+ }
111
+ return { ...options, [BaseAPI.REQUEST_OWNER]: this.ownAccount() } as AxiosRequestConfig;
112
+ }
113
+
114
+ // Sent for another account: only that account's SDK objects handle it. Unmarked requests as before.
115
+ private sentByOtherAccount(config?: AxiosRequestConfig): boolean {
116
+ const owner = (config as Record<string, unknown> | undefined)?.[BaseAPI.REQUEST_OWNER];
117
+ return owner !== undefined && owner !== this.ownAccount();
118
+ }
119
+
120
+
95
121
  constructor(configuration?: Configuration, protected basePath: string = BASE_PATH, protected axios: AxiosInstance = globalAxios) {
96
122
  if (configuration) {
97
123
  this.configuration = configuration;
@@ -222,7 +248,8 @@ export class BaseAPI {
222
248
  return '';
223
249
  }
224
250
 
225
- const options: AxiosRequestConfig = {
251
+ // Sent through globalAxios like any call; marked as retried, so a refused refresh is not refreshed again.
252
+ const options = {
226
253
  method: 'POST',
227
254
  url: `${this.configuration.basePath}/authservice/v1/refresh-token`,
228
255
  headers: {
@@ -231,7 +258,8 @@ export class BaseAPI {
231
258
  },
232
259
  data: { username: username },
233
260
  withCredentials: true,
234
- };
261
+ _retry: true,
262
+ } as AxiosRequestConfig;
235
263
 
236
264
  const { data: { accessToken } } = await globalAxios.request<LoginClass>(options);
237
265
 
@@ -252,6 +280,43 @@ export class BaseAPI {
252
280
  return this.configuration;
253
281
  }
254
282
 
283
+ private sharedRefresh(): Promise<string> {
284
+ return BaseAPI.shareRefresh(refreshesInFlight, this.configuration, () => this.refreshTokenInternal());
285
+ }
286
+
287
+ private refreshRunning(): boolean {
288
+ return refreshesInFlight.has(this.configuration);
289
+ }
290
+
291
+ // Joins the refresh already in flight for this key, or starts one: calls refused at the same time wait for
292
+ // one refresh instead of each starting their own (a refresh token may be single-use). The entry is removed
293
+ // when the refresh settles.
294
+ private static shareRefresh<K, T>(inFlight: Map<K, Promise<T>>, key: K, start: () => Promise<T>): Promise<T> {
295
+ const running = inFlight.get(key);
296
+ if (running) {
297
+ return running;
298
+ }
299
+ const refresh = start();
300
+ inFlight.set(key, refresh);
301
+ const settled = () => { inFlight.delete(key); };
302
+ refresh.then(settled, settled);
303
+ return refresh;
304
+ }
305
+
306
+ // A refused call that joins a refresh already running is not a new try: only started refreshes count toward
307
+ // the limit, so every call refused at the same time is retried.
308
+ private mayRefreshAfterNetworkError(): boolean {
309
+ if (this.refreshRunning()) {
310
+ return true;
311
+ }
312
+ if (_retry_count >= 4) {
313
+ return false;
314
+ }
315
+ _retry_count++;
316
+ return true;
317
+ }
318
+
319
+
255
320
  private attachInterceptor(axios: AxiosInstance) {
256
321
  axios.interceptors.response.use(
257
322
  (res) => {
@@ -259,12 +324,15 @@ export class BaseAPI {
259
324
  },
260
325
  async (err) => {
261
326
  let originalConfig = err.config;
327
+ if (this.sentByOtherAccount(originalConfig)) {
328
+ return Promise.reject(err);
329
+ }
262
330
  if (err.response) {
263
331
  // Access Token was expired
264
332
  if (err.response.status === 401 && !originalConfig._retry) {
265
333
  originalConfig._retry = true;
266
334
  try {
267
- const tokenString = await this.refreshTokenInternal();
335
+ const tokenString = await this.sharedRefresh();
268
336
  const accessToken = `Bearer ${tokenString}`;
269
337
 
270
338
  originalConfig.headers['Authorization'] = accessToken;
@@ -284,12 +352,12 @@ export class BaseAPI {
284
352
  }
285
353
  } else if(err.message === NETWORK_ERROR_MESSAGE
286
354
  && err.isAxiosError
355
+ && !originalConfig._retry
287
356
  && originalConfig.headers.hasOwnProperty('Authorization')
288
- && _retry_count < 4
357
+ && this.mayRefreshAfterNetworkError()
289
358
  ){
290
- _retry_count++;
291
359
  try {
292
- const tokenString = await this.refreshTokenInternal();
360
+ const tokenString = await this.sharedRefresh();
293
361
  const accessToken = `Bearer ${tokenString}`;
294
362
 
295
363
  _retry = true;
package/common.ts CHANGED
@@ -131,9 +131,10 @@ export const toPathString = function (url: URL) {
131
131
  * @export
132
132
  */
133
133
  export const createRequestFunction = function (axiosArgs: RequestArgs, globalAxios: AxiosInstance, BASE_PATH: string, configuration?: Configuration) {
134
- return <T = unknown, R = AxiosResponse<T>>(axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => {
134
+ // Typed by hand: since axios 1.20, request() returns an internal axios type that SDK declarations cannot name.
135
+ return <T = unknown, R = AxiosResponse<T>>(axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH): Promise<R> => {
135
136
  const axiosRequestArgs = {...axiosArgs.options, url: (configuration?.basePath || basePath) + axiosArgs.url};
136
- return axios.request<T, R>(axiosRequestArgs);
137
+ return axios.request<T, R>(axiosRequestArgs) as Promise<R>;
137
138
  };
138
139
  }
139
140
 
@@ -714,7 +714,7 @@ export declare class CampaignsApi extends BaseAPI {
714
714
  * @throws {RequiredError}
715
715
  * @memberof CampaignsApi
716
716
  */
717
- createCampaign(requestParameters: CampaignsApiCreateCampaignRequest, options?: AxiosRequestConfig): Promise<import("axios").AxiosResponse<CreateCampaignResponseClass, any, {}>>;
717
+ createCampaign(requestParameters: CampaignsApiCreateCampaignRequest, options?: AxiosRequestConfig): Promise<import("axios").AxiosResponse<CreateCampaignResponseClass, any, {}, any>>;
718
718
  /**
719
719
  * Creates an account that is eligible to redeem a vouchers from a specific campaign.
720
720
  * @summary Create the Eligible Account
@@ -723,7 +723,7 @@ export declare class CampaignsApi extends BaseAPI {
723
723
  * @throws {RequiredError}
724
724
  * @memberof CampaignsApi
725
725
  */
726
- createEligibleAccount(requestParameters: CampaignsApiCreateEligibleAccountRequest, options?: AxiosRequestConfig): Promise<import("axios").AxiosResponse<CreateEligibleAccountResponseClass, any, {}>>;
726
+ createEligibleAccount(requestParameters: CampaignsApiCreateEligibleAccountRequest, options?: AxiosRequestConfig): Promise<import("axios").AxiosResponse<CreateEligibleAccountResponseClass, any, {}, any>>;
727
727
  /**
728
728
  * Removes a campaign and its associated vouchers. This will prevent any further voucher redemptions.
729
729
  * @summary Delete the Campaign
@@ -732,7 +732,7 @@ export declare class CampaignsApi extends BaseAPI {
732
732
  * @throws {RequiredError}
733
733
  * @memberof CampaignsApi
734
734
  */
735
- deleteCampaign(requestParameters: CampaignsApiDeleteCampaignRequest, options?: AxiosRequestConfig): Promise<import("axios").AxiosResponse<void, any, {}>>;
735
+ deleteCampaign(requestParameters: CampaignsApiDeleteCampaignRequest, options?: AxiosRequestConfig): Promise<import("axios").AxiosResponse<void, any, {}, any>>;
736
736
  /**
737
737
  * Removes an eligible account from a campaign. This will prevent the account from using the assigned voucher code for discounts when the campaign is released.
738
738
  * @summary Delete the Eligible Account
@@ -741,7 +741,7 @@ export declare class CampaignsApi extends BaseAPI {
741
741
  * @throws {RequiredError}
742
742
  * @memberof CampaignsApi
743
743
  */
744
- deleteEligibleAccount(requestParameters: CampaignsApiDeleteEligibleAccountRequest, options?: AxiosRequestConfig): Promise<import("axios").AxiosResponse<void, any, {}>>;
744
+ deleteEligibleAccount(requestParameters: CampaignsApiDeleteEligibleAccountRequest, options?: AxiosRequestConfig): Promise<import("axios").AxiosResponse<void, any, {}, any>>;
745
745
  /**
746
746
  * Removes all eligible accounts from a campaign. This will prevent these accounts from using their assigned voucher codes for discounts when the campaign is released.
747
747
  * @summary Delete the Eligible Accounts
@@ -750,7 +750,7 @@ export declare class CampaignsApi extends BaseAPI {
750
750
  * @throws {RequiredError}
751
751
  * @memberof CampaignsApi
752
752
  */
753
- deleteEligibleAccounts(requestParameters: CampaignsApiDeleteEligibleAccountsRequest, options?: AxiosRequestConfig): Promise<import("axios").AxiosResponse<void, any, {}>>;
753
+ deleteEligibleAccounts(requestParameters: CampaignsApiDeleteEligibleAccountsRequest, options?: AxiosRequestConfig): Promise<import("axios").AxiosResponse<void, any, {}, any>>;
754
754
  /**
755
755
  * Retrieves detailed information about a specific campaign.
756
756
  * @summary Retrieve the Campaign
@@ -759,7 +759,7 @@ export declare class CampaignsApi extends BaseAPI {
759
759
  * @throws {RequiredError}
760
760
  * @memberof CampaignsApi
761
761
  */
762
- getCampaign(requestParameters: CampaignsApiGetCampaignRequest, options?: AxiosRequestConfig): Promise<import("axios").AxiosResponse<GetCampaignResponseClass, any, {}>>;
762
+ getCampaign(requestParameters: CampaignsApiGetCampaignRequest, options?: AxiosRequestConfig): Promise<import("axios").AxiosResponse<GetCampaignResponseClass, any, {}, any>>;
763
763
  /**
764
764
  * Retrieves a list of campaigns.
765
765
  * @summary List Campaigns
@@ -768,7 +768,7 @@ export declare class CampaignsApi extends BaseAPI {
768
768
  * @throws {RequiredError}
769
769
  * @memberof CampaignsApi
770
770
  */
771
- listCampaigns(requestParameters?: CampaignsApiListCampaignsRequest, options?: AxiosRequestConfig): Promise<import("axios").AxiosResponse<ListCampaignsResponseClass, any, {}>>;
771
+ listCampaigns(requestParameters?: CampaignsApiListCampaignsRequest, options?: AxiosRequestConfig): Promise<import("axios").AxiosResponse<ListCampaignsResponseClass, any, {}, any>>;
772
772
  /**
773
773
  * Retrieves a list of eligible accounts.
774
774
  * @summary List Eligible Accounts
@@ -777,7 +777,7 @@ export declare class CampaignsApi extends BaseAPI {
777
777
  * @throws {RequiredError}
778
778
  * @memberof CampaignsApi
779
779
  */
780
- listEligibleAccounts(requestParameters?: CampaignsApiListEligibleAccountsRequest, options?: AxiosRequestConfig): Promise<import("axios").AxiosResponse<ListEligibleAccountsResponseClass, any, {}>>;
780
+ listEligibleAccounts(requestParameters?: CampaignsApiListEligibleAccountsRequest, options?: AxiosRequestConfig): Promise<import("axios").AxiosResponse<ListEligibleAccountsResponseClass, any, {}, any>>;
781
781
  /**
782
782
  * Updates the data of an existing campaign. Only DRAFT campaigns can be updated.
783
783
  * @summary Update the Campaign
@@ -786,7 +786,7 @@ export declare class CampaignsApi extends BaseAPI {
786
786
  * @throws {RequiredError}
787
787
  * @memberof CampaignsApi
788
788
  */
789
- updateCampaign(requestParameters: CampaignsApiUpdateCampaignRequest, options?: AxiosRequestConfig): Promise<import("axios").AxiosResponse<UpdateCampaignResponseClass, any, {}>>;
789
+ updateCampaign(requestParameters: CampaignsApiUpdateCampaignRequest, options?: AxiosRequestConfig): Promise<import("axios").AxiosResponse<UpdateCampaignResponseClass, any, {}, any>>;
790
790
  /**
791
791
  * Updates the status of a campaign, which affects whether vouchers can be redeemed.
792
792
  * @summary Updates the status of a campaign.
@@ -795,7 +795,7 @@ export declare class CampaignsApi extends BaseAPI {
795
795
  * @throws {RequiredError}
796
796
  * @memberof CampaignsApi
797
797
  */
798
- updateCampaignStatus(requestParameters: CampaignsApiUpdateCampaignStatusRequest, options?: AxiosRequestConfig): Promise<import("axios").AxiosResponse<void, any, {}>>;
798
+ updateCampaignStatus(requestParameters: CampaignsApiUpdateCampaignStatusRequest, options?: AxiosRequestConfig): Promise<import("axios").AxiosResponse<void, any, {}, any>>;
799
799
  /**
800
800
  * Uploads accounts that are eligible to redeem vouchers from a specific campaign using a CSV file. The CSV file must contain a header row with the following columns: partnerNumber, voucherCode. Separate each column with a comma.
801
801
  * @summary Uploads the eligible accounts.
@@ -804,5 +804,5 @@ export declare class CampaignsApi extends BaseAPI {
804
804
  * @throws {RequiredError}
805
805
  * @memberof CampaignsApi
806
806
  */
807
- uploadEligibleAccounts(requestParameters: CampaignsApiUploadEligibleAccountsRequest, options?: AxiosRequestConfig): Promise<import("axios").AxiosResponse<void, any, {}>>;
807
+ uploadEligibleAccounts(requestParameters: CampaignsApiUploadEligibleAccountsRequest, options?: AxiosRequestConfig): Promise<import("axios").AxiosResponse<void, any, {}, any>>;
808
808
  }