totalum-api-sdk 2.0.41 → 3.0.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
@@ -1,20 +1,106 @@
1
- ## Totalum api sdk wrapper
1
+ ## Totalum API SDK (v3.0.0)
2
2
 
3
- This library wraps the totalum public api, so you can easy call all endpoints.
3
+ Official TypeScript/JavaScript SDK for the Totalum API. This library provides a fully typed, modern interface to interact with all Totalum endpoints.
4
4
 
5
-
6
- ## Installation:
5
+ ## Installation
7
6
 
8
7
  ```bash
9
8
  npm i totalum-api-sdk
10
9
  ```
11
10
 
11
+ ## What's New in v3.0
12
+
13
+ - **Native Fetch**: Removed `axios` dependency, now using native `fetch` API (works in Node.js 18+ and browsers)
14
+ - **Typed Responses**: All methods return strongly-typed `TotalumApiResponse<T>` with proper TypeScript support
15
+ - **Better Error Handling**: Introduced `TotalumError` class for structured error handling
16
+ - **Renamed Methods**: More consistent naming (`getItems` → `getRecords`, `getItemById` → `getRecordById`, etc.)
17
+ - **Improved Type Safety**: Full TypeScript support with detailed response types
18
+ - **No Breaking Changes in API**: Same Totalum API, just better developer experience
19
+
20
+ ## Migration Guide (v2.x → v3.0)
21
+
22
+ ### Breaking Changes
23
+
24
+ #### 1. Method Names (CRUD Service)
25
+ ```javascript
26
+ // v2.x
27
+ await totalumClient.crud.getItemById(table, id);
28
+ await totalumClient.crud.getItems(table, query);
29
+ await totalumClient.crud.createItem(table, data);
30
+ await totalumClient.crud.editItemById(table, id, data);
31
+ await totalumClient.crud.deleteItemById(table, id);
32
+ await totalumClient.crud.addManyToManyReferenceItem(table, id, prop, refId);
33
+ await totalumClient.crud.dropManyToManyReferenceItem(table, id, prop, refId);
34
+ await totalumClient.crud.getManyToManyReferencesItems(table, id, prop, query);
35
+
36
+ // v3.0
37
+ await totalumClient.crud.getRecordById(table, id);
38
+ await totalumClient.crud.getRecords(table, query);
39
+ await totalumClient.crud.createRecord(table, data);
40
+ await totalumClient.crud.editRecordById(table, id, data);
41
+ await totalumClient.crud.deleteRecordById(table, id);
42
+ await totalumClient.crud.addManyToManyReferenceRecord(table, id, prop, refId);
43
+ await totalumClient.crud.dropManyToManyReferenceRecord(table, id, prop, refId);
44
+ await totalumClient.crud.getManyToManyReferencesRecords(table, id, prop, query);
45
+ ```
46
+
47
+ #### 2. Response Structure
48
+ ```javascript
49
+ // v2.x (using axios)
50
+ const result = await totalumClient.crud.getItems(table, {});
51
+ const items = result.data.data; // Double .data because of axios wrapper
52
+
53
+ // v3.0 (using fetch)
54
+ const result = await totalumClient.crud.getRecords(table, {});
55
+ if (result.errors) {
56
+ console.error('Error:', result.errors.errorMessage);
57
+ return;
58
+ }
59
+ const records = result.data; // Direct access to data
60
+ ```
61
+
62
+ #### 3. Error Handling
63
+ ```javascript
64
+ // v2.x (axios throws errors)
65
+ try {
66
+ const result = await totalumClient.crud.getItems(table, {});
67
+ const items = result.data.data;
68
+ } catch (error) {
69
+ console.error('Error:', error.message);
70
+ }
71
+
72
+ // v3.0 (errors in response object)
73
+ const result = await totalumClient.crud.getRecords(table, {});
74
+ if (result.errors) {
75
+ console.error('Error:', result.errors.errorMessage);
76
+ console.error('Error Code:', result.errors.errorCode);
77
+ return;
78
+ }
79
+ const records = result.data;
80
+ ```
81
+
82
+ ### Dependencies
83
+ ```json
84
+ // v2.x
85
+ {
86
+ "dependencies": {
87
+ "axios": "^1.x.x"
88
+ }
89
+ }
90
+
91
+ // v3.0 (no dependencies!)
92
+ {
93
+ "dependencies": {}
94
+ }
95
+ ```
96
+
97
+ **Note:** v3.0 requires Node.js 18+ (for native fetch support). If you're using an older Node.js version, you'll need to polyfill `fetch` or upgrade to Node.js 18+.
12
98
 
13
99
  # Usage of TotalumApiSdk
14
100
 
15
- Totalum allows you to use the SDK to perform actions such as creating users, creating items, creating pdfs, etc.
101
+ Totalum allows you to use the SDK to perform actions such as creating records, managing files, creating PDFs, sending emails, and more.
16
102
 
17
- Basically the Totalum sdk is a wrapper of the Totalum api, so if you want you can use the api directly if you prefer.
103
+ The SDK is a fully-typed wrapper around the Totalum REST API.
18
104
 
19
105
  ### What happens if you are not programming in javascript?
20
106
 
@@ -22,7 +108,7 @@ If you are not programming in javascript, you can use the api directly, see <a h
22
108
 
23
109
  ## Authentication
24
110
 
25
- **Note:** If you use totalumSdk inside a totalum plugin, you don't need to authenticate, you can start using totalum like this: modules.totalumSdk.your.function();-> example: modules.totalumSdk.crud.getItems('your_item', {})
111
+ **Note:** If you use totalumSdk inside a totalum plugin, you don't need to authenticate, you can start using totalum like this: modules.totalumSdk.your.function();-> example: modules.totalumSdk.crud.getRecords('your_table', {})
26
112
 
27
113
  You can choose to use one of the two authentication methods offered by Totalum Sdk:
28
114
 
