@magentrix-corp/magentrix-sdk 1.1.4 → 1.1.6

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
@@ -24,33 +24,46 @@ npm install @magentrix-corp/magentrix-sdk
24
24
  ### JavaScript/TypeScript
25
25
 
26
26
  ```typescript
27
- import { MagentrixClient, type MagentrixConfig } from '@magentrix-corp/magentrix-sdk'
27
+ import { MagentrixClient, MagentrixError, type MagentrixConfig } from '@magentrix-corp/magentrix-sdk'
28
28
 
29
29
  const config: MagentrixConfig = {
30
- baseUrl: 'https://dev.magentrix.com',
30
+ baseUrl: 'https://your-portal-domain.com',
31
31
  refreshToken: '<your-refresh-token>',
32
- isDevMode: true, // Use token-based auth
33
- onSessionExpired: async () => {
34
- console.log('Session expired!')
35
- },
36
- onError: (error) => {
37
- console.error('API Error:', error)
38
- }
32
+ isDevMode: true // Use token-based auth
39
33
  }
40
34
 
41
- const client = new MagentrixClient(config)
35
+ const dataService = new MagentrixClient(config)
42
36
 
43
- // Create a session
44
- const session = await client.createSession()
45
- console.log('Token:', session.token)
37
+ // Get current user information
38
+ try {
39
+ const userInfo = await dataService.getUserInfo()
40
+ console.log('Logged in as:', userInfo.name)
41
+ console.log('Role:', userInfo.roleType)
42
+ } catch (error) {
43
+ if (error instanceof MagentrixError) {
44
+ console.error('Failed to get user info:', error.message)
45
+ }
46
+ }
46
47
 
47
- // Query data
48
- const results = await client.query('SELECT Id, Name FROM Account')
49
- console.log(results)
48
+ // Query data - session is automatically created when needed
49
+ try {
50
+ const results = await dataService.query('SELECT Id, Name FROM Account')
51
+ console.log(results)
52
+ } catch (error) {
53
+ if (error instanceof MagentrixError) {
54
+ console.error('Query failed:', error.message)
55
+ }
56
+ }
50
57
 
51
58
  // Retrieve by ID
52
- const record = await client.retrieve('account-id-123')
53
- console.log(record)
59
+ try {
60
+ const record = await dataService.retrieve('account-id-123')
61
+ console.log(record)
62
+ } catch (error) {
63
+ if (error instanceof MagentrixError) {
64
+ console.error('Retrieve failed:', error.message)
65
+ }
66
+ }
54
67
  ```
55
68
 
56
69
  ### Vue 3
@@ -58,32 +71,40 @@ console.log(record)
58
71
  ```vue
59
72
  <script setup lang="ts">
60
73
  import { ref, onMounted } from 'vue'
61
- import { type MagentrixConfig } from '@magentrix-corp/magentrix-sdk'
74
+ import { MagentrixError, type MagentrixConfig } from '@magentrix-corp/magentrix-sdk'
62
75
  import { useMagentrixSdk } from '@magentrix-corp/magentrix-sdk/vue'
63
76
 
64
77
  const config: MagentrixConfig = {
65
- baseUrl: 'https://dev.magentrix.com',
78
+ baseUrl: 'https://your-portal-domain.com',
66
79
  refreshToken: '<your-refresh-token>',
67
- isDevMode: true,
68
- onError: (error: any) => {
69
- console.error('API Error:', error)
70
- }
80
+ isDevMode: true
71
81
  }
72
82
 
73
- const client = useMagentrixSdk().getInstance(config)
83
+ const dataService = useMagentrixSdk().getInstance(config)
74
84
  const account = ref<any>(null)
85
+ const error = ref<string | null>(null)
75
86
 
76
87
  onMounted(async () => {
77
- await client.createSession()
78
- account.value = (await client.retrieve('006000000LJIxF70000')).record
79
- console.log(account.value)
88
+ try {
89
+ // Session is automatically created when needed
90
+ account.value = (await dataService.retrieve('006000000LJIxF70000')).record
91
+ console.log(account.value)
92
+ } catch (err) {
93
+ if (err instanceof MagentrixError) {
94
+ error.value = err.message
95
+ console.error('Failed to retrieve account:', err.message)
96
+ }
97
+ }
80
98
  })
81
99
  </script>
82
100
 
83
101
  <template>
84
- <div v-if="account">
85
- <h1>{{ account.Name }}</h1>
86
- <p>{{ account.Email }}</p>
102
+ <div>
103
+ <div v-if="error" class="error">{{ error }}</div>
104
+ <div v-else-if="account">
105
+ <h1>{{ account.Name }}</h1>
106
+ <p>{{ account.Email }}</p>
107
+ </div>
87
108
  </div>
88
109
  </template>
89
110
  ```
