merchi_sdk_ts 1.0.70 → 1.0.72-test

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
@@ -1,22 +1,244 @@
1
- # merchi_cart
2
- Merchi's cart
1
+ # Merchi TypeScript SDK
3
2
 
3
+ A TypeScript SDK for interacting with the Merchi API.
4
+
5
+ [![npm version](https://img.shields.io/npm/v/merchi_sdk_ts.svg)](https://www.npmjs.com/package/merchi_sdk_ts)
6
+ [![License: GPL-3.0](https://img.shields.io/badge/License-GPL%203.0-blue.svg)](https://www.gnu.org/licenses/gpl-3.0)
4
7
 
5
8
  ## Table of Contents
6
9
 
7
10
  - [Installation](#installation)
8
- - [Usage](#usage)
11
+ - [Quick Start](#quick-start)
12
+ - [Configuration](#configuration)
13
+ - [Authentication](#authentication)
14
+ - [Basic Usage](#basic-usage)
15
+ - [Entity Operations](#entity-operations)
16
+ - [Embedding Related Entities](#embedding-related-entities)
17
+ - [Available Entities](#available-entities)
18
+ - [Examples](#examples)
19
+ - [TypeScript Support](#typescript-support)
20
+ - [License](#license)
9
21
 
10
22
  ## Installation
11
23
 
12
24
  ```bash
25
+ # Using npm
13
26
  npm install merchi_sdk_ts
14
27
 
15
- or
16
-
28
+ # Using yarn
17
29
  yarn add merchi_sdk_ts
18
30
  ```
19
31
 
20
- ### Usage
21
- The sdk by default is set up to make request to the Merchi production server 'https://api.merchi.co/'.
22
- You can set the API URI by setting `process.env.MERCHI_BACKEND_URI` in your environment or `window.merchiBackendUri` on the client.
32
+ ## Quick Start
33
+
34
+ ```typescript
35
+ import { Merchi, Product } from 'merchi_sdk_ts';
36
+
37
+ // Initialize the SDK
38
+ const merchi = new Merchi();
39
+
40
+ // Fetch a product by ID
41
+ Product.get(123).then(product => {
42
+ console.log(product.name);
43
+ });
44
+ ```
45
+
46
+ ## Configuration
47
+
48
+ The SDK by default is set up to make requests to the Merchi production server at `https://api.merchi.co/v6/`.
49
+
50
+ You can customize the API endpoint by:
51
+
52
+ 1. Setting `process.env.MERCHI_BACKEND_URI` in your Node.js environment.
53
+ 2. Setting `window.merchiBackendUri` in the browser.
54
+ 3. Passing the `backendUri` directly to the `Merchi` constructor (highest precedence).
55
+
56
+ The SDK will look for these in the order of 3, 2, 1, and finally use the default production URL if none are found.
57
+ The API version (e.g., `/v6/`) will be appended automatically if not included in your custom URI, assuming the URI ends with the base domain (e.g. `https://custom.merchi.co`). If your custom URI already includes a path (e.g., `https://custom.merchi.co/api/`), ensure it ends with a trailing slash for the version to be appended correctly (e.g., `https://custom.merchi.co/api/v6/`).
58
+
59
+ **Example: Passing `backendUri` to the constructor**
60
+
61
+ ```typescript
62
+ import { Merchi } from 'merchi_sdk_ts';
63
+
64
+ // Initialize the SDK with a custom backend URI
65
+ // This URI should be the base path to your Merchi backend instance.
66
+ // The API version (e.g., /v6/) will be appended.
67
+ const customBackend = 'https://my-custom-merchi-instance.com/';
68
+ const merchi = new Merchi(undefined, undefined, undefined, undefined, customBackend);
69
+
70
+ // If your custom URI already includes a specific path and you want to control the full endpoint:
71
+ const specificCustomBackend = 'https://my-custom-merchi-instance.com/api/custom_version/';
72
+ const merchiSpecific = new Merchi(undefined, undefined, undefined, undefined, specificCustomBackend);
73
+
74
+ // Now, all API calls made using this 'merchi' or 'merchiSpecific' instance
75
+ // will be directed to your specified backend.
76
+ // For example:
77
+ // merchi.Product.get(1) will call https://my-custom-merchi-instance.com/v6/products/1/
78
+ // merchiSpecific.Product.get(1) will call https://my-custom-merchi-instance.com/api/custom_version/products/1/
79
+ ```
80
+
81
+ ## Authentication
82
+
83
+ The SDK supports several authentication methods:
84
+
85
+ ```typescript
86
+ // Session token authentication (most common)
87
+ const merchi = new Merchi('your-session-token');
88
+
89
+ // Alternative methods
90
+ const merchi = new Merchi(
91
+ 'your-session-token', // Session token
92
+ 'your-client-token', // Client token
93
+ 'your-invoice-token', // Invoice token
94
+ 'your-cart-token' // Cart token
95
+ );
96
+
97
+ // The SDK will also attempt to read session_token from cookies
98
+ // if no token is provided
99
+ ```
100
+
101
+ ## Basic Usage
102
+
103
+ ### Entity Operations
104
+
105
+ Each entity supports standard CRUD operations:
106
+
107
+ ```typescript
108
+ // Fetch a single entity
109
+ Product.get(123).then(product => {
110
+ console.log(product);
111
+ });
112
+
113
+ // List entities with filtering
114
+ Product.list({
115
+ limit: 10,
116
+ offset: 0,
117
+ q: 'search-term'
118
+ }).then(response => {
119
+ console.log(response.items); // Array of products
120
+ console.log(response.metadata); // Metadata including count, limit, offset
121
+ });
122
+
123
+ // Create a new entity
124
+ const product = new Product();
125
+ product.name = 'New Product';
126
+ product.description = 'Product description';
127
+ product.create().then(newProduct => {
128
+ console.log(newProduct.id);
129
+ });
130
+
131
+ // Update an entity
132
+ product.name = 'Updated Product Name';
133
+ product.save().then(updatedProduct => {
134
+ console.log(updatedProduct);
135
+ });
136
+
137
+ // Delete an entity
138
+ product.delete().then(() => {
139
+ console.log('Product deleted');
140
+ });
141
+ ```
142
+
143
+ ### Embedding Related Entities
144
+
145
+ You can request related entities be included in responses:
146
+
147
+ ```typescript
148
+ Product.get(123, {
149
+ embed: {
150
+ domain: {},
151
+ variations: {
152
+ variationFields: {}
153
+ }
154
+ }
155
+ }).then(product => {
156
+ console.log(product.domain); // Domain entity is included
157
+ console.log(product.variations); // Variations are included
158
+ console.log(product.variations[0].variationFields); // Fields are included
159
+ });
160
+ ```
161
+
162
+ ## Available Entities
163
+
164
+ The SDK provides access to all Merchi entities, including but not limited to:
165
+
166
+ - User, Company, Domain
167
+ - Product, Category, Variation
168
+ - Cart, CartItem
169
+ - Job, Assignment, Invoice
170
+ - File, Draft, DraftTemplate
171
+ - Payment, Shipment
172
+ - And many more...
173
+
174
+ Each entity maps directly to the corresponding API endpoint and data structure.
175
+
176
+ ## Examples
177
+
178
+ ### Working with Products
179
+
180
+ ```typescript
181
+ import { Merchi, Product } from 'merchi_sdk_ts';
182
+
183
+ // Initialize Merchi
184
+ const merchi = new Merchi('your-session-token');
185
+
186
+ // Create a new product
187
+ const product = new Product();
188
+ product.name = 'Custom T-Shirt';
189
+ product.description = 'High-quality custom printed t-shirt';
190
+ product.public = true;
191
+
192
+ product.create().then(newProduct => {
193
+ console.log(`Created product with ID: ${newProduct.id}`);
194
+ });
195
+ ```
196
+
197
+ ### Managing a Cart
198
+
199
+ ```typescript
200
+ import { Merchi, Cart, CartItem } from 'merchi_sdk_ts';
201
+
202
+ // Initialize Merchi
203
+ const merchi = new Merchi('your-session-token');
204
+
205
+ // Create a new cart
206
+ const cart = new Cart();
207
+ cart.create().then(newCart => {
208
+ // Add an item to the cart
209
+ const cartItem = new CartItem();
210
+ cartItem.productId = 123;
211
+ cartItem.quantity = 2;
212
+ cartItem.cartId = newCart.id;
213
+
214
+ return cartItem.create();
215
+ }).then(newCartItem => {
216
+ console.log('Item added to cart!');
217
+ });
218
+ ```
219
+
220
+ ## TypeScript Support
221
+
222
+ This SDK is built with TypeScript and provides full type definitions for all entities and operations.
223
+
224
+ ```typescript
225
+ import { Product, EmbedDescriptor } from 'merchi_sdk_ts';
226
+
227
+ // TypeScript will provide intellisense for all properties
228
+ const product = new Product();
229
+ product.name = 'New Product';
230
+
231
+ // Type checking for embed options
232
+ const embedOptions: EmbedDescriptor = {
233
+ domain: {},
234
+ variations: {
235
+ variationFields: {}
236
+ }
237
+ };
238
+
239
+ Product.get(123, { embed: embedOptions });
240
+ ```
241
+
242
+ ## License
243
+
244
+ This project is licensed under the GNU General Public License v3.0 - see the [LICENSE](LICENSE) file for details.
@@ -116,6 +116,10 @@ var CartItem = /** @class */ (function (_super) {
116
116
  CartItem.property({ arrayType: 'DomainTag' }),
117
117
  __metadata("design:type", Array)
118
118
  ], CartItem.prototype, "tags", void 0);
119
+ __decorate([
120
+ CartItem.property({ arrayType: 'Draft' }),
121
+ __metadata("design:type", Array)
122
+ ], CartItem.prototype, "ownDrafts", void 0);
119
123
  return CartItem;
120
124
  }(Entity));
121
125
  export { CartItem };
package/dist/merchi.js CHANGED
@@ -91,8 +91,9 @@ function cloneClass(original, arg) {
91
91
  Object.assign(copy, original);
92
92
  return copy;
93
93
  }
94
+ export var API_VERSION = 'v6';
94
95
  var Merchi = /** @class */ (function () {
95
- function Merchi(sessionToken, clientToken, invoiceToken, cartToken) {
96
+ function Merchi(sessionToken, clientToken, invoiceToken, cartToken, backendUri) {
96
97
  var _this = this;
97
98
  this.id = generateUUID();
98
99
  this.authenticatedFetch = function (resource, options, expectEmptyResponse) {
@@ -116,7 +117,8 @@ var Merchi = /** @class */ (function () {
116
117
  /* istanbul ignore next */
117
118
  options.query.push(['cart_token', _this.cartToken]);
118
119
  }
119
- return apiFetch(resource, options, expectEmptyResponse);
120
+ // Pass the full backendUri, and resource is now just the endpoint
121
+ return apiFetch(_this.backendUri, resource, options, expectEmptyResponse);
120
122
  };
121
123
  /* istanbul ignore next */
122
124
  this.authenticatedFetchWithProgress = function (resource, options, progressCallback) {
@@ -135,7 +137,8 @@ var Merchi = /** @class */ (function () {
135
137
  if (_this.cartToken) {
136
138
  options.query.push(['cart_token', _this.cartToken]);
137
139
  }
138
- return apiFetchWithProgress(resource, options, progressCallback);
140
+ // Pass the full backendUri, and resource is now just the endpoint
141
+ return apiFetchWithProgress(_this.backendUri, resource, options, progressCallback);
139
142
  };
140
143
  this.getCurrentUser = function (options) {
141
144
  var _a = (options || {}).embed, embed = _a === void 0 ? {} : _a;
@@ -171,6 +174,30 @@ var Merchi = /** @class */ (function () {
171
174
  else {
172
175
  this.cartToken = getCookie('cart_token');
173
176
  }
177
+ var determinedBaseUri = backendUri;
178
+ if (!determinedBaseUri) {
179
+ var clientBackendUri = typeof window !== 'undefined' &&
180
+ window.merchiBackendUri ?
181
+ window.merchiBackendUri : undefined;
182
+ if (clientBackendUri) {
183
+ determinedBaseUri = clientBackendUri;
184
+ }
185
+ }
186
+ if (!determinedBaseUri) {
187
+ var envBackendUri = typeof process !== 'undefined' &&
188
+ process.env.MERCHI_BACKEND_URI ?
189
+ process.env.MERCHI_BACKEND_URI : undefined;
190
+ if (envBackendUri) {
191
+ determinedBaseUri = envBackendUri;
192
+ }
193
+ }
194
+ if (!determinedBaseUri) {
195
+ determinedBaseUri = 'https://api.merchi.co/';
196
+ }
197
+ if (!determinedBaseUri.endsWith('/')) {
198
+ determinedBaseUri += '/';
199
+ }
200
+ this.backendUri = determinedBaseUri + API_VERSION + '/';
174
201
  // re-export configured versions of all classes
175
202
  this.AutomaticPaymentRelationship = this.setupClass(AutomaticPaymentRelationship);
176
203
  this.Variation = this.setupClass(Variation);
package/dist/request.js CHANGED
@@ -45,39 +45,28 @@ var ApiError = /** @class */ (function (_super) {
45
45
  }(Error));
46
46
  export { ApiError };
47
47
  export var version = 'v6';
48
- export function backendFetch(resource, options) {
48
+ export function backendFetch(baseUrl, resource, options) {
49
49
  var e_1, _a;
50
- var _b;
51
- var defaultBackendUri = 'https://api.merchi.co/';
52
- // backend uri as defined on the window element takes priority
53
- var clientBackendUri = typeof window !== 'undefined' &&
54
- window.merchiBackendUri ?
55
- window.merchiBackendUri : undefined;
56
- // backend uri as defined on env
57
- var envBackendUri = typeof process !== 'undefined' &&
58
- process.env.MERCHI_BACKEND_URI ?
59
- process.env.MERCHI_BACKEND_URI : undefined;
60
- var server = (_b = envBackendUri !== null && envBackendUri !== void 0 ? envBackendUri : clientBackendUri) !== null && _b !== void 0 ? _b : defaultBackendUri;
61
- var url = new URL(server + version + resource);
50
+ var url = new URL(resource, baseUrl);
62
51
  if (options && options.query) {
63
52
  try {
64
- for (var _c = __values(options.query), _d = _c.next(); !_d.done; _d = _c.next()) {
65
- var entry = _d.value;
53
+ for (var _b = __values(options.query), _c = _b.next(); !_c.done; _c = _b.next()) {
54
+ var entry = _c.value;
66
55
  url.searchParams.append(entry[0], entry[1]);
67
56
  }
68
57
  }
69
58
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
70
59
  finally {
71
60
  try {
72
- if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
61
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
73
62
  }
74
63
  finally { if (e_1) throw e_1.error; }
75
64
  }
76
65
  }
77
66
  return fetch(url.toString(), options);
78
67
  }
79
- export function apiFetch(resource, options, expectEmptyResponse) {
80
- return backendFetch(resource, options).then(function (response) {
68
+ export function apiFetch(baseUrl, resource, options, expectEmptyResponse) {
69
+ return backendFetch(baseUrl, resource, options).then(function (response) {
81
70
  if (response.status < 200 || response.status > 299) {
82
71
  return response.json().then(function (json) {
83
72
  var err = new ApiError(json);
@@ -90,8 +79,8 @@ export function apiFetch(resource, options, expectEmptyResponse) {
90
79
  });
91
80
  }
92
81
  /* istanbul ignore next */
93
- export function apiFetchWithProgress(resource, options, progressCallback) {
94
- return backendFetch(resource, options).then(function (response) {
82
+ export function apiFetchWithProgress(baseUrl, resource, options, progressCallback) {
83
+ return backendFetch(baseUrl, resource, options).then(function (response) {
95
84
  if (!response.body) {
96
85
  var err = new ApiError('empty response');
97
86
  return Promise.reject(err);
@@ -4,20 +4,20 @@ import { setup, mockFetch } from './test_util.js';
4
4
  setup();
5
5
  test('can pass through data from server', function () {
6
6
  mockFetch(true, { 'animal': 'turtle' }, 200);
7
- return apiFetch('/test').then(function (data) {
7
+ return apiFetch('https://api.merchi.co/', '/test').then(function (data) {
8
8
  expect(data.animal).toBe('turtle');
9
9
  });
10
10
  });
11
11
  test('can pass through data from server with override url', function () {
12
12
  window.merchiBackendUri = 'http://override.example.com/';
13
13
  mockFetch(true, { 'animal': 'turtle' }, 200);
14
- return apiFetch('/test').then(function (data) {
14
+ return apiFetch('https://api.merchi.co/', '/test').then(function (data) {
15
15
  expect(data.animal).toBe('turtle');
16
16
  });
17
17
  });
18
18
  test('404 creates ApiError', function () {
19
19
  mockFetch(false, { 'statusCode': 404, 'errorCode': ErrorType.RESOURCE_NOT_FOUND }, 404);
20
- apiFetch('/test').catch(function (e) {
20
+ apiFetch('https://api.merchi.co/', '/test').catch(function (e) {
21
21
  expect(e.statusCode).toBe(404);
22
22
  expect(e.name).toBe('ApiError');
23
23
  expect(e.errorCode).toBe(ErrorType.RESOURCE_NOT_FOUND);
@@ -28,7 +28,7 @@ test('will get default errorCode', function () {
28
28
  mockFetch(false, { 'statusCode': 404,
29
29
  'errorCode': -1,
30
30
  'message': 'just a test' }, 404);
31
- apiFetch('/test').catch(function (e) {
31
+ apiFetch('https://api.merchi.co/', '/test').catch(function (e) {
32
32
  expect(e.statusCode).toBe(404);
33
33
  expect(e.name).toBe('ApiError');
34
34
  expect(e.errorCode).toBe(ErrorType.UNKNOWN_ERROR);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "merchi_sdk_ts",
3
- "version": "1.0.70",
3
+ "version": "1.0.72-test",
4
4
  "main": "dist/index.js",
5
5
  "type": "module",
6
6
  "repository": "git@github.com:merchisdk/merchi_sdk_ts.git",
@@ -6,6 +6,7 @@ import { RequestOptions } from '../request.js';
6
6
  import { Variation } from './variation.js';
7
7
  import { VariationsGroup } from './variations_group.js';
8
8
  import { DomainTag } from './domain_tag.js';
9
+ import { Draft } from './draft.js';
9
10
 
10
11
  export class CartItem extends Entity {
11
12
  protected static resourceName = 'cart_items';
@@ -57,6 +58,9 @@ export class CartItem extends Entity {
57
58
  @CartItem.property({arrayType: 'DomainTag'})
58
59
  public tags?: DomainTag[];
59
60
 
61
+ @CartItem.property({arrayType: 'Draft'})
62
+ public ownDrafts?: Draft[];
63
+
60
64
  public requiresShipment = () => {
61
65
  if (this.product === undefined) {
62
66
  throw 'product is undefined, did you forget to embed it?';
package/src/merchi.ts CHANGED
@@ -99,6 +99,8 @@ interface UserRequestOptions {
99
99
  embed?: EmbedDescriptor;
100
100
  }
101
101
 
102
+ export const API_VERSION = 'v6';
103
+
102
104
  export class Merchi {
103
105
  public id: string = generateUUID();
104
106
 
@@ -106,6 +108,7 @@ export class Merchi {
106
108
  public invoiceToken?: string;
107
109
  public clientToken?: string;
108
110
  public cartToken?: string;
111
+ public readonly backendUri: string;
109
112
 
110
113
  public AutomaticPaymentRelationship: typeof AutomaticPaymentRelationship;
111
114
  public Notification: typeof Notification;
@@ -189,7 +192,8 @@ export class Merchi {
189
192
  sessionToken?: string,
190
193
  clientToken?: string,
191
194
  invoiceToken?: string,
192
- cartToken?: string
195
+ cartToken?: string,
196
+ backendUri?: string
193
197
  ) {
194
198
  if (sessionToken) {
195
199
  this.sessionToken = sessionToken;
@@ -215,6 +219,32 @@ export class Merchi {
215
219
  this.cartToken = getCookie('cart_token');
216
220
  }
217
221
 
222
+ let determinedBaseUri = backendUri;
223
+ if (!determinedBaseUri) {
224
+ const clientBackendUri = typeof window !== 'undefined' &&
225
+ (window as any).merchiBackendUri ?
226
+ (window as any).merchiBackendUri : undefined;
227
+ if (clientBackendUri) {
228
+ determinedBaseUri = clientBackendUri;
229
+ }
230
+ }
231
+ if (!determinedBaseUri) {
232
+ const envBackendUri = typeof process !== 'undefined' &&
233
+ process.env.MERCHI_BACKEND_URI ?
234
+ process.env.MERCHI_BACKEND_URI : undefined;
235
+ if (envBackendUri) {
236
+ determinedBaseUri = envBackendUri;
237
+ }
238
+ }
239
+ if (!determinedBaseUri) {
240
+ determinedBaseUri = 'https://api.merchi.co/';
241
+ }
242
+
243
+ if (!determinedBaseUri.endsWith('/')) {
244
+ determinedBaseUri += '/';
245
+ }
246
+ this.backendUri = determinedBaseUri + API_VERSION + '/';
247
+
218
248
  // re-export configured versions of all classes
219
249
  this.AutomaticPaymentRelationship = this.setupClass(
220
250
  AutomaticPaymentRelationship
@@ -348,7 +378,8 @@ export class Merchi {
348
378
  /* istanbul ignore next */
349
379
  options.query.push(['cart_token', this.cartToken]);
350
380
  }
351
- return apiFetch(resource, options, expectEmptyResponse);
381
+ // Pass the full backendUri, and resource is now just the endpoint
382
+ return apiFetch(this.backendUri, resource, options, expectEmptyResponse);
352
383
  };
353
384
 
354
385
  /* istanbul ignore next */
@@ -372,7 +403,8 @@ export class Merchi {
372
403
  if (this.cartToken) {
373
404
  options.query.push(['cart_token', this.cartToken]);
374
405
  }
375
- return apiFetchWithProgress(resource, options, progressCallback);
406
+ // Pass the full backendUri, and resource is now just the endpoint
407
+ return apiFetchWithProgress(this.backendUri, resource, options, progressCallback);
376
408
  };
377
409
 
378
410
  public getCurrentUser = (options?: UserRequestOptions) => {
@@ -6,7 +6,7 @@ setup();
6
6
 
7
7
  test('can pass through data from server', () => {
8
8
  mockFetch(true, {'animal': 'turtle'}, 200);
9
- return apiFetch('/test').then(data => {
9
+ return apiFetch('https://api.merchi.co/', '/test').then(data => {
10
10
  expect(data.animal).toBe('turtle');
11
11
  });
12
12
  });
@@ -14,14 +14,14 @@ test('can pass through data from server', () => {
14
14
  test('can pass through data from server with override url', () => {
15
15
  (window as any).merchiBackendUri = 'http://override.example.com/';
16
16
  mockFetch(true, {'animal': 'turtle'}, 200);
17
- return apiFetch('/test').then(data => {
17
+ return apiFetch('https://api.merchi.co/', '/test').then(data => {
18
18
  expect(data.animal).toBe('turtle');
19
19
  });
20
20
  });
21
21
 
22
22
  test('404 creates ApiError', () => {
23
23
  mockFetch(false, {'statusCode': 404, 'errorCode': ErrorType.RESOURCE_NOT_FOUND}, 404);
24
- apiFetch('/test').catch(e => {
24
+ apiFetch('https://api.merchi.co/', '/test').catch(e => {
25
25
  expect(e.statusCode).toBe(404);
26
26
  expect(e.name).toBe('ApiError');
27
27
  expect(e.errorCode).toBe(ErrorType.RESOURCE_NOT_FOUND);
@@ -34,7 +34,7 @@ test('will get default errorCode', () => {
34
34
  {'statusCode': 404,
35
35
  'errorCode': -1,
36
36
  'message': 'just a test'}, 404);
37
- apiFetch('/test').catch(e => {
37
+ apiFetch('https://api.merchi.co/', '/test').catch(e => {
38
38
  expect(e.statusCode).toBe(404);
39
39
  expect(e.name).toBe('ApiError');
40
40
  expect(e.errorCode).toBe(ErrorType.UNKNOWN_ERROR);
package/src/request.ts CHANGED
@@ -25,18 +25,8 @@ export class ApiError extends Error {
25
25
 
26
26
  export const version = 'v6';
27
27
 
28
- export function backendFetch(resource: string, options?: RequestOptions) {
29
- const defaultBackendUri: string = 'https://api.merchi.co/';
30
- // backend uri as defined on the window element takes priority
31
- const clientBackendUri = typeof window !== 'undefined' &&
32
- (window as any).merchiBackendUri ?
33
- (window as any).merchiBackendUri : undefined;
34
- // backend uri as defined on env
35
- const envBackendUri = typeof process !== 'undefined' &&
36
- process.env.MERCHI_BACKEND_URI ?
37
- process.env.MERCHI_BACKEND_URI : undefined;
38
- const server = envBackendUri ?? clientBackendUri ?? defaultBackendUri;
39
- const url = new URL(server + version + resource);
28
+ export function backendFetch(baseUrl: string, resource: string, options?: RequestOptions) {
29
+ const url = new URL(resource, baseUrl);
40
30
  if (options && options.query) {
41
31
  for (const entry of options.query) {
42
32
  url.searchParams.append(entry[0], entry[1]);
@@ -46,11 +36,12 @@ export function backendFetch(resource: string, options?: RequestOptions) {
46
36
  }
47
37
 
48
38
  export function apiFetch(
39
+ baseUrl: string,
49
40
  resource: string,
50
41
  options?: RequestOptions,
51
42
  expectEmptyResponse?: boolean
52
43
  ) {
53
- return backendFetch(resource, options as RequestInit | undefined).then(
44
+ return backendFetch(baseUrl, resource, options as RequestInit | undefined).then(
54
45
  function (response) {
55
46
  if (response.status < 200 || response.status > 299) {
56
47
  return response.json().then(function (json) {
@@ -66,11 +57,12 @@ export function apiFetch(
66
57
 
67
58
  /* istanbul ignore next */
68
59
  export function apiFetchWithProgress(
60
+ baseUrl: string,
69
61
  resource: string,
70
62
  options?: RequestOptions,
71
63
  progressCallback?: (progress: number) => void
72
64
  ) {
73
- return backendFetch(resource, options as RequestInit | undefined).then(
65
+ return backendFetch(baseUrl, resource, options as RequestInit | undefined).then(
74
66
  function (response) {
75
67
  if (!response.body) {
76
68
  const err = new ApiError('empty response');