@@ -55,8 +141,8 @@ const options: AuthOptions = {
55
141
  const totalumClient = new TotalumApiSdk(options);
56
142
 
57
143
  // execute some TotalumApiSdk function
58
- const result = await totalumClient.crud.getItems('your_element_table_name', {});
59
-
144
+ const result = await totalumClient.crud.getRecords('your_table_name', {});
145
+
60
146
  ```
61
147
 
62
148
  **CommonJS Require:**
@@ -84,15 +170,15 @@ const options = {
84
170
  const totalumClient = new totalum.TotalumApiSdk(options);
85
171
 
86
172
  // execute some TotalumApiSdk function
87
- const result = await totalumClient.crud.getItems('your_element_table_name', {});
88
-
173
+ const result = await totalumClient.crud.getRecords('your_table_name', {});
174
+
89
175
  ```
90
176
 
91
177
  **HTML script import:** (Use this way if you are using standalone html, and you cannot import npm packages)
92
178
 
93
179
  ```html
94
180
  <head>
95
- <script src="https://cdn.jsdelivr.net/npm/totalum-api-sdk@2.0.37/dist/totalum-sdk.min.js"></script>
181
+ <script src="https://cdn.jsdelivr.net/npm/totalum-api-sdk@3.0.0/dist/totalum-sdk.min.js"></script>
96
182
  </head>
97
183
  <script>
98
184
  //Example of use TotalumSdk in your custom html page
@@ -103,42 +189,119 @@ const result = await totalumClient.crud.getItems('your_element_table_name', {});
103
189
  }
104
190
  });
105
191
 
106
- const tableElementName = 'your-table-name'; // replace with your table name
192
+ const tableName = 'your-table-name'; // replace with your table name
107
193
 
108
194
  //example of endpoint execution
109
- const result = totalumClient.crud.getItems(tableElementName, {}).then((result) => {
110
- const items = result.data.data;
111
- console.log("THE ITEMS", items);
195
+ totalumClient.crud.getRecords(tableName, {}).then((result) => {
196
+ if (result.errors) {
197
+ console.error("ERROR:", result.errors);
198
+ return;
199
+ }
200
+ const records = result.data;
201
+ console.log("THE RECORDS", records);
112
202
  });
113
-
203
+
114
204
  </script>
115
205
  ```
116
206
 
207
+ ## Response Structure
117
208
 
118
- ## Functions for create, read, filter, update, delete. (CRUD)
209
+ All SDK methods return a `TotalumApiResponse<T>` object with the following structure:
210
+
211
+ ```typescript
212
+ interface TotalumApiResponse<T> {
213
+ data?: T; // The successful response data
214
+ errors?: ErrorResult; // Error information if request failed
215
+ }
216
+
217
+ interface ErrorResult {
218
+ errorCode: string;
219
+ errorMessage: string;
220
+ hasManyErrors?: boolean;
221
+ multipleErrors?: Array<{ errorCode: string; errorMessage: string }>;
222
+ }
223
+ ```
224
+
225
+ **Example:**
226
+
227
+ ```typescript
228
+ const result = await totalumClient.crud.getRecordById('users', 'user-id-123');
119
229
 
230
+ // Always check for errors first
231
+ if (result.errors) {
232
+ console.error('Error:', result.errors.errorMessage);
233
+ console.error('Error Code:', result.errors.errorCode);
234
+ return;
235
+ }
236
+
237
+ // Now you can safely use result.data
238
+ const user = result.data;
239
+ console.log('User:', user);
240
+ ```
241
+
242
+ ## Error Handling
243
+
244
+ The SDK provides a `TotalumError` class for structured error handling:
245
+
246
+ ```typescript
247
+ import { TotalumError } from 'totalum-api-sdk';
120
248
 
121
- ### Get item by id
249
+ const result = await totalumClient.crud.getRecordById('users', 'invalid-id');
122
250
 
251
+ if (result.errors) {
252
+ // You can create a TotalumError for better error handling
253
+ const error = new TotalumError(result.errors);
254
+ console.error('Error Code:', error.errorCode);
255
+ console.error('Error Message:', error.errorMessage);
256
+
257
+ // Check for multiple errors
258
+ if (error.hasManyErrors && error.multipleErrors) {
259
+ error.multipleErrors.forEach(err => {
260
+ console.error(`- ${err.errorCode}: ${err.errorMessage}`);
261
+ });
262
+ }
263
+ }
264
+ ```
265
+
266
+ ## Functions for create, read, filter, update, delete. (CRUD)
267
+
268
+
269
+ ### Get record by id
123
270
 
124
271
  ```javascript
125
272
 
126
- // get item by id from your_element_table_name
127
- const tableElementName = 'your_element_table_name'; // replace 'your_element_table_name' with the name of your element table
128
- let your_item_id = 'your_item_id'; // replace 'your_item_id' with the id of the item object
129
- const result = await totalumClient.crud.getItemById(tableElementName, your_item_id);
130
- const item = result.data.data;
273
+ // Get a single record by id
274
+ const tableName = 'users'; // replace with your table name
275
+ const recordId = 'record-id-123'; // replace with your record id
276
+
277
+ const result = await totalumClient.crud.getRecordById(tableName, recordId);
278
+
279
+ if (result.errors) {
280
+ console.error('Error:', result.errors.errorMessage);
281
+ return;
282
+ }
283
+
284
+ const record = result.data;
285
+ console.log('Record:', record);
131
286
 
132
287
  ```
133
288
 
134
- ### Get items
289
+ ### Get records
135
290
 
136
291
  ```javascript
137
292
 
138
- // get items from your_element_table_name (for default 50 items per page)
139
- const tableElementName = 'your_element_table_name'; // replace 'your_element_table_name' with the name of your element table
140
- const result = await totalumClient.crud.getItems(tableElementName, {});
141
- const items = result.data.data;
293
+ // Get records from a table (default: first 50 records)
294
+ const tableName = 'users'; // replace with your table name
295
+
296
+ const result = await totalumClient.crud.getRecords(tableName, {});
297
+
298
+ if (result.errors) {
299
+ console.error('Error:', result.errors.errorMessage);
300
+ return;
301
+ }
302
+
303
+ const records = result.data;
304
+ console.log('Records:', records);
142
305
 
143
306
  ```
144
307
 
@@ -305,120 +468,185 @@ const products = result.data.data;
305
468
  You can do the same approach to get the orders.
306
469
 
307
470
 
308
- ### delete item by id
471
+ ### Delete record by id
309
472
 
310
473
  ```javascript
311
- // delete item by id from your_element_table_name
312
- const tableElementName = 'your_element_table_name'; // replace 'your_element_table_name' with the name of your element table
313
- let your_item_id = 'your_item_id'; // replace 'your_item_id' with the id of the item object
314
- const result = await totalumClient.crud.deleteItemById(tableElementName, your_item_id);
474
+
475
+ // Delete a record by id
476
+ const tableName = 'users';
477
+ const recordId = 'record-id-123';
478
+
479
+ const result = await totalumClient.crud.deleteRecordById(tableName, recordId);
480
+
481
+ if (result.errors) {
482
+ console.error('Error:', result.errors.errorMessage);
483
+ return;
484
+ }
485
+
486
+ console.log('Deleted count:', result.data.deletedCount);
487
+ console.log('Acknowledged:', result.data.acknowledged);
315
488
 
316
489
  ```
317
490
 
318
- ### edit item by id
491
+ ### Edit record by id
319
492
 
320
493
  ```javascript
321
- // edit item by id from your_element_table_name, you can edit 1 or multiple properties at the same time (like a patch)
322
- const tableElementName = 'your_element_table_name'; // replace 'your_element_table_name' with the name of your element table
323
- let your_item_id = 'your_item_id'; // replace 'your_item_id' with the id of the item object
324
- const result = await totalumClient.crud.editItemById(tableElementName, your_item_id, {your_item_property: 'new value'});
494
+
495
+ // Edit a record by id (you can edit one or multiple properties at the same time)
496
+ const tableName = 'users';
497
+ const recordId = 'record-id-123';
498
+ const updates = {
499
+ name: 'John Doe',
500
+ email: 'john@example.com',
501
+ age: 30
502
+ };
503
+
504
+ const result = await totalumClient.crud.editRecordById(tableName, recordId, updates);
505
+
506
+ if (result.errors) {
507
+ console.error('Error:', result.errors.errorMessage);
508
+ return;
509
+ }
510
+
511
+ console.log('Modified count:', result.data.modifiedCount);
512
+ console.log('Matched count:', result.data.matchedCount);
325
513
 
326
514
  ```
327
515
 
328
- ### create item
516
+ ### Create record
329
517
 
330
518
  ```javascript
331
- // create item from your_element_table_name, you need to pass at least the required properties
332
- const tableElementName = 'your_element_table_name'; // replace 'your_element_table_name' with the name of your element table
333
- const result = await totalumClient.crud.createItem(tableElementName, {your_item_property: 'new value'});
519
+
520
+ // Create a new record (you need to pass at least the required properties)
521
+ const tableName = 'users';
522
+ const newRecord = {
523
+ name: 'Jane Doe',
524
+ email: 'jane@example.com',
525
+ age: 25
526
+ };
527
+
528
+ const result = await totalumClient.crud.createRecord(tableName, newRecord);
529
+
530
+ if (result.errors) {
531
+ console.error('Error:', result.errors.errorMessage);
532
+ return;
533
+ }
534
+
535
+ console.log('Created record ID:', result.data.insertedId);
536
+ console.log('Acknowledged:', result.data.acknowledged);
334
537
 
335
538
  ```
336
539
 
337
- ### add many to many reference item (add a reference to another item that have a many to many relationship)
540
+ ### Add many-to-many reference (add a reference to another record with a many-to-many relationship)
338
541
 
339
542
  ```javascript
340
543
 
341
- const tableElementName = 'your_element_table_name'; // replace 'your_element_table_name' with the name of your element table
342
- let your_item_id = 'your_item_id'; // replace 'your_item_id' with the id of the item
343
- const propertyName = 'your_property_name'; // replace 'your_property_name' with the name of the property that have a many to many relationship
344
- const referenceId = 'your_reference_item_id'; // replace 'your_reference_item_id' with the id of the item that you want to add as a many to many reference
345
- const result = await totalumClient.crud.addManyToManyReferenceItem(tableElementName, your_item_id, propertyName, referenceId);
544
+ const tableName = 'students';
545
+ const recordId = 'student-id-123';
546
+ const propertyName = 'courses'; // the property that defines the many-to-many relationship
547
+ const referenceId = 'course-id-456'; // the id of the record to link
548
+
549
+ const result = await totalumClient.crud.addManyToManyReferenceRecord(tableName, recordId, propertyName, referenceId);
550
+
551
+ if (result.errors) {
552
+ console.error('Error:', result.errors.errorMessage);
553
+ return;
554
+ }
555
+
556
+ console.log('Reference added successfully');
346
557
 
347
558
  ```
348
559
 
349
- ### drop many to many reference item (drop a reference to another item that have a many to many relationship)
560
+ ### Drop many-to-many reference (remove a reference from a many-to-many relationship)
350
561
 
351
562
  ```javascript
352
563
 
353
- const tableElementName = 'your_element_table_name'; // replace 'your_element_table_name' with the name of your element table
354
- let your_item_id = 'your_item_id'; // replace 'your_item_id' with the id of the item
355
- const propertyName = 'your_property_name'; // replace 'your_property_name' with the name of the property that have a many to many relationship
356
- const referenceId = 'your_reference_item_id'; // replace 'your_reference_item_id' with the id of the item that you want to drop as a many to many reference
357
- const result = await totalumClient.crud.dropManyToManyReferenceItem(tableElementName, your_item_id, propertyName, referenceId);
564
+ const tableName = 'students';
565
+ const recordId = 'student-id-123';
566
+ const propertyName = 'courses';
567
+ const referenceId = 'course-id-456'; // the id of the record to unlink
568
+
569
+ const result = await totalumClient.crud.dropManyToManyReferenceRecord(tableName, recordId, propertyName, referenceId);
570
+
571
+ if (result.errors) {
572
+ console.error('Error:', result.errors.errorMessage);
573
+ return;
574
+ }
575
+
576
+ console.log('Reference removed successfully');
358
577
 
359
578
  ```
360
579
 
361
- ### get many to many references items (get all items that have a many to many relationship with the item)
580
+ ### Get many-to-many references (get all records with a many-to-many relationship)
362
581
 
363
582
  ```javascript
364
583
 
365
- const tableElementName = 'your_element_table_name'; // replace 'your_element_table_name' with the name of your element table
366
- let your_item_id = 'your_item_id'; // replace 'your_item_id' with the id of the item
367
- const propertyName = 'your_property_name'; // replace 'your_property_name' with the name of the property that have a many to many relationship
584
+ const tableName = 'students';
585
+ const recordId = 'student-id-123';
586
+ const propertyName = 'courses';
368
587
 
369
- // the query is optional, you can use it to filter and sort the results
588
+ // Optional query for filtering and sorting
370
589
  const query = {
371
590
  filter: [
372
591
  {
373
- 'your_property_name': 'value' // add your custom filters here
592
+ 'courseName': { regex: 'Math', options: 'i' }
374
593
  },
375
594
  ],
376
- sort:{
377
- 'your_property_name': 1 // 1 for asc, -1 for desc
595
+ sort: {
596
+ 'courseName': 1 // 1 for asc, -1 for desc
378
597
  },
379
598
  pagination: {
380
599
  limit: 50,
381
600
  page: 0,
382
601
  }
383
602
  };
384
- const result = await totalumClient.crud.getManyToManyReferencesItems(tableElementName, your_item_id, propertyName, query);
603
+
604
+ const result = await totalumClient.crud.getManyToManyReferencesRecords(tableName, recordId, propertyName, query);
605
+
606
+ if (result.errors) {
607
+ console.error('Error:', result.errors.errorMessage);
608
+ return;
609
+ }
610
+
611
+ const relatedRecords = result.data;
612
+ console.log('Related records:', relatedRecords);
385
613
 
386
614
  ```
387
615
 
388
616
 
389
617
  ## Functions for filter data
390
618
 
391
- ### Filter data using totalum AND filter
619
+ ### Filter data using AND filter
392
620
 
393
621
  ```javascript
394
622
 
395
- const tableElementName = 'your_element_table_name'; // replace 'your_element_table_name' with the name of your element table
623
+ const tableName = 'users';
396
624
 
397
- // get items from your_element_table_name (for default 50 items per page) applying a filter AND query (all conditions must be true)
398
- const filter: FilterSearchQueryI = {
625
+ // Get records applying AND filter (all conditions must be true)
626
+ const filter = {
399
627
  filter: [
400
628
  {
401
- 'your_property_name': 'value' // it matches the value exactly
629
+ 'name': 'John' // exact match
402
630
  },
403
631
  {
404
- 'your_other_property_name': {regex: 'your regex query', options: 'i'} // it matches a value using a regex query and options: i for case insensitive (ignore if it is uppercase or lowercase)
632
+ 'email': { regex: '@example.com', options: 'i' } // regex with case insensitive
405
633
  },
406
- // PD: gte and lte operators are only allowed for properties of type date or number
634
+ // Note: gte and lte operators are only for date or number properties
407
635
  {
408
- 'your_other_property_name': {gte: new Date('your date')} // it matches a value greater than or equal to the date
636
+ 'age': { gte: 18 } // greater than or equal to 18
409
637
  },
410
638
  {
411
- 'your_other_property_name': {lte: new Date('your date')} // it matches a value less than or equal to the date
639
+ 'age': { lte: 65 } // less than or equal to 65
412
640
  },
413
641
  {
414
- 'your_other_property_name': {gte: 10} // it matches a value greater than or equal to 10
642
+ 'createdAt': { gte: new Date('2024-01-01') } // created after date
415
643
  },
416
644
  {
417
- 'your_other_property_name': {lte: 100} // it matches a value less than or equal to 100
645
+ 'createdAt': { lte: new Date('2024-12-31') } // created before date
418
646
  }
419
647
  ],
420
- sort:{
421
- 'your_property_name': 1 // 1 for asc, -1 for desc
648
+ sort: {
649
+ 'name': 1 // 1 for ascending, -1 for descending
422
650
  },
423
651
  pagination: {
424
652
  limit: 50,
@@ -426,34 +654,43 @@ const filter: FilterSearchQueryI = {
426
654
  }
427
655
  };
428
656
 
429
- const result = await totalumClient.crud.getItems(tableElementName, filter);
430
- const items = result.data.data;
657
+ const result = await totalumClient.crud.getRecords(tableName, filter);
658
+
659
+ if (result.errors) {
660
+ console.error('Error:', result.errors.errorMessage);
661
+ return;
662
+ }
663
+
664
+ const records = result.data;
665
+ console.log('Filtered records:', records);
431
666
 
432
667
  ```
433
668
 
434
- ### Filter data using totalum OR filter
669
+ ### Filter data using OR filter
435
670
 
436
671
  ```javascript
437
672
 
438
- // get items from your_element_table_name (for default 50 items per page) applying a filter OR query (at least one condition must be true)
439
- const filter: FilterSearchQueryI = {
673
+ const tableName = 'users';
674
+
675
+ // Get records applying OR filter (at least one condition must be true)
676
+ const filter = {
440
677
  filter: [
441
678
  {
442
679
  or: [
443
680
  {
444
- 'your_property_name': 'value' // it matches the value exactly
681
+ 'name': 'John'
445
682
  },
446
683
  {
447
- 'your_other_property_name': {regex: 'your regex query', options: 'i'} // it matches a value using a regex query and options: i for case insensitive (ignore if it is uppercase or lowercase)
684
+ 'email': { regex: '@example.com', options: 'i' }
448
685
  },
449
686
  {
450
- 'your_other_property_name': {gte: new Date('your date')} // it matches a value greater than or equal to the date
687
+ 'age': { gte: 18 }
451
688
  },
452
689
  ]
453
690
  }
454
691
  ],
455
692
  sort: {
456
- 'your_property_name': 1 // 1 for asc, -1 for desc
693
+ 'name': 1 // 1 for ascending, -1 for descending
457
694
  },
458
695
  pagination: {
459
696
  limit: 50,
@@ -461,35 +698,43 @@ const filter: FilterSearchQueryI = {
461
698
  }
462
699
  };
463
700
 
464
- const result = await totalumClient.crud.getItems(tableElementName, filter);
465
- const items = result.data.data;
701
+ const result = await totalumClient.crud.getRecords(tableName, filter);
702
+
703
+ if (result.errors) {
704
+ console.error('Error:', result.errors.errorMessage);
705
+ return;
706
+ }
707
+
708
+ const records = result.data;
709
+ console.log('Filtered records:', records);
466
710
 
467
711
  ```
468
712
 
469
- ### Filter data using totalum AND and OR filter
713
+ ### Filter data using AND and OR combined
470
714
 
471
715
  ```javascript
472
716
 
473
- // get items from your_element_table_name (for default 50 items per page) applying a filter OR and AND
474
- const filter: FilterSearchQueryI = {
717
+ const tableName = 'users';
718
+
719
+ // Get records applying both OR and AND filters
720
+ const filter = {
475
721
  filter: [
476
722
  {
477
723
  or: [
478
724
  {
479
- 'your_property_name_in_or': 'value' // it matches the value exactly
725
+ 'role': 'admin'
480
726
  },
481
727
  {
482
- 'your_other_property_name_in_or': {regex: 'your regex query', options: 'i'} // it matches a value using a regex query and options: i for case insensitive (ignore if it is uppercase or lowercase)
728
+ 'role': 'moderator'
483
729
  },
484
730
  ],
485
731
  },
486
732
  {
487
- 'your_other_property_name': 'value' // it matches the value exactly
733
+ 'status': 'active' // AND this condition must be true
488
734
  }
489
-
490
735
  ],
491
736
  sort: {
492
- 'your_property_name': 1 // 1 for asc, -1 for desc
737
+ 'name': 1
493
738
  },
494
739
  pagination: {
495
740
  limit: 50,
@@ -497,27 +742,40 @@ const filter: FilterSearchQueryI = {
497
742
  }
498
743
  };
499
744
 
500
- const result = await totalumClient.crud.getItems(tableElementName, filter);
501
- const items = result.data.data;
745
+ const result = await totalumClient.crud.getRecords(tableName, filter);
746
+
747
+ if (result.errors) {
748
+ console.error('Error:', result.errors.errorMessage);
749
+ return;
750
+ }
502
751
 
752
+ const records = result.data;
753
+ console.log('Filtered records:', records);
503
754
 
504
755
  ```
505
756
 
506
- ### Filter using your custom mongoDb aggregation query
757
+ ### Filter using custom MongoDB aggregation query
507
758
 
508
759
  ```javascript
509
760
 
510
- // filter results from your_element_table_name applying a filter query (a custom mongodb aggregation query)
761
+ const tableName = 'users';
762
+
763
+ // Custom MongoDB aggregation query as string
511
764
  const customMongoDbAggregationQueryInString = `
512
-
513
- your custom mongo aggregation query in string, for more info:
514
- https://docs.mongodb.com/manual/aggregation/
515
765
 
516
- or ask to chatgpt, he is very good writing mongo aggregation queries ;)
766
+ Your custom MongoDB aggregation query in string format
767
+ For more info: https://docs.mongodb.com/manual/aggregation/
517
768
 