@@ -94,11 +115,9 @@ onMounted(async () => {
94
115
 
95
116
  | Property | Type | Required | Description |
96
117
  |----------|------|----------|-------------|
97
- | `baseUrl` | `string` | Yes | Base URL of your Magentrix instance (e.g., 'https://your-instance.magentrix.com') |
118
+ | `baseUrl` | `string` | Yes | Base URL of your Magentrix instance (e.g., 'https://your-portal-domain.com') |
98
119
  | `refreshToken` | `string` | No | Refresh token for authentication. Required when `isDevMode: true` |
99
120
  | `isDevMode` | `boolean` | No | Enable token-based authentication (default: `false`). See [Authentication Modes](#authentication-modes) |
100
- | `onSessionExpired` | `() => Promise<void> \| void` | No | Callback invoked when session expires |
101
- | `onError` | `(error: any) => void` | No | Global error handler for all API errors |
102
121
 
103
122
  ## Authentication Modes
104
123
 
@@ -118,12 +137,12 @@ The SDK supports two authentication modes controlled by the `isDevMode` flag:
118
137
  import { MagentrixClient, type MagentrixConfig } from '@magentrix-corp/magentrix-sdk'
119
138
 
120
139
  const config: MagentrixConfig = {
121
- baseUrl: 'https://dev.magentrix.com',
140
+ baseUrl: 'https://your-portal-domain.com',
122
141
  refreshToken: '<your-refresh-token>',
123
142
  isDevMode: true
124
143
  }
125
144
 
126
- const client = new MagentrixClient(config)
145
+ const dataService = new MagentrixClient(config)
127
146
  ```
128
147
 
129
148
  ### Production Mode (`isDevMode: false` or not set)
@@ -141,11 +160,11 @@ const client = new MagentrixClient(config)
141
160
  import { MagentrixClient, type MagentrixConfig } from '@magentrix-corp/magentrix-sdk'
142
161
 
143
162
  const config: MagentrixConfig = {
144
- baseUrl: 'https://your-instance.magentrix.com',
163
+ baseUrl: 'https://your-portal-domain.com',
145
164
  isDevMode: false // or omit this property
146
165
  }
147
166
 
148
- const client = new MagentrixClient(config)
167
+ const dataService = new MagentrixClient(config)
149
168
  ```
150
169
 
151
170
  ## API Reference
@@ -156,10 +175,29 @@ const client = new MagentrixClient(config)
156
175
 
157
176
  Creates a new session using the refresh token.
158
177
 
178
+ **Note**: You typically don't need to call this method directly. The SDK automatically creates and refreshes sessions when needed.
179
+
159
180
  ```typescript
160
- const session = await client.createSession()
161
- console.log(session.token) // Bearer token
162
- console.log(session.expires_in) // Seconds until expiration
181
+ import { MagentrixClient, MagentrixError, type MagentrixConfig } from '@magentrix-corp/magentrix-sdk'
182
+
183
+ const config: MagentrixConfig = {
184
+ baseUrl: 'https://your-portal-domain.com',
185
+ refreshToken: '<your-refresh-token>',
186
+ isDevMode: true
187
+ }
188
+
189
+ const dataService = new MagentrixClient(config)
190
+
191
+ // Optional: Manually create session if needed
192
+ try {
193
+ const session = await dataService.createSession()
194
+ console.log(session.token) // Bearer token
195
+ console.log(session.expires_in) // Seconds until expiration
196
+ } catch (error) {
197
+ if (error instanceof MagentrixError) {
198
+ console.error('Session creation failed:', error.message)
199
+ }
200
+ }
163
201
  ```
164
202
 
165
203
  **Parameters**:
@@ -177,8 +215,16 @@ console.log(session.expires_in) // Seconds until expiration
177
215
  Execute a custom query using Magentrix query language.
178
216
 
179
217
  ```typescript
180
- const results = await client.query('SELECT Id, Name, Email FROM Contact WHERE Status = "Active"')
181
- console.log(results)
218
+ import { MagentrixError } from '@magentrix-corp/magentrix-sdk'
219
+
220
+ try {
221
+ const results = await dataService.query('SELECT Id, Name, Email FROM Contact WHERE Status = "Active"')
222
+ console.log(results)
223
+ } catch (error) {
224
+ if (error instanceof MagentrixError) {
225
+ console.error('Query failed:', error.message)
226
+ }
227
+ }
182
228
  ```
183
229
 
184
230
  **Parameters**:
@@ -195,8 +241,16 @@ console.log(results)
195
241
  Retrieve a single record by ID.
196
242
 
197
243
  ```typescript
198
- const account = await client.retrieve('account-id-123')
199
- console.log(account.Name)
244
+ import { MagentrixError } from '@magentrix-corp/magentrix-sdk'
245
+
246
+ try {
247
+ const account = await dataService.retrieve('account-id-123')
248
+ console.log(account.Name)
249
+ } catch (error) {
250
+ if (error instanceof MagentrixError) {
251
+ console.error('Retrieve failed:', error.message)
252
+ }
253
+ }
200
254
  ```
201
255
 
202
256
  **Parameters**:
@@ -215,12 +269,25 @@ console.log(account.Name)
215
269
  Create a new record.
216
270
 
217
271
  ```typescript
218
- const newAccount = await client.create('Account', {
219
- Name: 'Acme Corporation',
220
- Email: 'contact@acme.com',
221
- Status: 'Active'
222
- })
223
- console.log('Created ID:', newAccount.Id)
272
+ import { MagentrixError, DatabaseError } from '@magentrix-corp/magentrix-sdk'
273
+
274
+ try {
275
+ const newAccount = await dataService.create('Account', {
276
+ Name: 'Acme Corporation',
277
+ Email: 'contact@acme.com',
278
+ Status: 'Active'
279
+ })
280
+ console.log('Created ID:', newAccount.Id)
281
+ } catch (error) {
282
+ if (error instanceof DatabaseError) {
283
+ console.error('Database error:', error.message)
284
+ error.getErrors().forEach(err => {
285
+ console.error(`Field: ${err.fieldName}, Message: ${err.message}`)
286
+ })
287
+ } else if (error instanceof MagentrixError) {
288
+ console.error('Create failed:', error.message)
289
+ }
290
+ }
224
291
  ```
225
292
 
226
293
  **Parameters**:
@@ -229,7 +296,7 @@ console.log('Created ID:', newAccount.Id)
229
296
 
230
297
  **Returns**: Created record with ID
231
298
 
232
- **Throws**: `MagentrixError` if entityName or data is missing
299
+ **Throws**: `MagentrixError` if entityName or data is missing, `DatabaseError` for validation errors
233
300
 
234
301
  ---
235
302
 
@@ -238,11 +305,25 @@ console.log('Created ID:', newAccount.Id)
238
305
  Update an existing record (requires `Id` in data).
239
306
 
240
307
  ```typescript
241
- const updated = await client.edit('Account', {
242
- Id: 'account-id-123',
243
- Name: 'Updated Name',
244
- Status: 'Inactive'
245
- })
308
+ import { MagentrixError, DatabaseError } from '@magentrix-corp/magentrix-sdk'
309
+
310
+ try {
311
+ const updated = await dataService.edit('Account', {
312
+ Id: 'account-id-123',
313
+ Name: 'Updated Name',
314
+ Status: 'Inactive'
315
+ })
316
+ console.log('Updated successfully')
317
+ } catch (error) {
318
+ if (error instanceof DatabaseError) {
319
+ console.error('Database error:', error.message)
320
+ error.getErrors().forEach(err => {
321
+ console.error(`Field: ${err.fieldName}, Message: ${err.message}`)
322
+ })
323
+ } else if (error instanceof MagentrixError) {
324
+ console.error('Edit failed:', error.message)
325
+ }
326
+ }
246
327
  ```
247
328
 
248
329
  **Parameters**:
@@ -251,7 +332,7 @@ const updated = await client.edit('Account', {
251
332
 
252
333
  **Returns**: Updated record
253
334
 
254
- **Throws**: `MagentrixError` if entityName or data is missing
335
+ **Throws**: `MagentrixError` if entityName or data is missing, `DatabaseError` for validation errors
255
336
 
256
337
  ---
257
338
 
@@ -260,11 +341,25 @@ const updated = await client.edit('Account', {
260
341
  Create or update a record. If `Id` is provided and exists, updates the record; otherwise creates a new one.
261
342
 
262
343
  ```typescript
263
- const record = await client.upsert('Contact', {
264
- Id: 'contact-id-456', // Optional
265
- Name: 'John Doe',
266
- Email: 'john@example.com'
267
- })
344
+ import { MagentrixError, DatabaseError } from '@magentrix-corp/magentrix-sdk'
345
+
346
+ try {
347
+ const record = await dataService.upsert('Contact', {
348
+ Id: 'contact-id-456', // Optional
349
+ Name: 'John Doe',
350
+ Email: 'john@example.com'
351
+ })
352
+ console.log('Upsert successful:', record.Id)
353
+ } catch (error) {
354
+ if (error instanceof DatabaseError) {
355
+ console.error('Database error:', error.message)
356
+ error.getErrors().forEach(err => {
357
+ console.error(`Field: ${err.fieldName}, Message: ${err.message}`)
358
+ })
359
+ } else if (error instanceof MagentrixError) {
360
+ console.error('Upsert failed:', error.message)
361
+ }
362
+ }
268
363
  ```
269
364
 
270
365
  **Parameters**:
@@ -273,7 +368,7 @@ const record = await client.upsert('Contact', {
273
368
 
274
369
  **Returns**: Created or updated record
275
370
 
276
- **Throws**: `MagentrixError` if entityName or data is missing
371
+ **Throws**: `MagentrixError` if entityName or data is missing, `DatabaseError` for validation errors
277
372
 
278
373
  ---
279
374
 
@@ -282,11 +377,27 @@ const record = await client.upsert('Contact', {
282
377
  Delete a record by ID.
283
378
 
284
379
  ```typescript
285
- // Soft delete (default)
286
- await client.delete('Account', 'account-id-123')
380
+ import { MagentrixError } from '@magentrix-corp/magentrix-sdk'
287
381
 
288
- // Permanent delete
289
- await client.delete('Account', 'account-id-123', true)
382
+ try {
383
+ // Soft delete (default)
384
+ await dataService.delete('Account', 'account-id-123')
385
+ console.log('Account deleted successfully')
386
+ } catch (error) {
387
+ if (error instanceof MagentrixError) {
388
+ console.error('Delete failed:', error.message)
389
+ }
390
+ }
391
+
392
+ try {
393
+ // Permanent delete
394
+ await dataService.delete('Account', 'account-id-123', true)
395
+ console.log('Account permanently deleted')
396
+ } catch (error) {
397
+ if (error instanceof MagentrixError) {
398
+ console.error('Delete failed:', error.message)
399
+ }
400
+ }
290
401
  ```
291
402
 
292
403
  **Parameters**:
@@ -305,7 +416,16 @@ await client.delete('Account', 'account-id-123', true)
305
416
  Delete multiple records by IDs.
306
417
 
307
418
  ```typescript
308
- await client.deleteMany('Contact', ['id-1', 'id-2', 'id-3'])
419
+ import { MagentrixError } from '@magentrix-corp/magentrix-sdk'
420
+
421
+ try {
422
+ await dataService.deleteMany('Contact', ['id-1', 'id-2', 'id-3'])
423
+ console.log('Contacts deleted successfully')
424
+ } catch (error) {
425
+ if (error instanceof MagentrixError) {
426
+ console.error('Delete many failed:', error.message)
427
+ }
428
+ }
309
429
  ```
310
430
 
311
431
  **Parameters**:
@@ -319,6 +439,52 @@ await client.deleteMany('Contact', ['id-1', 'id-2', 'id-3'])
319
439
 
320
440
  ---
321
441
 
442
+ ### User Information
443
+
444
+ #### `getUserInfo(): Promise<UserInfo>`
445
+
446
+ Get information about the currently authenticated user.
447
+
448
+ ```typescript
449
+ import { MagentrixError, type UserInfo } from '@magentrix-corp/magentrix-sdk'
450
+
451
+ try {
452
+ const userInfo: UserInfo = await dataService.getUserInfo()
453
+ console.log('User Name:', userInfo.name)
454
+ console.log('Username:', userInfo.userName)
455
+ console.log('User ID:', userInfo.id)
456
+ console.log('Role Type:', userInfo.roleType)
457
+ console.log('Locale:', userInfo.locale)
458
+ console.log('Preferred Currency:', userInfo.preferred_currency)
459
+ console.log('Currency Symbol:', userInfo.userCurrencySymbol)
460
+ console.log('Timezone Offset:', userInfo.user_timezone)
461
+ console.log('Is Guest:', userInfo.guest)
462
+ console.log('Is Impersonating:', userInfo.impr)
463
+ } catch (error) {
464
+ if (error instanceof MagentrixError) {
465
+ console.error('Failed to get user info:', error.message)
466
+ }
467
+ }
468
+ ```
469
+
470
+ **Returns**: `UserInfo` object containing:
471
+ - `name`: Full name of the user
472
+ - `userName`: Username of the user
473
+ - `id`: User ID
474
+ - `guest`: Whether the user is a guest
475
+ - `impr`: Whether the user is using delegated access (impersonation)
476
+ - `preferred_currency`: User's preferred currency ISO code
477
+ - `user_timezone`: User's timezone offset
478
+ - `userCurrencySymbol`: User's currency symbol
479
+ - `lang`: User's language code
480
+ - `roleType`: User's role type (`'guest'`, `'employee'`, `'customer'`, `'partner'`, or `'admin'`)
481
+ - `locale`: User's locale
482
+ - `display_user_currency`: Whether to display amounts in user's currency
483
+
484
+ **Throws**: `MagentrixError` if the request fails
485
+
486
+ ---
487
+
322
488
  ### Custom Endpoints
323
489
 
324
490
  #### `execute(path: string, model?: any, method?: RequestMethod): Promise<any>`
@@ -326,16 +492,30 @@ await client.deleteMany('Contact', ['id-1', 'id-2', 'id-3'])
326
492
  Execute a custom API endpoint.
327
493
 
328
494
  ```typescript
329
- import { RequestMethod } from '@magentrix-corp/magentrix-sdk'
495
+ import { MagentrixError, RequestMethod } from '@magentrix-corp/magentrix-sdk'
330
496
 
331
- // GET request
332
- const data = await client.execute('/custom/endpoint', null, RequestMethod.get)
497
+ try {
498
+ // GET request
499
+ const data = await dataService.execute('/custom/endpoint', null, RequestMethod.get)
500
+ console.log('GET result:', data)
501
+ } catch (error) {
502
+ if (error instanceof MagentrixError) {
503
+ console.error('GET request failed:', error.message)
504
+ }
505
+ }
333
506
 
334
- // POST request
335
- const result = await client.execute('/custom/action', {
336
- param1: 'value1',
337
- param2: 'value2'
338
- }, RequestMethod.post)
507
+ try {
508
+ // POST request
509
+ const result = await dataService.execute('/custom/action', {
510
+ param1: 'value1',
511
+ param2: 'value2'
512
+ }, RequestMethod.post)
513
+ console.log('POST result:', result)
514
+ } catch (error) {
515
+ if (error instanceof MagentrixError) {
516
+ console.error('POST request failed:', error.message)
517
+ }
518
+ }
339
519
  ```
340
520
 
341
521
  **Parameters**:
@@ -361,7 +541,8 @@ General SDK errors (authentication, validation, API errors).
361
541
  import { MagentrixError } from '@magentrix-corp/magentrix-sdk'
362
542
 
363
543
  try {
364
- await client.createSession()
544
+ const results = await dataService.query('SELECT Id FROM Account')
545
+ console.log(results)
365
546
  } catch (error) {
366
547
  if (error instanceof MagentrixError) {
367
548
  console.error('Magentrix Error:', error.message)
@@ -377,7 +558,7 @@ Database-specific errors with detailed error information.
377
558
  import { DatabaseError } from '@magentrix-corp/magentrix-sdk'
378
559
 
379
560
  try {
380
- await client.create('Account', invalidData)
561
+ await dataService.create('Account', invalidData)
381
562
  } catch (error) {
382
563
  if (error instanceof DatabaseError) {
383
564
  console.error('Database Error:', error.message)
@@ -390,21 +571,209 @@ try {
390
571
  }
391
572
  ```
392
573
 
393
- ### Global Error Handler
574
+ ### Common Error Codes
575
+
576
+ The API returns specific error codes for different scenarios. Here are the most common ones:
577
+
578
+ #### Create Operation Errors
579
+
580
+ **HTTP 406 Not Acceptable** - Validation errors
581
+
582
+ ```json
583
+ {
584
+ "errors": [
585
+ {
586
+ "code": "Missing_Field",
587
+ "fieldName": "Name",
588
+ "message": "You must enter a value."
589
+ }
590
+ ],
591
+ "id": null,
592
+ "success": false
593
+ }
594
+ ```
595
+
596
+ **HTTP 413 Request Entity Too Large** - Payload exceeds size limit
597
+
598
+ ```json
599
+ {
600
+ "errors": [
601
+ {
602
+ "code": "PAYLOAD_TOO_LARGE",
603
+ "message": "The payload size exceeds the 20MB size limit."
604
+ }
605
+ ],
606
+ "id": null,
607
+ "success": false
608
+ }
609
+ ```
610
+
611
+ **HTTP 400 Bad Request** - Missing or invalid payload
612
+
613
+ ```json
614
+ {
615
+ "errors": [
616
+ {
617
+ "code": "PAYLOAD_MISSING",
618
+ "message": "Request body is empty. A valid JSON/XML payload is required."
619
+ }
620
+ ],
621
+ "id": null,
622
+ "success": false
623
+ }
624
+ ```
625
+
626
+ #### Update Operation Errors
627
+
628
+ **HTTP 406 Not Acceptable** - Validation errors
629
+
630
+ ```json
631
+ {
632
+ "errors": [
633
+ {
634
+ "code": "Missing_Field",
635
+ "fieldName": "LastName",
636
+ "message": "You must enter a value."
637
+ }
638
+ ],
639
+ "id": null,
640
+ "success": false
641
+ }
642
+ ```
643
+
644
+ **HTTP 404 Not Found** - Record not found
394
645
 
395
- Set a global error handler in the configuration:
646
+ ```json
647
+ {
648
+ "errors": [
649
+ {
650
+ "code": "MISSING_ENTITY",
651
+ "message": "Record no longer exists."
652
+ }
653
+ ],
654
+ "id": null,
655
+ "success": false
656
+ }
657
+ ```
658
+
659
+ **HTTP 400 Bad Request** - ID mismatch
660
+
661
+ ```json
662
+ {
663
+ "errors": [
664
+ {
665
+ "code": "ENTITY_ID_MISMATCH",
666
+ "message": "The ID in the request body does not match the record ID in the URL."
667
+ }
668
+ ],
669
+ "id": null,
670
+ "success": false
671
+ }
672
+ ```
673
+
674
+ #### Delete Operation Errors
675
+
676
+ **HTTP 406 Not Acceptable** - Resource not found
677
+
678
+ ```json
679
+ {
680
+ "message": "Resource not found",
681
+ "success": false
682
+ }
683
+ ```
684
+
685
+ **HTTP 404 Not Found** - Record not found
686
+
687
+ ```json
688
+ {
689
+ "errors": [
690
+ {
691
+ "code": "ENTITY_NOT_FOUND",
692
+ "message": "Record was not found or you may not have access."
693
+ }
694
+ ],
695
+ "id": "Not found",
696
+ "success": false
697
+ }
698
+ ```
699
+
700
+ #### Authentication Errors
701
+
702
+ **HTTP 401 Unauthorized** - Invalid or expired session
703
+
704
+ ```json
705
+ {
706
+ "message": "Session expired. Please authenticate again.",
707
+ "success": false
708
+ }
709
+ ```
710
+
711
+ **HTTP 403 Forbidden** - Invalid token or too many failed attempts
712
+
713
+ ```json
714
+ {
715
+ "errors": [
716
+ {
717
+ "code": "403",
718
+ "message": "Invalid Token"
719
+ }
720
+ ],
721
+ "success": false
722
+ }
723
+ ```
724
+
725
+ #### General Errors
726
+
727
+ **HTTP 404 Not Found** - Invalid entity or resource
728
+
729
+ ```json
730
+ {
731
+ "errors": [
732
+ {
733
+ "code": "INVALID_ENTITY",
734
+ "message": "Entity 'InvalidEntity' does not exist."
735
+ }
736
+ ],
737
+ "id": null,
738
+ "success": false
739
+ }
740
+ ```
741
+
742
+ **HTTP 500 Internal Server Error** - Unexpected server error
743
+
744
+ ```json
745
+ {
746
+ "message": "An unexpected error occurred.",
747
+ "success": false
748
+ }
749
+ ```
750
+
751
+ ### Error Handling Example
396
752
 
397
753
  ```typescript
398
- const client = new MagentrixClient({
399
- baseUrl: 'https://your-instance.magentrix.com',
400
- onError: (error) => {
401
- // Log to monitoring service
402
- console.error('Global error handler:', error)
403
-
404
- // Show user notification
405
- showNotification('An error occurred', 'error')
754
+ import { MagentrixError, DatabaseError } from '@magentrix-corp/magentrix-sdk'
755
+
756
+ try {
757
+ const newAccount = await dataService.create('Account', {
758
+ Name: 'Acme Corporation',
759
+ Email: 'contact@acme.com'
760
+ })
761
+ console.log('Created:', newAccount.Id)
762
+ } catch (error) {
763
+ if (error instanceof DatabaseError) {
764
+ // Handle validation errors with field-level details
765
+ console.error('Validation failed:', error.message)
766
+ error.getErrors().forEach(err => {
767
+ console.error(`- ${err.fieldName}: ${err.message} (Code: ${err.code})`)
768
+ })
769
+ } else if (error instanceof MagentrixError) {
770
+ // Handle general API errors
771
+ console.error('API Error:', error.message)
772
+ } else {
773
+ // Handle unexpected errors
774
+ console.error('Unexpected error:', error)
406
775
  }
407
- })
776
+ }
408
777
  ```
409
778
 
410
779
 
@@ -412,21 +781,30 @@ const client = new MagentrixClient({
412
781
 
413
782
  ## Advanced Usage
414
783
 
415
- ### Session Expiration Handling
784
+ ### Automatic Session Management
416
785
 
417
- Handle session expiration gracefully:
786
+ The SDK automatically handles session creation and refresh:
418
787
 
419
788
  ```typescript
420
- const client = new MagentrixClient({
421
- baseUrl: 'https://your-instance.magentrix.com',
789
+ import { MagentrixClient, MagentrixError, type MagentrixConfig } from '@magentrix-corp/magentrix-sdk'
790
+
791
+ const config: MagentrixConfig = {
792
+ baseUrl: 'https://your-portal-domain.com',
422
793
  refreshToken: 'your-refresh-token',
423
- isDevMode: true,
424
- onSessionExpired: async () => {
425
- console.log('Session expired, refreshing...')
426
- // The SDK will automatically refresh the session
427
- // You can add custom logic here (e.g., show notification)
794
+ isDevMode: true
795
+ }
796
+
797
+ const dataService = new MagentrixClient(config)
798
+
799
+ // No need to call createSession() - the SDK handles it automatically
800
+ try {
801
+ const results = await dataService.query('SELECT Id FROM Account')
802
+ console.log(results)
803
+ } catch (error) {
804
+ if (error instanceof MagentrixError) {
805
+ console.error('Query failed:', error.message)
428
806
  }
429
- })
807
+ }
430
808
  ```
431
809
 
432
810
  ### TypeScript Types
@@ -438,6 +816,7 @@ import {
438
816
  MagentrixClient,
439
817
  MagentrixConfig,
440
818
  SessionInfo,
819
+ UserInfo,
441
820
  MagentrixError,
442
821
  DatabaseError,
443
822
  RequestMethod,
@@ -445,12 +824,16 @@ import {
445
824
  } from '@magentrix-corp/magentrix-sdk'
446
825
 
447
826
  const config: MagentrixConfig = {
448
- baseUrl: 'https://your-instance.magentrix.com',
827
+ baseUrl: 'https://your-portal-domain.com',
449
828
  refreshToken: 'your-refresh-token',
450
829
  isDevMode: true
451
830
  }
452
831
 
453
- const client = new MagentrixClient(config)
832
+ const dataService = new MagentrixClient(config)
833
+
834
+ // Use UserInfo type for type safety
835
+ const userInfo: UserInfo = await dataService.getUserInfo()
836
+ console.log(`Welcome ${userInfo.name}!`)
454
837
  ```
455
838
 
456
839
  ### Batch Operations
@@ -458,6 +841,8 @@ const client = new MagentrixClient(config)
458
841
  Perform multiple operations efficiently:
459
842
 
460
843
  ```typescript
844
+ import { MagentrixError } from '@magentrix-corp/magentrix-sdk'
845
+
461
846
  // Create multiple records
462
847
  const accounts = [
463
848
  { Name: 'Account 1', Status: 'Active' },
@@ -465,34 +850,69 @@ const accounts = [
465
850
  { Name: 'Account 3', Status: 'Active' }
466
851
  ]
467
852
 
468
- const created = await Promise.all(
469
- accounts.map(account => client.create('Account', account))
470
- )
471
-
472
- console.log('Created IDs:', created.map(a => a.Id))
853
+ try {
854
+ const created = await Promise.all(
855
+ accounts.map(account => dataService.create('Account', account))
856
+ )
857
+ console.log('Created IDs:', created.map(a => a.Id))
858
+ } catch (error) {
859
+ if (error instanceof MagentrixError) {
860
+ console.error('Batch create failed:', error.message)
861
+ }
862
+ }
473
863
 
474
864
  // Delete multiple records
475
- const idsToDelete = ['id-1', 'id-2', 'id-3']
476
- await client.deleteMany('Account', idsToDelete)
865
+ try {
866
+ const idsToDelete = ['id-1', 'id-2', 'id-3']
867
+ await dataService.deleteMany('Account', idsToDelete)
868
+ console.log('Batch delete successful')
869
+ } catch (error) {
870
+ if (error instanceof MagentrixError) {
871
+ console.error('Batch delete failed:', error.message)
872
+ }
873
+ }
477
874
  ```
478
875
 
479
876
  ### Custom Query Examples
480
877
 
481
878
  ```typescript
482
- // Simple query
483
- const activeContacts = await client.query(
484
- 'SELECT Id, Name, Email FROM Contact WHERE Status = "Active"'
485
- )
879
+ import { MagentrixError } from '@magentrix-corp/magentrix-sdk'
486
880
 
487
- // Query with sorting
488
- const sortedAccounts = await client.query(
489
- 'SELECT Id, Name FROM Account ORDER BY Name ASC'
490
- )
881
+ try {
882
+ // Simple query
883
+ const activeContacts = await dataService.query(
884
+ 'SELECT Id, Name, Email FROM Contact WHERE Status = "Active"'
885
+ )
886
+ console.log('Active contacts:', activeContacts)
887
+ } catch (error) {
888
+ if (error instanceof MagentrixError) {
889
+ console.error('Query failed:', error.message)
890
+ }
891
+ }
491
892
 
492
- // Query with limit
493
- const recentRecords = await client.query(
494
- 'SELECT Id, Name FROM Account LIMIT 10'
495
- )
893
+ try {
894
+ // Query with sorting
895
+ const sortedAccounts = await dataService.query(
896
+ 'SELECT Id, Name FROM Account ORDER BY Name ASC'
897
+ )
898
+ console.log('Sorted accounts:', sortedAccounts)
899
+ } catch (error) {
900
+ if (error instanceof MagentrixError) {
901
+ console.error('Query failed:', error.message)
902
+ }
903
+ }
904
+
905
+ try {
906
+ // Query with limit
907
+ const recentRecords = await dataService.query(
908
+ 'SELECT Id, Name FROM Account LIMIT 10'
909
+ )
910
+ console.log('Recent records:', recentRecords)
911
+ } catch (error) {
912
+ if (error instanceof MagentrixError) {
913
+ console.error('Query failed:', error.message)
914
+ }
915
+ }
496
916
  ```
497
917
 
498
918
  ---
@@ -506,16 +926,16 @@ The SDK provides a dedicated Vue 3 composable:
506
926
  ```vue
507
927
  <script setup lang="ts">
508
928
  import { ref, onMounted } from 'vue'
509
- import { type MagentrixConfig } from '@magentrix-corp/magentrix-sdk'
929
+ import { MagentrixError, type MagentrixConfig } from '@magentrix-corp/magentrix-sdk'
510
930
  import { useMagentrixSdk } from '@magentrix-corp/magentrix-sdk/vue'
511
931
 
512
932
  const config: MagentrixConfig = {
513
- baseUrl: 'https://dev.magentrix.com',
933
+ baseUrl: 'https://your-portal-domain.com',
514
934
  refreshToken: '<your-refresh-token>',
515
935
  isDevMode: true
516
936
  }
517
937
 
518
- const client = useMagentrixSdk().getInstance(config)
938
+ const dataService = useMagentrixSdk().getInstance(config)
519
939
  const accounts = ref<any[]>([])
520
940
  const loading = ref(false)
521
941
  const error = ref<string | null>(null)
@@ -525,11 +945,14 @@ const loadAccounts = async () => {
525
945
  error.value = null
526
946
 
527
947
  try {
528
- await client.createSession()
529
- const results = await client.query('SELECT Id, Name FROM Account')
948
+ // Session is automatically created when needed
949
+ const results = await dataService.query('SELECT Id, Name FROM Account')
530
950
  accounts.value = results
531
- } catch (err: any) {
532
- error.value = err.message
951
+ } catch (err) {
952
+ if (err instanceof MagentrixError) {
953
+ error.value = err.message
954
+ console.error('Failed to load accounts:', err.message)
955
+ }
533
956
  } finally {
534
957
  loading.value = false
535
958
  }
@@ -558,16 +981,16 @@ onMounted(() => {
558
981
  ```vue
559
982
  <script setup lang="ts">
560
983
  import { ref } from 'vue'
561
- import { type MagentrixConfig } from '@magentrix-corp/magentrix-sdk'
984
+ import { MagentrixError, DatabaseError, type MagentrixConfig } from '@magentrix-corp/magentrix-sdk'
562
985
  import { useMagentrixSdk } from '@magentrix-corp/magentrix-sdk/vue'
563
986
 
564
987
  const config: MagentrixConfig = {
565
- baseUrl: 'https://dev.magentrix.com',
988
+ baseUrl: 'https://your-portal-domain.com',
566
989
  refreshToken: '<your-refresh-token>',
567
990
  isDevMode: true
568
991
  }
569
992
 
570
- const client = useMagentrixSdk().getInstance(config)
993
+ const dataService = useMagentrixSdk().getInstance(config)
571
994
 
572
995
  const formData = ref({
573
996
  Name: 'Company Name',
@@ -577,34 +1000,50 @@ const formData = ref({
577
1000
 
578
1001
  const createAccount = async () => {
579
1002
  try {
580
- const created = await client.create('Account', formData.value)
1003
+ const created = await dataService.create('Account', formData.value)
581
1004
  console.log('Created:', created)
582
1005
 
583
1006
  // Reset form
584
1007
  formData.value = { Name: '', Type: '', Status: 'Active' }
585
1008
  } catch (error) {
586
- console.error('Failed to create account:', error)
1009
+ if (error instanceof DatabaseError) {
1010
+ console.error('Database error:', error.message)
1011
+ error.getErrors().forEach(err => {
1012
+ console.error(`Field: ${err.fieldName}, Message: ${err.message}`)
1013
+ })
1014
+ } else if (error instanceof MagentrixError) {
1015
+ console.error('Failed to create account:', error.message)
1016
+ }
587
1017
  }
588
1018
  }
589
1019
 
590
1020
  const updateAccount = async (id: string) => {
591
1021
  try {
592
- await client.edit('Account', {
1022
+ await dataService.edit('Account', {
593
1023
  Id: id,
594
1024
  ...formData.value
595
1025
  })
596
1026
  console.log('Updated successfully')
597
1027
  } catch (error) {
598
- console.error('Failed to update account:', error)
1028
+ if (error instanceof DatabaseError) {
1029
+ console.error('Database error:', error.message)
1030
+ error.getErrors().forEach(err => {
1031
+ console.error(`Field: ${err.fieldName}, Message: ${err.message}`)
1032
+ })
1033
+ } else if (error instanceof MagentrixError) {
1034
+ console.error('Failed to update account:', error.message)
1035
+ }
599
1036
  }
600
1037
  }
601
1038
 
602
1039
  const deleteAccount = async (id: string) => {
603
1040
  try {
604
- await client.delete('Account', id)
1041
+ await dataService.delete('Account', id)
605
1042
  console.log('Deleted successfully')
606
1043
  } catch (error) {
607
- console.error('Failed to delete account:', error)
1044
+ if (error instanceof MagentrixError) {
1045
+ console.error('Failed to delete account:', error.message)
1046
+ }
608
1047
  }
609
1048
  }
610
1049
  </script>
@@ -619,8 +1058,8 @@ const deleteAccount = async (id: string) => {
619
1058
  Use environment variables for configuration:
620
1059
 
621
1060
  ```typescript
622
- const client = new MagentrixClient({
623
- baseUrl: process.env.MAGENTRIX_BASE_URL || 'https://default.magentrix.com',
1061
+ const dataService = new MagentrixClient({
1062
+ baseUrl: process.env.MAGENTRIX_BASE_URL || 'https://your-portal-domain.com',
624
1063
  refreshToken: process.env.MAGENTRIX_REFRESH_TOKEN,
625
1064
  isDevMode: process.env.NODE_ENV === 'development'
626
1065
  })
@@ -631,12 +1070,15 @@ const client = new MagentrixClient({
631
1070
  Always handle errors appropriately:
632
1071
 
633
1072
  ```typescript
1073
+ import { MagentrixError, DatabaseError } from '@magentrix-corp/magentrix-sdk'
1074
+
634
1075
  try {
635
- const result = await client.create('Account', data)
636
- // Handle success
1076
+ const result = await dataService.create('Account', data)
1077
+ console.log('Account created:', result.Id)
637
1078
  } catch (error) {
638
1079
  if (error instanceof DatabaseError) {
639
1080
  // Handle database validation errors
1081
+ console.error('Database Error:', error.message)
640
1082
  error.getErrors().forEach(err => {
641
1083
  console.error(`${err.fieldName}: ${err.message}`)
642
1084
  })
@@ -652,21 +1094,23 @@ try {
652
1094
 
653
1095
  ### 3. Session Management
654
1096
 
655
- For development mode, create session once at app initialization:
1097
+ The SDK automatically manages sessions - no manual initialization needed:
656
1098
 
657
1099
  ```typescript
658
1100
  // app.ts or main.ts
659
- const client = new MagentrixClient({
660
- baseUrl: 'https://your-instance.magentrix.com',
1101
+ import { MagentrixClient, type MagentrixConfig } from '@magentrix-corp/magentrix-sdk'
1102
+
1103
+ const config: MagentrixConfig = {
1104
+ baseUrl: 'https://your-portal-domain.com',
661
1105
  refreshToken: 'your-refresh-token',
662
1106
  isDevMode: true
663
- })
1107
+ }
664
1108
 
665
- // Initialize session
666
- await client.createSession()
1109
+ const dataService = new MagentrixClient(config)
667
1110
 
1111
+ // No need to call createSession() - it's handled automatically
668
1112
  // Export for use throughout the app
669
- export { client }
1113
+ export { dataService }
670
1114
  ```
671
1115
 
672
1116
  ### 4. Production Deployment
@@ -674,14 +1118,25 @@ export { client }
674
1118
  For production (cookie-based auth), no session creation needed:
675
1119
 
676
1120
  ```typescript
677
- const client = new MagentrixClient({
678
- baseUrl: 'https://your-instance.magentrix.com',
1121
+ import { MagentrixClient, MagentrixError, type MagentrixConfig } from '@magentrix-corp/magentrix-sdk'
1122
+
1123
+ const config: MagentrixConfig = {
1124
+ baseUrl: 'https://your-portal-domain.com',
679
1125
  isDevMode: false // Uses ASP.NET session cookies
680
- })
1126
+ }
1127
+
1128
+ const dataService = new MagentrixClient(config)
681
1129
 
682
1130
  // No need to call createSession()
683
- // Just use the client directly
684
- const data = await client.query('SELECT Id FROM Account')
1131
+ // Just use the dataService directly
1132
+ try {
1133
+ const data = await dataService.query('SELECT Id FROM Account')
1134
+ console.log(data)
1135
+ } catch (error) {
1136
+ if (error instanceof MagentrixError) {
1137
+ console.error('Query failed:', error.message)
1138
+ }
1139
+ }
685
1140
  ```
686
1141
 
687
1142
  ---
@@ -695,11 +1150,15 @@ const data = await client.query('SELECT Id FROM Account')
695
1150
  **Solution**: Ensure `refreshToken` is provided in config when using `isDevMode: true`
696
1151
 
697
1152
  ```typescript
698
- const client = new MagentrixClient({
699
- baseUrl: 'https://your-instance.magentrix.com',
1153
+ import { MagentrixClient, type MagentrixConfig } from '@magentrix-corp/magentrix-sdk'
1154
+
1155
+ const config: MagentrixConfig = {
1156
+ baseUrl: 'https://your-portal-domain.com',
700
1157
  refreshToken: 'your-refresh-token', // Required for dev mode
701
1158
  isDevMode: true
702
- })
1159
+ }
1160
+
1161
+ const dataService = new MagentrixClient(config)
703
1162
  ```
704
1163
 
705
1164
  ---
@@ -723,8 +1182,8 @@ Proprietary
723
1182
  ## Support
724
1183
 
725
1184
  For issues and questions:
726
- - GitHub Issues: [Create an issue](https://github.com/your-repo/magentrix-sdk/issues)
727
- - Documentation: [Magentrix Developer Portal](https://your-instance.magentrix.com/docs)
1185
+ - Documentation: [Magentrix Help Center]https://help.magentrix.com/
1186
+ - Website: [Magentrix.com](https://www.magentrix.com/)
728
1187
 
729
1188
  ---
730
1189