@commercelayer/sdk 6.4.0 → 6.5.0

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/README.md CHANGED
@@ -20,9 +20,12 @@ A JavaScript Library wrapper that makes it quick and easy to interact with the [
20
20
  - [Installation](#installation)
21
21
  - [Authentication](#authentication)
22
22
  - [Import](#import)
23
+ - [Options](#options)
23
24
  - [SDK usage](#sdk-usage)
24
25
  - [Overriding credentials](#overriding-credentials)
25
26
  - [Handling validation errors](#handling-validation-errors)
27
+ - [Using interceptors](#using-interceptors)
28
+ - [Refreshing access token](#refreshing-access-token)
26
29
  - [Contributors guide](#contributors-guide)
27
30
  - [Need help?](#need-help)
28
31
  - [License](#license)
@@ -66,6 +69,37 @@ const cl = CommerceLayer({
66
69
  })
67
70
  ```
68
71
 
72
+ ### Options
73
+
74
+ When instantiating a new SDK client you can pass some options to initialize it:
75
+
76
+ ```javascript
77
+ {
78
+ organization: string // The organization slug
79
+ accessToken: string // A valid API access token
80
+ timeout?: number // A custom request timout (<= 15 secs [default])
81
+ headers?: RequestHeaders // Custom request headers
82
+ userAgent?: string // Custom user-agent useful in certaing contexts but often not allowed by browsers
83
+ fetch?: Fetch // A specific fetch implementation
84
+ refreshToken?: RefreshToken // A function responsible for token refresh
85
+ }
86
+ ```
87
+
88
+ Same options can be changed after SDK initialization or passed at runtime while executing an API call:
89
+
90
+ ```javascript
91
+ const options = { ... }
92
+
93
+ // Instantiate the client using desired options
94
+ const cl = CommerceLayer(options)
95
+
96
+ // Change configuration after client cteation
97
+ cl.config(options)
98
+
99
+ // Use runtime configuration without persisting settings
100
+ cl.customers.list({}, options)
101
+ ```
102
+
69
103
  ## SDK usage
70
104
 
71
105
  The JavaScript SDK is a wrapper around Commerce Layer API which means you would still be making API requests but with a different syntax. For now, we don't have comprehensive SDK documentation for every single resource our API supports (about 400+ endpoints), hence you will need to rely on our comprehensive [API Reference](https://docs.commercelayer.io/core/v/api-reference) as you go about using this SDK. So for example, if you want to create an order, take a look at the [Order object](https://docs.commercelayer.io/core/v/api-reference/orders/object) or the [Create an order](https://docs.commercelayer.io/core/v/api-reference/orders/create) documentation to see the required attributes and/or relationships. The same goes for every other supported resource.
@@ -388,6 +422,76 @@ Commerce Layer API returns specific errors (with extra information) on each attr
388
422
 
389
423
  ℹ️ Check our API reference for more information about the [errors](https://docs.commercelayer.io/developers/handling-errors) returned by the API.
390
424
 
425
+ ## Using interceptors
426
+
427
+ You can use interceptors to intercept SDK messages and modify them on the fly before the request is sent to the API or before the response is parsed and returned by the client. You can also access the error object before it is thrown by the SDK.
428
+
429
+ Interceptors are special functions that are able to handle SDK messages and return a (eventually) modified version of them for use by the client.
430
+
431
+ ```javascript
432
+ const requestInterceptor = (request: RequestObj): RequestObj => {
433
+ console.log(request)
434
+ return request
435
+ }
436
+
437
+ const responseInterceptor = (response: ResponseObj): ResponseObj => {
438
+ console.log(response)
439
+ return response
440
+ }
441
+
442
+ const errorInterceptor = (error: ErrorObj): ErrorObj => {
443
+ console.log(error)
444
+ return error
445
+ }
446
+ ```
447
+
448
+ Here an example of how to use them:
449
+
450
+ ```javascript
451
+ // Add the interceptors (only one or all if needed)
452
+ cl.addRequestInterceptor(requestInterceptor)
453
+ cl.addResponseInterceptor(responseInterceptor, errorInterceptor)
454
+
455
+ const customers = await cl.customers.list()
456
+
457
+ // Remove interceptors
458
+ // Tt is possible to remove only a specific interceptor: cl.removeInterceptor('request')
459
+ cl.removeInterceptors()
460
+ ```
461
+
462
+ #### Raw Response Reader
463
+
464
+ The *RawResponseReader* is a special interceptor that allows to catch the original message coming frome the API before it is parsed and translated in SDK objects.
465
+
466
+ ```javascript
467
+ // Add a RawResponseReader capable of capturing also response headers
468
+ const rrr = cl.addRawResponseReader({ headers: true })
469
+
470
+ const customers = await cl.customers.list()
471
+
472
+ cl.removeRawResponseReader()
473
+
474
+ console.log(rrr.rawResponse)
475
+ console.log(rrr.headers)
476
+ ```
477
+
478
+ ## Refreshing access token
479
+
480
+ It is possible that you are using an access token that is about to expire especially if it has been used for many API calls.
481
+ In this case you can define a special function that takes care of refreshing the token when a call fails because it has expired.
482
+
483
+ ```javascript
484
+ async function myRefreshTokenFunction(espiredToken: string): Promise<string> {
485
+ // Get a new access token using for example our js-auth library
486
+ return (await getAccessToken()).accessToken
487
+ }
488
+
489
+ cl.config({ refreshToken: myRefreshTokenFunction })
490
+
491
+ // If needed you can later retrieve the new access token
492
+ const newToken = cl.currentAccessToken
493
+ ```
494
+
391
495
  ## Contributors guide
392
496
 
393
497
  1. Fork [this repository](https://github.com/commercelayer/commercelayer-sdk) (learn how to do this [here](https://help.github.com/articles/fork-a-repo)).
package/lib/index.d.mts CHANGED
@@ -47,12 +47,14 @@ type RawResponseReader = {
47
47
 
48
48
  type RequestParams = Record<string, string | number | boolean>;
49
49
  type RequestHeaders = Record<string, string>;
50
+ type RefreshToken = (expiredToken: string) => Promise<string>;
50
51
  type RequestConfig = {
51
52
  timeout?: number;
52
53
  params?: RequestParams;
53
54
  headers?: RequestHeaders;
54
55
  userAgent?: string;
55
56
  fetch?: Fetch;
57
+ refreshToken?: RefreshToken;
56
58
  };
57
59
  type ApiConfig = {
58
60
  organization: string;
@@ -72,6 +74,7 @@ declare class ApiClient {
72
74
  userAgent(userAgent: string): this;
73
75
  request(method: Method, path: string, body?: any, options?: ApiClientConfig): Promise<FetchResponse>;
74
76
  private customHeaders;
77
+ get currentAccessToken(): string;
75
78
  }
76
79
 
77
80
  type CreateArrayWithLengthX<LENGTH extends number, ACC extends unknown[] = []> = ACC['length'] extends LENGTH ? ACC : CreateArrayWithLengthX<LENGTH, [...ACC, 1]>;
@@ -15004,7 +15007,8 @@ declare enum ErrorType {
15004
15007
  RESPONSE = "response",// Error response from API
15005
15008
  CANCEL = "cancel",// Forced request abort using interceptor
15006
15009
  PARSE = "parse",// Error parsing API resource
15007
- TIMEOUT = "timeout"
15010
+ TIMEOUT = "timeout",// Timeout error
15011
+ TOKEN_REFRESH = "token-refresh"
15008
15012
  }
15009
15013
  declare class SdkError extends Error {
15010
15014
  static NAME: string;
@@ -15157,6 +15161,7 @@ declare class CommerceLayerClient {
15157
15161
  get webhooks(): Webhooks;
15158
15162
  get wire_transfers(): WireTransfers;
15159
15163
  get currentOrganization(): string;
15164
+ get currentAccessToken(): string;
15160
15165
  private get interceptors();
15161
15166
  private localConfig;
15162
15167
  config(config: CommerceLayerConfig): this;
@@ -15167,6 +15172,7 @@ declare class CommerceLayerClient {
15167
15172
  addRequestInterceptor(onSuccess?: RequestInterceptor, onFailure?: ErrorInterceptor): number;
15168
15173
  addResponseInterceptor(onSuccess?: ResponseInterceptor, onFailure?: ErrorInterceptor): number;
15169
15174
  removeInterceptor(type: InterceptorType, id?: number): void;
15175
+ removeInterceptors(): void;
15170
15176
  addRawResponseReader(options?: {
15171
15177
  headers: boolean;
15172
15178
  }): RawResponseReader;
@@ -15181,6 +15187,7 @@ declare const CommerceLayerStatic: {
15181
15187
  isSdkError: (error: unknown) => error is SdkError;
15182
15188
  isApiError: (error: unknown) => error is ApiError;
15183
15189
  init: (config: CommerceLayerInitConfig) => CommerceLayerClient;
15190
+ isTokenExpired: (token: string) => boolean;
15184
15191
  readonly schemaVersion: string;
15185
15192
  };
15186
15193
 
package/lib/index.d.ts CHANGED
@@ -47,12 +47,14 @@ type RawResponseReader = {
47
47
 
48
48
  type RequestParams = Record<string, string | number | boolean>;
49
49
  type RequestHeaders = Record<string, string>;
50
+ type RefreshToken = (expiredToken: string) => Promise<string>;
50
51
  type RequestConfig = {
51
52
  timeout?: number;
52
53
  params?: RequestParams;
53
54
  headers?: RequestHeaders;
54
55
  userAgent?: string;
55
56
  fetch?: Fetch;
57
+ refreshToken?: RefreshToken;
56
58
  };
57
59
  type ApiConfig = {
58
60
  organization: string;
@@ -72,6 +74,7 @@ declare class ApiClient {
72
74
  userAgent(userAgent: string): this;
73
75
  request(method: Method, path: string, body?: any, options?: ApiClientConfig): Promise<FetchResponse>;
74
76
  private customHeaders;
77
+ get currentAccessToken(): string;
75
78
  }
76
79
 
77
80
  type CreateArrayWithLengthX<LENGTH extends number, ACC extends unknown[] = []> = ACC['length'] extends LENGTH ? ACC : CreateArrayWithLengthX<LENGTH, [...ACC, 1]>;
@@ -15004,7 +15007,8 @@ declare enum ErrorType {
15004
15007
  RESPONSE = "response",// Error response from API
15005
15008
  CANCEL = "cancel",// Forced request abort using interceptor
15006
15009
  PARSE = "parse",// Error parsing API resource
15007
- TIMEOUT = "timeout"
15010
+ TIMEOUT = "timeout",// Timeout error
15011
+ TOKEN_REFRESH = "token-refresh"
15008
15012
  }
15009
15013
  declare class SdkError extends Error {
15010
15014
  static NAME: string;
@@ -15157,6 +15161,7 @@ declare class CommerceLayerClient {
15157
15161
  get webhooks(): Webhooks;
15158
15162
  get wire_transfers(): WireTransfers;
15159
15163
  get currentOrganization(): string;
15164
+ get currentAccessToken(): string;
15160
15165
  private get interceptors();
15161
15166
  private localConfig;
15162
15167
  config(config: CommerceLayerConfig): this;
@@ -15167,6 +15172,7 @@ declare class CommerceLayerClient {
15167
15172
  addRequestInterceptor(onSuccess?: RequestInterceptor, onFailure?: ErrorInterceptor): number;
15168
15173
  addResponseInterceptor(onSuccess?: ResponseInterceptor, onFailure?: ErrorInterceptor): number;
15169
15174
  removeInterceptor(type: InterceptorType, id?: number): void;
15175
+ removeInterceptors(): void;
15170
15176
  addRawResponseReader(options?: {
15171
15177
  headers: boolean;
15172
15178
  }): RawResponseReader;
@@ -15181,6 +15187,7 @@ declare const CommerceLayerStatic: {
15181
15187
  isSdkError: (error: unknown) => error is SdkError;
15182
15188
  isApiError: (error: unknown) => error is ApiError;
15183
15189
  init: (config: CommerceLayerInitConfig) => CommerceLayerClient;
15190
+ isTokenExpired: (token: string) => boolean;
15184
15191
  readonly schemaVersion: string;
15185
15192
  };
15186
15193