518
769
  `;
519
770
 
520
- const result = await totalumClient.filter.runCustomMongoAggregationQuery(tableElementName, customMongoDbAggregationQueryInString);
771
+ const result = await totalumClient.filter.runCustomMongoAggregationQuery(tableName, customMongoDbAggregationQueryInString);
772
+
773
+ if (result.errors) {
774
+ console.error('Error:', result.errors.errorMessage);
775
+ return;
776
+ }
777
+
778
+ const results = result.data;
521
779
 
522
780
  ```
523
781
 
@@ -525,9 +783,17 @@ const result = await totalumClient.filter.runCustomMongoAggregationQuery(tableEl
525
783
 
526
784
  ```javascript
527
785
 
528
- const result = await totalumClient.crud.getHistoricRecordUpdatesById(yourRecordId); // replace yourRecordId with the id of the record
786
+ const recordId = 'record-id-123';
787
+
788
+ const result = await totalumClient.crud.getHistoricRecordUpdatesById(recordId);
789
+
790
+ if (result.errors) {
791
+ console.error('Error:', result.errors.errorMessage);
792
+ return;
793
+ }
529
794
 
530
- const historicUpdates = result.data.data;
795
+ const historicUpdates = result.data;
796
+ console.log('Historic updates:', historicUpdates);
531
797
 
532
798
  ```
533
799
 
@@ -609,11 +875,18 @@ Depending on the platform you are using, you will need to transform the file to
609
875
  const FormData = require('form-data'); // if you are using node.js
610
876
 
611
877
  const fileName = 'your_file_name.png'; // replace 'your_file_name' with the name of your file, replace .png with the extension of your file
612
- const file = yourFileBlob // your blob file created in the previous step
878
+ const file = yourFileBlob // your blob file created in the previous step
613
879
  const formData = new FormData();
614
880
  formData.append('file', file, fileName);
881
+
615
882
  const result = await totalumClient.files.uploadFile(formData);
616
- const fileNameId = result.data.data;
883
+
884
+ if (result.errors) {
885
+ console.error('Error:', result.errors.errorMessage);
886
+ return;
887
+ }
888
+
889
+ const fileNameId = result.data;
617
890
  ```
618
891
 
619
892
  **Using Totalum API**
@@ -638,9 +911,19 @@ Depending on the platform you are using, you will need to transform the file to
638
911
 
639
912
  ``` javascript
640
913
 
641
- //if you want to link this file to an item, you need to add the fileNameId to the item property of type file
642
- const result2 = await totalumClient.crud.editItemById('your_element_table_name', 'your_item_id', {'your_file_property_name': {name: fileNameId}});
643
- // now the file is linked to the item property, and you can see it in the totalum panel.
914
+ // If you want to link this file to a record, you need to add the fileNameId to the record property of type file
915
+ const tableName = 'documents';
916
+ const recordId = 'record-id-123';
917
+ const result2 = await totalumClient.crud.editRecordById(tableName, recordId, {
918
+ 'attachmentFile': { name: fileNameId }
919
+ });
920
+
921
+ if (result2.errors) {
922
+ console.error('Error:', result2.errors.errorMessage);
923
+ return;
924
+ }
925
+
926
+ console.log('File linked to record successfully');
644
927
 
645
928
  ```
646
929
 
@@ -648,141 +931,365 @@ const result2 = await totalumClient.crud.editItemById('your_element_table_name',
648
931
 
649
932
  ```javascript
650
933
 
651
- // you can remove a file from totalum using the file name id
652
- const fileNameId = 'your_file_name.png'; // replace 'your_file_name' with the name id of your file, replace .png with the extension of your file
934
+ // Remove a file from Totalum using the file name id
935
+ const fileNameId = 'your_file_name.png';
653
936
 
654
937
  const result = await totalumClient.files.deleteFile(fileNameId);
655
938
 
939
+ if (result.errors) {
940
+ console.error('Error:', result.errors.errorMessage);
941
+ return;
942
+ }
943
+
944
+ console.log('File deleted successfully');
945
+
656
946
  ```
657
947
 
658
- ### Get the download url of a file
948
+ ### Get the download URL of a file
659
949
 
660
950
  ```javascript
661
951
 
662
- // you can get the fileNameId from the result of the upload file function
663
- const fileNameId = 'your_file_name.png'; // replace 'your_file_name' with the name id of your file, replace .png with the extension of your file
952
+ // Get a signed download URL for a file
953
+ const fileNameId = 'your_file_name.png';
664
954
 
665
- //optional options
955
+ // Optional: set expiration time
666
956
  const options = {
667
- // the default expiration time is 128 hours, but you can set it to whatever you want, after the expiration time the url will not return the file
668
- expirationTime: Date.now() + (128 * 60 * 60 * 1000); // Set to expire in 128 hours, how it works is, set the current date in miliseconds + the miliseconds you want the url to expire
669
- }
957
+ // Default expiration is 128 hours. Set custom expiration in milliseconds from now
958
+ expirationTime: Date.now() + (128 * 60 * 60 * 1000) // 128 hours
959
+ };
670
960
 
671
961
  const result = await totalumClient.files.getDownloadUrl(fileNameId, options);
672
- let [fileUrl] = result.data.data;
673
- // the result will be a full url that you can use to download the file
962
+
963
+ if (result.errors) {
964
+ console.error('Error:', result.errors.errorMessage);
965
+ return;
966
+ }
967
+
968
+ const fileUrl = result.data;
969
+ console.log('Download URL:', fileUrl);
674
970
 
675
971
  ```
676
972
 
677
- ### Generate a pdf from a template
973
+ ### Generate a PDF from a template
678
974
 
679
975
  ```javascript
680
976
 
681
- const templateId = 'your_template_id'; // replace 'your_template_id' with the id of your template id, go to totalum -> configuration -> pdf templates
977
+ // Go to Totalum -> Configuration -> PDF Templates to get your template ID
978
+ const templateId = 'template-id-123';
682
979
 
683
- // the variables will be replaced in your template with handlebars
684
- const variablesExample = { // replace the variables with your variables, can contain nested objects of n deep, can contain strings, numbers, dates, etc.
685
- 'your_variable_name': 'your_variable_value',
686
- 'your_other_variable_name': {
687
- 'your_other_variable_name': 'your_other_variable_value'
688
- 'your_other_variable_name': 10,
689
- 'your_other_variable_name': new Date('your date'),
980
+ // Variables will be replaced in your template using Handlebars
981
+ const variables = {
982
+ 'customerName': 'John Doe',
983
+ 'orderDetails': {
984
+ 'orderId': 'ORD-12345',
985
+ 'amount': 150.50,
986
+ 'date': new Date(),
690
987
  },
988
+ };
989
+
990
+ const fileName = 'invoice_12345.pdf';
991
+ // CAUTION: if you use the same name, the previous PDF will be overwritten
992
+
993
+ const result = await totalumClient.files.generatePdfByTemplate(templateId, variables, fileName);
994
+
995
+ if (result.errors) {
996
+ console.error('Error:', result.errors.errorMessage);
997
+ return;
691
998
  }
692
999
 
693
- const fileName = 'your_pdf_name.pdf'; // replace 'your_pdf_name' with the name of your pdf
694
- //CAUTION: if you use the same name for multiple pdfs, the pdfs will be overwritten
695
- const result = await totalumClient.files.generatePdfByTemplate(templateId, variablesExample, name);
696
- const fileResult = result.data.data;
697
- // with the fileUrl you can download the pdf
1000
+ const generatedFileName = result.data;
1001
+ console.log('PDF generated:', generatedFileName);
698
1002
 
699
- //if you want to link this pdf to an item, you need to add the fileName to the item property of type file
700
- const result2 = await totalumClient.crud.editItemById('your_element_table_name', 'your_item_id', {'your_pdf_property_name': {name: fileResult.fileName}});
1003
+ // Link this PDF to a record
1004
+ const tableName = 'invoices';
1005
+ const recordId = 'invoice-record-123';
1006
+ const result2 = await totalumClient.crud.editRecordById(tableName, recordId, {
1007
+ 'pdfFile': { name: generatedFileName }
1008
+ });
701
1009
 
702
1010
  ```
703
1011
 
704
- ### get OCR of an image (get the text of an image)
1012
+ ### Get OCR of an image (extract text from image)
705
1013
 
706
1014
  ```javascript
707
1015
 
708
- // you can only do ocr of a file that is previously uploaded to totalum (see the upload file function)
709
- // then you can do ocr of the file using the file name of the file uploaded
710
- const fileNameId = 'your_file_name_id.png'; // replace 'your_file_name' with the name of your file, replace .png with the extension of your image
1016
+ // First upload the image to Totalum, then extract text from it
1017
+ const fileNameId = 'uploaded_image.png';
1018
+
711
1019
  const result = await totalumClient.files.ocrOfImage(fileNameId);
712
- const ocrResult = result.data.data;
713
- // ocrResult.text will contain all text of the image
714
- // ocrResult.fullDetails will contain all details of the image, like the language, the position of the text, etc.
1020
+
1021
+ if (result.errors) {
1022
+ console.error('Error:', result.errors.errorMessage);
1023
+ return;
1024
+ }
1025
+
1026
+ const ocrResult = result.data;
1027
+ console.log('Extracted text:', ocrResult.text);
1028
+ console.log('Full details:', ocrResult.fullDetails);
715
1029
 
716
1030
  ```
717
1031
 
718
- ### get OCR of a pdf (get the text of a pdf)
1032
+ ### Get OCR of a PDF (extract text from PDF)
719
1033
 
720
1034
  ```javascript
721
1035
 
722
- // you can only do ocr of a file that is previously uploaded to totalum (see the upload file function)
723
- // then you can do ocr of the file using the file name of the file uploaded
724
- const fileName = 'your_file_name_id.pdf'; // replace 'your_file_name' with the name of your file
725
- const result = await totalumClient.files.ocrOfPdf(fileName);
726
- const ocrResult = result.data.data;
727
- // ocrResult.text will contain all text of the pdf
728
- // ocrResult.fullDetails will contain all details of the pdf, like the language, in which page is the text, the position of the text, etc.
1036
+ // First upload the PDF to Totalum, then extract text from it
1037
+ const fileNameId = 'uploaded_document.pdf';
1038
+
1039
+ const result = await totalumClient.files.ocrOfPdf(fileNameId);
1040
+
1041
+ if (result.errors) {
1042
+ console.error('Error:', result.errors.errorMessage);
1043
+ return;
1044
+ }
1045
+
1046
+ const ocrResult = result.data;
1047
+ console.log('Extracted text:', ocrResult.text);
1048
+ console.log('Full details:', ocrResult.fullDetails);
729
1049
 
730
1050
  ```
731
1051
 
732
- ### scan an invoice (get the details of an invoice)
1052
+ ### Scan an invoice (extract structured data from invoice)
733
1053
 
734
1054
  ```javascript
735
1055
 
736
- // you can only do scan of a file that is previously uploaded to totalum (see the upload file function)
737
- // then you can do scan of the file using the file name of the file uploaded
738
- const fileName = 'your_file_name.png'; // replace 'your_file_name' with the name of your file, replace .png with the extension of your file
739
- const file = yourFileBlob // replace yourFile with your file object binary blob (in blob format)
1056
+ // First upload the invoice file to Totalum
1057
+ const fileName = 'invoice.png';
1058
+ const file = yourFileBlob;
740
1059
  const formData = new FormData();
741
1060
  formData.append('file', file, fileName);
742
- const result = await totalumClient.files.uploadFile(formData);
743
- const fileNameId = result.data.data;
744
1061
 
1062
+ const uploadResult = await totalumClient.files.uploadFile(formData);
1063
+
1064
+ if (uploadResult.errors) {
1065
+ console.error('Error:', uploadResult.errors.errorMessage);
1066
+ return;
1067
+ }
1068
+
1069
+ const fileNameId = uploadResult.data;
1070
+
1071
+ // Scan the invoice to extract structured data
745
1072
  const result = await totalumClient.files.scanInvoice(fileNameId);
746
- const invoiceResult = result.data.data;
1073
+
1074
+ if (result.errors) {
1075
+ console.error('Error:', result.errors.errorMessage);
1076
+ return;
1077
+ }
1078
+
1079
+ const invoiceData = result.data.data;
1080
+ const metadata = result.data.metadata;
1081
+
1082
+ console.log('Invoice data:', invoiceData);
1083
+ console.log('Total amount:', invoiceData.totalAmountIncludingTaxes);
1084
+ console.log('Invoice number:', invoiceData.complete_invoice_number);
1085
+ console.log('Usage units:', metadata.usageUnits);
747
1086
 
748
1087
  ```
749
1088
 
750
- ### scan a document (get the details of a document)
1089
+ ### Scan a document (extract custom fields from document)
751
1090
 
752
1091
  ```javascript
753
1092
 
754
- // first upload the file to totalum
755
- const fileName = 'your_file_name.png'; // replace 'your_file_name' with the name of your file, replace .png with the extension of your file
756
- const file = yourFileBlob // replace yourFile with your file object binary blob (in blob format)
1093
+ // First upload the document
1094
+ const fileName = 'document.png';
1095
+ const file = yourFileBlob;
757
1096
  const formData = new FormData();
758
1097
  formData.append('file', file, fileName);
759
- const result = await totalumClient.files.uploadFile(formData);
760
- const fileNameId = result.data.data;
761
1098
 
762
- // define the json properties that you want to extract from the document
763
- // this is just an example, you can define your own properties following the JSON schema format, the api will return a json with the properties that you define here
764
- const properties = {
1099
+ const uploadResult = await totalumClient.files.uploadFile(formData);
1100
+
1101
+ if (uploadResult.errors) {
1102
+ console.error('Error:', uploadResult.errors.errorMessage);
1103
+ return;
1104
+ }
1105
+
1106
+ const fileNameId = uploadResult.data;
1107
+
1108
+ // Define the JSON schema for properties you want to extract
1109
+ const properties = {
765
1110
  "fecha": {
766
- "type": "string",
767
- "format": "date",
768
- "description": "introduce here your description for help api to extract this value"
1111
+ "type": "string",
1112
+ "format": "date",
1113
+ "description": "The date of the document"
769
1114
  },
770
1115
  "import": {
771
- "type": "number",
772
- "description": "the import"
1116
+ "type": "number",
1117
+ "description": "The total amount"
773
1118
  },
774
1119
  "currency": {
775
- "type": "string",
776
- "enum": ["EUR", "USD", "GBP", "OTHER"],
777
- "description": "if currency is not EUR, USD or GBP set OTHER"
1120
+ "type": "string",
1121
+ "enum": ["EUR", "USD", "GBP", "OTHER"],
1122
+ "description": "Currency code"
778
1123
  }
779
- }
1124
+ };
780
1125
 
781
1126
  const result = await totalumClient.files.scanDocument(fileNameId, properties);
782
- const documentResult = result.data.data;
1127
+
1128
+ if (result.errors) {
1129
+ console.error('Error:', result.errors.errorMessage);
1130
+ return;
1131
+ }
1132
+
1133
+ const documentData = result.data.data;
1134
+ const metadata = result.data.metadata;
1135
+
1136
+ console.log('Extracted data:', documentData);
1137
+ console.log('OCR text:', metadata.ocrFullResultText);
1138
+ console.log('Usage units:', metadata.usageUnits);
1139
+
1140
+ ```
1141
+
1142
+ ### Create PDF from HTML
1143
+
1144
+ Create a PDF directly from custom HTML:
1145
+
1146
+ ```javascript
1147
+
1148
+ const htmlContent = `
1149
+ <html>
1150
+ <body>
1151
+ <h1>Hello World</h1>
1152
+ <p>This is a PDF created from HTML</p>
1153
+ </body>
1154
+ </html>
1155
+ `;
1156
+
1157
+ const fileName = 'my-generated-pdf.pdf';
1158
+
1159
+ const result = await totalumClient.files.createPdfFromHtml({
1160
+ html: htmlContent,
1161
+ name: fileName
1162
+ });
1163
+
1164
+ if (result.errors) {
1165
+ console.error('Error:', result.errors.errorMessage);
1166
+ return;
1167
+ }
1168
+
1169
+ const generatedFileName = result.data;
1170
+ console.log('PDF generated:', generatedFileName);
1171
+
1172
+ // Link this PDF to a record
1173
+ const tableName = 'documents';
1174
+ const recordId = 'doc-record-123';
1175
+ const result2 = await totalumClient.crud.editRecordById(tableName, recordId, {
1176
+ 'pdfFile': { name: generatedFileName }
1177
+ });
1178
+
1179
+ ```
1180
+
1181
+ **Note:** The HTML is automatically encoded to base64 by the SDK before sending it to the API. Works in both Node.js and browser environments.
1182
+
1183
+
1184
+ ## Functions for send emails
1185
+
1186
+ ### Send a basic email
1187
+
1188
+ ```javascript
1189
+
1190
+ const emailPayload = {
1191
+ to: ['recipient@example.com'],
1192
+ subject: 'Your email subject',
1193
+ html: '<h1>Hello</h1><p>This is the email content in HTML</p>',
1194
+ };
1195
+
1196
+ const result = await totalumClient.email.sendEmail(emailPayload);
1197
+
1198
+ if (result.errors) {
1199
+ console.error('Error:', result.errors.errorMessage);
1200
+ return;
1201
+ }
1202
+
1203
+ console.log('Email sent successfully');
1204
+ console.log('Message ID:', result.data.messageId);
783
1205
 
784
1206
  ```
785
1207
 
1208
+ ### Send an email with all options
1209
+
1210
+ ```javascript
1211
+
1212
+ const emailPayload = {
1213
+ to: ['recipient1@example.com', 'recipient2@example.com'], // array of recipients
1214
+ subject: 'Your email subject',
1215
+ html: '<h1>Hello</h1><p>This is the email content in HTML</p>',
1216
+ fromName: 'Your Company Name', // optional: custom sender name
1217
+ cc: ['cc@example.com'], // optional: carbon copy recipients
1218
+ bcc: ['bcc@example.com'], // optional: blind carbon copy recipients
1219
+ replyTo: 'reply@example.com', // optional: reply-to address
1220
+ attachments: [ // optional: array of attachments (max 10, each up to 15MB)
1221
+ {
1222
+ filename: 'document.pdf',
1223
+ url: 'https://example.com/path/to/document.pdf',
1224
+ contentType: 'application/pdf' // optional
1225
+ },
1226
+ {
1227
+ filename: 'image.png',
1228
+ url: 'https://example.com/path/to/image.png',
1229
+ contentType: 'image/png' // optional
1230
+ }
1231
+ ]
1232
+ };
1233
+
1234
+ const result = await totalumClient.email.sendEmail(emailPayload);
1235
+
1236
+ if (result.errors) {
1237
+ console.error('Error:', result.errors.errorMessage);
1238
+ return;
1239
+ }
1240
+
1241
+ console.log('Email sent successfully');
1242
+ console.log('Message ID:', result.data.messageId);
1243
+
1244
+ ```
1245
+
1246
+ ### Send an email with files from Totalum storage
1247
+
1248
+ ```javascript
1249
+
1250
+ // First, get the download URL of the file uploaded to Totalum
1251
+ const fileNameId = 'your_file_name.pdf';
1252
+
1253
+ const fileUrlResult = await totalumClient.files.getDownloadUrl(fileNameId);
1254
+
1255
+ if (fileUrlResult.errors) {
1256
+ console.error('Error:', fileUrlResult.errors.errorMessage);
1257
+ return;
1258
+ }
1259
+
1260
+ const fileUrl = fileUrlResult.data;
1261
+
1262
+ // Then, send the email with the attachment
1263
+ const emailPayload = {
1264
+ to: ['recipient@example.com'],
1265
+ subject: 'Email with attachment from Totalum',
1266
+ html: '<h1>Hello</h1><p>Please find the attached document</p>',
1267
+ attachments: [
1268
+ {
1269
+ filename: 'document.pdf',
1270
+ url: fileUrl,
1271
+ contentType: 'application/pdf'
1272
+ }
1273
+ ]
1274
+ };
1275
+
1276
+ const result = await totalumClient.email.sendEmail(emailPayload);
1277
+
1278
+ if (result.errors) {
1279
+ console.error('Error:', result.errors.errorMessage);
1280
+ return;
1281
+ }
1282
+
1283
+ console.log('Email sent successfully');
1284
+
1285
+ ```
1286
+
1287
+ **Important notes:**
1288
+ - Maximum attachments: 10 per email
1289
+ - Maximum size per attachment: 15MB
1290
+ - All attachments must be provided as valid HTTP/HTTPS URLs
1291
+ - The SDK validates attachments before sending
1292
+
786
1293
 
787
1294
  ## Functions for call OpenAI API without need to have an OpenAI account
788
1295
 
@@ -791,15 +1298,22 @@ const documentResult = result.data.data;
791
1298
 
792
1299
  ```javascript
793
1300
 
794
- //body the openai completion body, more info here: https://platform.openai.com/docs/api-reference/completions/create
795
- const body={
796
- // see the openai api docs for more info
797
- }
1301
+ // See OpenAI API docs: https://platform.openai.com/docs/api-reference/completions/create
1302
+ const body = {
1303
+ model: 'gpt-3.5-turbo-instruct',
1304
+ prompt: 'Say hello in Spanish',
1305
+ max_tokens: 50
1306
+ };
798
1307
 
799
1308
  const result = await totalumClient.openai.createCompletion(body);
800
- const gptCompletion = result.data.data;
801
1309
 
802
- // returns the completion provided by openai api
1310
+ if (result.errors) {
1311
+ console.error('Error:', result.errors.errorMessage);
1312
+ return;
1313
+ }
1314
+
1315
+ const completion = result.data;
1316
+ console.log('Completion:', completion);
803
1317
 
804
1318
  ```
805
1319
 
@@ -807,21 +1321,26 @@ const gptCompletion = result.data.data;
807
1321
 
808
1322
  ```javascript
809
1323
 
810
- //body the openai chat completion body, more info here: https://platform.openai.com/docs/api-reference/chat/create
811
- const bodyExample={
812
- // see the openai api docs for more info
1324
+ // See OpenAI API docs: https://platform.openai.com/docs/api-reference/chat/create
1325
+ const body = {
813
1326
  messages: [
814
- {content: 'You are a math specialist assistant', role: 'system'},
815
- {content: 'how I can resolve a matrix', role: 'user'}
816
- //etc...
1327
+ { content: 'You are a math specialist assistant', role: 'system' },
1328
+ { content: 'How do I solve a matrix?', role: 'user' }
817
1329
  ],
818
1330
  model: 'gpt-3.5-turbo',
819
- max_tokens: 30,
1331
+ max_tokens: 150,
1332
+ };
1333
+
1334
+ const result = await totalumClient.openai.createChatCompletion(body);
1335
+
1336
+ if (result.errors) {
1337
+ console.error('Error:', result.errors.errorMessage);
1338
+ return;
820
1339
  }
821
1340
 
822
- const result = await totalumClient.openai.createChatCompletion(bodyExample);
823
- const chatCompletion = result.data.data;
824
- // returns the completion provided by openai api
1341
+ const chatCompletion = result.data;
1342
+ console.log('Response:', chatCompletion.choices[0].message.content);
1343
+ console.log('Tokens used:', chatCompletion.usage.total_tokens);
825
1344
 
826
1345
  ```
827
1346
 
@@ -829,16 +1348,28 @@ const chatCompletion = result.data.data;
829
1348
 
830
1349
  ```javascript
831
1350
 
832
- //body the openai chat completion body, more info here: https://platform.openai.com/docs/api-reference/chat/create
833
- const bodyExample={
834
- prompt:'your prompt',
835
- size: '256x256' | '512x512' | '1024x1024',
836
- fileName: 'file-name-of-file-saved.png' // CAUTION: if you use the same name for multiple images, the images will be overwritten
1351
+ // See OpenAI API docs: https://platform.openai.com/docs/api-reference/images
1352
+ const body = {
1353
+ prompt: 'A beautiful sunset over the mountains',
1354
+ size: '1024x1024', // '256x256' | '512x512' | '1024x1024'
1355
+ fileName: 'sunset_image.png' // CAUTION: reusing names will overwrite files
1356
+ };
1357
+
1358
+ const result = await totalumClient.openai.generateImage(body);
1359
+
1360
+ if (result.errors) {
1361
+ console.error('Error:', result.errors.errorMessage);
1362
+ return;
837
1363
  }
838
1364
 
839
- const result = await totalumClient.openai.generateImage(bodyExample);
840
- const imageCompletion = result.data.data;
841
- // returns the file name with the file generated by openai, if is not an url, you can download it using files.getDownloadUrl(imageCompletion);
1365
+ const imageFileName = result.data;
1366
+ console.log('Image generated:', imageFileName);
1367
+
1368
+ // Get download URL to view/download the image
1369
+ const urlResult = await totalumClient.files.getDownloadUrl(imageFileName);
1370
+ if (!urlResult.errors) {
1371
+ console.log('Image URL:', urlResult.data);
1372
+ }
842
1373
 
843
1374
  ```
844
1375