-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathwoqlClient.js
1892 lines (1783 loc) · 65.2 KB
/
woqlClient.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-disable camelcase */
/* eslint-disable no-param-reassign */
/* eslint-disable no-underscore-dangle */
/* eslint-disable no-unused-vars */
/// /@ts-check
const FormData = require('form-data');
const fs = require('fs');
const typedef = require('./typedef');
const CONST = require('./const');
const DispatchRequest = require('./dispatchRequest');
const ErrorMessage = require('./errorMessage');
const ConnectionConfig = require('./connectionConfig');
const WOQL = require('./woql');
const WOQLQuery = require('./query/woqlCore');
/**
* @license Apache Version 2
* @class
* @classdesc The core functionality of the TerminusDB javascript client is
* defined in the WOQLClient class - in the woqlClient.js file. This class provides
* methods which allow you to directly get and set all of the configuration and API
* endpoints of the client. The other parts of the WOQL core - connectionConfig.js
* and connectionCapabilities.js - are used by the client to store internal state - they
* should never have to be accessed directly. For situations where you want to communicate
* with a TerminusDB server API, the WOQLClient class is all you will need.
*/
class WOQLClient {
connectionConfig = null;
databaseList = [];
organizationList = [];
/**
* @constructor
* @param {string} serverUrl - the terminusdb server url
* @param {typedef.ParamsObj} [params] - an object with the connection parameters
* @example
* //to connect with your local terminusDB
* const client = new TerminusClient.WOQLClient(SERVER_URL,{user:"admin",key:"myKey"})
* async function getSchema() {
* client.db("test")
* client.checkout("dev")
* const schema = await client.getSchema()
* }
* //The client has an internal state which defines what
* //organization / database / repository / branch / ref it is currently attached to
*
* //to connect with your TerminusDB Cloud Instance
* const client = new TerminusClient.WOQLClient('SERVER_CLOUD_URL/mycloudTeam',
* {user:"[email protected]", organization:'mycloudTeam'})
*
* client.setApiKey(MY_ACCESS_TOKEN)
*
* //to get the list of all organization's databases
* async function callGetDatabases(){
* const dbList = await client.getDatabases()
* console.log(dbList)
* }
*
* async function getSchema() {
* client.db("test")
* client.checkout("dev")
* const schema = await client.getSchema()
* }
*/
constructor(serverUrl, params) {
this.connectionConfig = new ConnectionConfig(serverUrl, params);
}
}
/**
* set the api key to access the cloud resources
* @param {string} accessToken
*/
WOQLClient.prototype.setApiKey = function (accessToken) {
const currentAuth = this.connectionConfig.localAuth() || {};
currentAuth.key = accessToken;
currentAuth.type = 'apikey';
this.connectionConfig.setLocalAuth(currentAuth);
};
/**
* add extra headers to your request
* @param {object} customHeaders
* @returns {object}
*/
// eslint-disable-next-line consistent-return
WOQLClient.prototype.customHeaders = function (customHeaders) {
if (customHeaders) this._customHeaders = customHeaders;
else return this._customHeaders;
};
WOQLClient.prototype.CONST = CONST;
/**
* creates a copy of the client with identical internal state and context
* useful if we want to change context for a particular API call without changing
* the current client context
* @returns {WOQLClient} new client object with identical state to original but
* which can be manipulated independently
* @example
* let newClient = client.copy()
*/
WOQLClient.prototype.copy = function () {
const other = new WOQLClient(this.server());
// other.connection = this.connection //keep same connection meta data - shared by copy
other.connectionConfig = this.connectionConfig.copy(); // new copy of current connection data
other.databaseList = this.databaseList;
return other;
};
/**
* Gets the current connected server url
* it can only be set creating a new WOQLCLient instance
* @returns {string}
*/
WOQLClient.prototype.server = function () {
return this.connectionConfig.serverURL();
};
/**
* Retrieve the URL of the server’s API base that we are currently connected to
* @returns {string} the URL of the TerminusDB server api endpoint we are connected
* to (typically server() + “api/”)
* @example
* let api_url = client.api()
*/
WOQLClient.prototype.api = function () {
return this.connectionConfig.apiURL();
};
/**
* Gets/Sets the client’s internal organization context value, if you change the organization
* name the databases list will be set to empty
* @param {string | boolean} [orgId] the organization id to set the context to
* @returns {string | boolean}
* @example
* client.organization("admin")
*/
WOQLClient.prototype.organization = function (orgId) {
if (typeof orgId !== 'undefined') {
this.connectionConfig.setOrganization(orgId);
// we have to reset the databases list
this.databases([]);
}
return this.connectionConfig.organization();
};
/**
* Checks if a database exists
*
* Returns true if a DB exists and false if it doesn't. Other results
* throw an exception.
* @param {string} [orgName] the organization id to set the context to
* @param {string} [dbName] the db name to set the context to
* @returns {Promise}
* @example
* async function executeIfDatabaseExists(f){
* const hasDB = await client.hasDatabase("admin", "testdb")
* if (hasDB) {
* f()
* }
* }
*/
WOQLClient.prototype.hasDatabase = async function (orgName, dbName) {
const dbCheckUrl = `${this.connectionConfig.apiURL()}db/${orgName}/${dbName}`;
return new Promise((resolve, reject) => {
this.dispatch(CONST.HEAD, dbCheckUrl).then((req) => {
resolve(true);
}).catch((err) => {
if (err.status === 404) {
resolve(false);
} else {
reject(err);
}
});
});
};
/**
* Gets the organization's databases list.
*
* If no organization has been set up, the function throws an exception
* @returns {Promise}
* @example
* async function callGetDatabases(){
* const dbList = await client.getDatabases()
* console.log(dbList)
* }
*/
WOQLClient.prototype.getDatabases = async function () {
// return response
if (!this.connectionConfig.organization()) {
throw new Error('You need to set the organization name');
}
// when we will have the end point to get the databases only for the current organization
// we'll change this call
await this.getUserOrganizations();
const dbs = this.userOrganizations().find(
(element) => element.name === this.connectionConfig.organization(),
);
const dbList = dbs && dbs.databases ? dbs.databases : [];
this.databases(dbList);
return dbList;
};
/**
* Set/Get the organization's databases list (id, label, comment) that the current
* user has access to on the server.
* @param {array} [dbList] a list of databases the user has access to on the server, each having:
* @returns {array} the organization's databases list
* @example
* //to get the list of all organization's databases
* async function callGetDatabases(){
* await client.getDatabases()
* console.log(client.databases())
* }
*
*/
WOQLClient.prototype.databases = function (dbList) {
if (dbList) this.databaseList = dbList;
return this.databaseList || [];
};
/**
* Gets the current user object as returned by the connect capabilities response
* user has fields: [id, name, notes, author]
* @returns {Object}
*/
WOQLClient.prototype.user = function () {
// this is the locacal
return this.connectionConfig.user();
};
/**
* @desription Gets the user's organization id
* @returns {string} the user organization name
*/
// this is something that need review
WOQLClient.prototype.userOrganization = function () {
return this.user();
};
/**
* Gets the database's details
* @param {string} [dbName] - the datbase name
* @returns {object} the database description object
*/
WOQLClient.prototype.databaseInfo = function (dbName) {
// const dbIdVal = dbId || this.db();
// const orgIdVal = orgId || this.organization()
const database = this.databases().find((element) => element.name === dbName);
return database || {};
};
/**
* Sets / Gets the current database
* @param {string} [dbId] - the database id to set the context to
* @returns {string|boolean} - the current database or false
* @example
* client.db("mydb")
*/
WOQLClient.prototype.db = function (dbId) {
if (typeof dbId !== 'undefined') {
this.connectionConfig.setDB(dbId);
}
return this.connectionConfig.dbid;
};
/**
*Sets the internal client context to allow it to talk to the server’s internal system database
*
*/
WOQLClient.prototype.setSystemDb = function () {
this.db(this.connectionConfig.system_db);
};
/**
* Gets / Sets the client’s internal repository context value (defaults to ‘local’)
* @param {typedef.RepoType | string} [repoId] - default value is local
* @returns {string} the current repository id within the client context
* @example
* client.repo("origin")
*/
WOQLClient.prototype.repo = function (repoId) {
if (typeof repoId !== 'undefined') {
this.connectionConfig.setRepo(repoId);
}
return this.connectionConfig.repo();
};
/**
* Gets/Sets the client’s internal branch context value (defaults to ‘main’)
* @param {string} [branchId] - the branch id to set the context to
* @returns {string} the current branch id within the client context
*/
WOQLClient.prototype.checkout = function (branchId) {
if (typeof branchId !== 'undefined') {
this.connectionConfig.setBranch(branchId);
}
return this.connectionConfig.branch();
};
/**
* Sets / gets the current ref pointer (pointer to a commit within a branch)
* Reference ID or Commit ID are unique hashes that are created whenever a new commit is recorded
* @param {string} [commitId] - the reference ID or commit ID
* @returns {string|boolean} the current commit id within the client context
* @example
* client.ref("mkz98k2h3j8cqjwi3wxxzuyn7cr6cw7")
*/
WOQLClient.prototype.ref = function (commitId) {
if (typeof commitId !== 'undefined') {
this.connectionConfig.setRef(commitId);
}
return this.connectionConfig.ref();
};
/**
* Sets/Gets set the database basic connection credential
* @param {typedef.CredentialObj} [newCredential]
* @returns {typedef.CredentialObj | boolean}
* @example
* client.localAuth({user:"admin","key":"mykey","type":"basic"})
*/
WOQLClient.prototype.localAuth = function (newCredential) {
if (typeof newCredential !== 'undefined') {
this.connectionConfig.setLocalAuth(newCredential);
}
return this.connectionConfig.localAuth();
};
/**
* Use {@link #localAuth} instead.
* @deprecated
*/
WOQLClient.prototype.local_auth = WOQLClient.prototype.localAuth;
/**
* Sets/Gets the jwt token for authentication
* we need this to connect 2 terminusdb server to each other for push, pull, clone actions
* @param {typedef.CredentialObj} [newCredential]
* @returns {typedef.CredentialObj | boolean}
* @example
* client.remoteAuth({"key":"dhfmnmjglkrelgkptohkn","type":"jwt"})
*/
WOQLClient.prototype.remoteAuth = function (newCredential) {
if (typeof newCredential !== 'undefined') {
this.connectionConfig.setRemoteAuth(newCredential);
}
return this.connectionConfig.remoteAuth();
};
/**
* Use {@link #remoteAuth} instead.
* @deprecated
*/
WOQLClient.prototype.remote_auth = WOQLClient.prototype.remoteAuth;
/**
* Gets the string that will be written into the commit log for the current user
* @returns {string} the current user
* @example
* client.author()
*/
WOQLClient.prototype.author = function () {
// we have to review this with is the author in local and remote
// was a old functionality
// if (ignoreJwt) {
// this.connectionConfig.user(ignoreJwt)
// }
return this.connectionConfig.user();
};
/**
* @param {typedef.ParamsObj} params - a object with connection params
* @example sets several of the internal state values in a single call
* (similar to connect, but only sets internal client state, does not communicate with server)
* client.set({key: "mypass", branch: "dev", repo: "origin"})
*/
WOQLClient.prototype.set = function (params) {
this.connectionConfig.update(params);
};
/**
* Generates a resource string for the required context
* of the current context for "commits" "meta" "branch" and "ref" special resources
* @param {typedef.ResourceType} resourceType - the type of resource string that is required - one
* of “db”, “meta”, “repo”, “commits”, “branch”, “ref”
* @param {string} [resourceId] - can be used to specify a specific branch / ref - if not supplied
* the current context will be used
* @returns {string} a resource string for the desired context
* @example
* const branch_resource = client.resource("branch")
*/
// eslint-disable-next-line consistent-return
WOQLClient.prototype.resource = function (resourceType, resourceId) {
let base = `${this.organization()}/${this.db()}/`;
if (resourceType === 'db') return base;
if (resourceType === 'meta') return `${base}_meta`;
base += `${this.repo()}`;
if (resourceType === 'repo') return base;
if (resourceType === 'commits') return `${base}/_commits`;
const resourceIdValue = resourceId || (resourceType === 'ref' ? this.ref() : this.checkout());
if (resourceType === 'branch') return `${base}/branch/${resourceIdValue}`;
if (resourceType === 'ref') return `${base}/commit/${resourceIdValue}`;
};
/**
* You can call this to get the server info or override the start params
* configuration, this.connectionConfig.server will be used if present,
* or the promise will be rejected.
*
* @deprecated
*
* @param {typedef.ParamsObj} [params] - TerminusDB Server connection parameters
* @returns {Promise} the connection capabilities response object or an error object
* @example
* client.connect()
*/
WOQLClient.prototype.connect = function (params) {
if (params) this.connectionConfig.update(params);
// unset the current server setting until successful connect
return this.dispatch(CONST.GET, this.connectionConfig.apiURLInfo()).then((response) => response);
};
/**
* Creates a new database in TerminusDB server
* @param {string} dbId - The id of the new database to be created
* @param {typedef.DbDetails} dbDetails - object containing details about the database to be created
* @param {string} [orgId] - optional organization id - if absent default local organization
* id is used
* @returns {Promise} A promise that returns the call response object, or an Error if rejected.
* @example
* //remember set schema:true if you need to add a schema graph
* client.createDatabase("mydb", {label: "My Database", comment: "Testing", schema: true})
*/
// maybe we can pass only the detailObj it is have inside the dbid and org
WOQLClient.prototype.createDatabase = function (dbId, dbDetails, orgId) {
if (orgId) this.organization(orgId);
// console.log("createDatabase", orgId)
if (dbId) {
this.db(dbId);
// to be review
// console.log('____remoteURL_BFF__', this.connectionConfig.dbURL())
return this.dispatch(CONST.POST, this.connectionConfig.dbURL(), dbDetails);
}
const errmsg = `Create database parameter error - you must specify a valid database id - ${dbId} is invalid`;
return Promise.reject(
new Error(ErrorMessage.getInvalidParameterMessage(CONST.CREATE_DATABASE, errmsg)),
);
};
/**
* Update a database in TerminusDB server
* @param {typedef.DbDoc} dbDoc - object containing details about the database to be updated
* @returns {Promise} A promise that returns the call response object, or an Error if rejected.
* @example
* client.updateDatabase({id: "mydb", label: "My Database", comment: "Testing"})
*/
WOQLClient.prototype.updateDatabase = function (dbDoc) {
const dbid = dbDoc.id || this.db();
this.organization(dbDoc.organization || this.organization());
if (dbid) {
this.db(dbid);
return this.dispatch(CONST.PUT, this.connectionConfig.dbURL(), dbDoc);
}
const errmsg = `Update database error - you must specify a valid database id - ${dbid} is invalid`;
return Promise.reject(
new Error(ErrorMessage.getInvalidParameterMessage(CONST.UPDATE_DATABASE, errmsg)),
);
};
/**
* Deletes a database from a TerminusDB server
* @param {string} dbId The id of the database to be deleted
* @param {string} [orgId] the id of the organization to which the database belongs
* (in desktop use, this will always be “admin”)
* @param {boolean} [force]
* @returns {Promise} A promise that returns the call response object, or an Error if rejected.
* @example
* client.deleteDatabase("mydb")
*/
WOQLClient.prototype.deleteDatabase = function (dbId, orgId, force) {
const orgIdValue = orgId || this.organization();
this.organization(orgIdValue);
const payload = force ? { force: true } : null;
if (dbId && this.db(dbId)) {
return this.dispatch(CONST.DELETE, this.connectionConfig.dbURL(), payload);
}
const errmsg = `Delete database parameter error - you must specify a valid database id - ${dbId} is invalid`;
return Promise.reject(
new Error(ErrorMessage.getInvalidParameterMessage(CONST.DELETE, errmsg)),
);
};
/**
* Retrieve the contents of a graph within a TerminusDB as triples, encoded in
* the turtle (ttl) format
* @param {typedef.GraphType} graphType - type of graph to get triples from,
* either “instance” or “schema”
* @returns {Promise} A promise that returns the call response object (with
* the contents being a string representing a set of triples in turtle (ttl) format),
* or an Error if rejected.
* @example
* const turtle = await client.getTriples("schema", "alt")
*/
WOQLClient.prototype.getTriples = function (graphType) {
if (graphType) {
return this.dispatch(
CONST.GET,
this.connectionConfig.triplesURL(graphType),
);
}
const errmsg = 'Get triples parameter error - you must specify a valid graph type (inference, instance, schema), and graph id';
return Promise.reject(
new Error(ErrorMessage.getInvalidParameterMessage(CONST.GET, errmsg)),
);
};
/**
* Replace the contents of the specified graph with the passed triples encoded
* in the turtle (ttl) format
* @param {string} graphType - type of graph |instance|schema|inference|
* @param {string} turtle - string encoding triples in turtle (ttl) format
* @param {string} commitMsg - Textual message describing the reason for the update
* @returns {Promise} A promise that returns the call response object, or an Error if rejected.
* @example
* client.updateTriples("schema", "alt", turtle_string, "dumping triples to graph alt")
*/
WOQLClient.prototype.updateTriples = function (graphType, turtle, commitMsg) {
if (commitMsg && turtle && graphType) {
const commit = this.generateCommitInfo(commitMsg);
commit.turtle = turtle;
return this.dispatch(
CONST.UPDATE_TRIPLES,
this.connectionConfig.triplesURL(graphType),
commit,
);
}
const errmsg = 'Update triples parameter error - you must specify a valid graph id, graph type, turtle contents and commit message';
return Promise.reject(
new Error(ErrorMessage.getInvalidParameterMessage(CONST.UPDATE_TRIPLES, errmsg)),
);
};
/**
* Appends the passed turtle to the contents of a graph
* @param {string} graphType type of graph |instance|schema|inference|
* @param {string} turtle is a valid set of triples in turtle format (OWL)
* @param {string} commitMsg Textual message describing the reason for the update
* @returns {Promise} A promise that returns the call response object, or an Error if rejected.
*/
WOQLClient.prototype.insertTriples = function (graphType, turtle, commitMsg) {
if (commitMsg && turtle && graphType) {
const commit = this.generateCommitInfo(commitMsg);
commit.turtle = turtle;
return this.dispatch(
CONST.INSERT_TRIPLES,
this.connectionConfig.triplesURL(graphType),
commit,
);
}
const errmsg = 'Update triples parameter error - you must specify a valid graph id, graph type, turtle contents and commit message';
return Promise.reject(
new Error(ErrorMessage.getInvalidParameterMessage(CONST.INSERT_TRIPLES, errmsg)),
);
};
/**
* Sends a message to the server
* @param {string} message - textual string
* @param {string} [pathname] - a server path to send the message to
* @returns {Promise} A promise that returns the call response object, or an Error if rejected.
*/
WOQLClient.prototype.message = function (message, pathname) {
let url = this.api();
url += pathname ? this.api() + pathname : 'message';
return this.dispatch(CONST.GET, url, message).then((response) => response);
};
/**
* Sends an action to the server
* @param {string} actionName - structure of the action
* @param {object} [payload] - a request body call
* @returns {Promise} A promise that returns the call response object, or an Error if rejected.
*/
WOQLClient.prototype.action = function (actionName, payload) {
const url = `${this.api()}action/${actionName}`;
return this.dispatch(CONST.ACTION, url, payload).then((response) => response);
};
/**
* Gets TerminusDB Server Information
* @returns {Promise} A promise that returns the call response object, or an Error if rejected.
* @example
* client.info()
*/
WOQLClient.prototype.info = function () {
const url = `${this.api()}info`;
return this.dispatch(CONST.GET, url).then((response) => response);
};
// Get Resource objects from WOQL query
function getResourceObjects(queryObject, result_array) {
if (queryObject instanceof Array) {
for (let i = 0; i < queryObject.length; i += 1) {
getResourceObjects(queryObject[i], result_array);
}
} else {
const keys = Object.keys(queryObject);
for (let i = 0; i < keys.length; i += 1) {
if (keys[i] === 'resource') {
if (queryObject[keys[i]]['@type'] && queryObject[keys[i]]['@type'] === 'QueryResource') {
result_array.push(queryObject[keys[i]]);
}
}
if (queryObject[keys[i]] instanceof Object || queryObject[keys[i]] instanceof Array) {
getResourceObjects(queryObject[keys[i]], result_array);
}
}
}
}
/**
* Executes a WOQL query on the specified database and returns the results
* @param {WOQLQuery} woql - an instance of the WOQLQuery class
* @param {string} [commitMsg] - a message describing the reason for the change that will
* be written into the commit log (only relevant if the query contains an update)
* @param {boolean} [allWitnesses]
* @param {string} [lastDataVersion] the last data version tracking id.
* @param {boolean} [getDataVersion] If true the function will return object having result
* and dataVersion.
* @param {Array<NamedResourceData>} [resources] csv resources supplied as strings
* @returns {Promise} A promise that returns the call response object or object having *result*
* and *dataVersion* object if ***getDataVersion*** parameter is true, or an Error if rejected.
* @example
* const result = await client.query(WOQL.star())
*/
WOQLClient.prototype.query = function (woql, commitMsg, allWitnesses, lastDataVersion = '', getDataVersion = false, resources = []) {
allWitnesses = allWitnesses || false;
commitMsg = commitMsg || 'Commit generated with javascript client without message';
const providedResourcesLookupMap = (resources ?? [])
.reduce((map, res) => ({ ...map, [(res.filename).split('/').pop()]: res.data }), {});
if (woql && woql.json && (!woql.containsUpdate() || commitMsg)) {
const doql = woql.containsUpdate() ? this.generateCommitInfo(commitMsg) : {};
doql.query = woql.json();
let postBody;
const resourceObjects = [];
getResourceObjects(doql.query, resourceObjects);
if (resourceObjects.length > 0) {
const formData = new FormData();
resourceObjects.forEach((resourceObject) => {
const providedResourceInsteadOfFile = typeof resourceObject.source.post === 'string'
? providedResourcesLookupMap?.[resourceObject.source.post.split('/').pop()]
: undefined;
const fileName = resourceObject.source.post.split('/').pop();
if (providedResourceInsteadOfFile) {
formData.append('file', providedResourceInsteadOfFile, { filename: fileName, contentType: 'application/csv' });
} else {
formData.append('file', fs.createReadStream(resourceObject.source.post));
}
resourceObject.source.post = fileName;
});
formData.append('payload', Buffer.from(JSON.stringify(doql)), { filename: 'body.json', contentType: 'application/json' });
this.customHeaders(formData.getHeaders());
postBody = formData;
} else {
postBody = doql;
}
if (allWitnesses) doql.all_witnesses = true;
if (typeof lastDataVersion === 'string' && lastDataVersion !== '') {
this.customHeaders({ 'TerminusDB-Data-Version': lastDataVersion });
}
// eslint-disable-next-line max-len
return this.dispatch(CONST.WOQL_QUERY, this.connectionConfig.queryURL(), postBody, getDataVersion);
}
let errmsg = 'WOQL query parameter error';
if (woql && woql.json && woql.containsUpdate() && !commitMsg) {
errmsg += ' - you must include a textual commit message to perform this update';
} else {
errmsg += ' - you must specify a valid WOQL Query';
}
return Promise.reject(
new Error(ErrorMessage.getInvalidParameterMessage(CONST.WOQL_QUERY, errmsg)),
);
};
/**
* Creates a new branch with a TerminusDB database, starting from the current context of
* the client (branch / ref)
* @param {string} newBranchId - local identifier of the new branch the ID of the new branch
* to be created
* @param {boolean} [isEmpty] - if isEmpty is true it will create a empty branch.
* @returns {Promise} A promise that returns the call response object, or an Error if rejected.
* @example
* client.branch("dev")
*/
WOQLClient.prototype.branch = function (newBranchId, isEmpty) {
if (newBranchId) {
let source = this.ref()
? { origin: `${this.organization()}/${this.db()}/${this.repo()}/commit/${this.ref()}` }
: {
origin: `${this.organization()}/${this.db()}/${this.repo()}/branch/${this.checkout()}`,
};
if (isEmpty && isEmpty === true) {
// @ts-ignore
source = {};
}
return this.dispatch(CONST.BRANCH, this.connectionConfig.branchURL(newBranchId), source);
}
const errmsg = 'Branch parameter error - you must specify a valid new branch id';
return Promise.reject(new Error(ErrorMessage.getInvalidParameterMessage(CONST.BRANCH, errmsg)));
};
/**
* Squash branch commits
* @param {string} branchId - local identifier of the new branch
* @param {string} commitMsg - Textual message describing the reason for the update
* @returns {Promise} A promise that returns the call response object, or an Error if rejected.
*/
WOQLClient.prototype.squashBranch = function (branchId, commitMsg) {
if (commitMsg && branchId) {
const commit = this.generateCommitInfo(commitMsg);
return this.dispatch(
CONST.SQUASH_BRANCH,
this.connectionConfig.squashBranchURL(branchId),
commit,
);
}
const errmsg = 'Branch parameter error - you must specify a valid new branch id and a commit message';
return Promise.reject(
new Error(ErrorMessage.getInvalidParameterMessage(CONST.SQUASH_BRANCH, errmsg)),
);
};
/**
* Reset branch to a commit id, Reference ID or Commit ID are unique hashes that are
* created whenever a new commit is recorded
* @param {string} branchId - local identifier of the new branch
* @param {string} commitId - Reference ID or Commit ID
* @returns {Promise} A promise that returns the call response object, or an Error if rejected.
*/
WOQLClient.prototype.resetBranch = function (branchId, commitId) {
if (commitId && branchId) {
// eslint-disable-next-line camelcase
return this.dispatch(
CONST.RESET_BRANCH,
this.connectionConfig.resetBranchUrl(branchId),
{ commit_descriptor: commitId },
);
}
const errmsg = 'Branch parameter error - you must specify a valid new branch id and a commit message';
return Promise.reject(
new Error(ErrorMessage.getInvalidParameterMessage(CONST.RESET_BRANCH, errmsg)),
);
};
/**
* Optimize db branch
* @param {string} branchId - local identifier of the new branch
* @returns {Promise} A promise that returns the call response object, or an Error if rejected.
*/
WOQLClient.prototype.optimizeBranch = function (branchId) {
if (branchId) {
return this.dispatch(
CONST.OPTIMIZE_SYSTEM,
this.connectionConfig.optimizeBranchUrl(branchId),
{},
);
}
const errmsg = 'Branch parameter error - you must specify a valid branch id';
return Promise.reject(new Error(ErrorMessage.getInvalidParameterMessage(CONST.BRANCH, errmsg)));
};
/**
* Deletes a branch from database
* @param {string} branchId - local identifier of the branch
* @returns {Promise} A promise that returns the call response object, or an Error if rejected.
*/
WOQLClient.prototype.deleteBranch = function (branchId) {
if (branchId) {
return this.dispatch(CONST.DELETE, this.connectionConfig.branchURL(branchId));
}
const errmsg = 'Branch parameter error - you must specify a valid new branch id';
return Promise.reject(new Error(ErrorMessage.getInvalidParameterMessage(CONST.BRANCH, errmsg)));
};
/**
* Pull changes from a branch on a remote database to a branch on a local database
* @param {typedef.RemoteRepoDetails} remoteSourceRepo - an object describing the source of the pull
* @returns {Promise} A promise that returns the call response object, or an Error if rejected.
* @example
* client.pull({remote: "origin", remote_branch: "main", message: "Pulling from remote"})
*/
WOQLClient.prototype.pull = function (remoteSourceRepo) {
const rc_args = this.prepareRevisionControlArgs(remoteSourceRepo);
if (rc_args && rc_args.remote && rc_args.remote_branch) {
return this.dispatch(CONST.PULL, this.connectionConfig.pullURL(), rc_args);
}
const errmsg = 'Pull parameter error - you must specify a valid remote source and branch to pull from';
return Promise.reject(new Error(ErrorMessage.getInvalidParameterMessage(CONST.PULL, errmsg)));
};
/**
* Fetch updates to a remote database to a remote repository with the local database
* @param {string} remoteId - if of the remote to fetch (eg: 'origin')
* @returns {Promise} A promise that returns the call response object, or an Error if rejected.
*/
WOQLClient.prototype.fetch = function (remoteId) {
return this.dispatch(CONST.FETCH, this.connectionConfig.fetchURL(remoteId));
};
/**
* Push changes from a branch on a local database to a branch on a remote database
* @param {typedef.RemoteRepoDetails} remoteTargetRepo - an object describing the target of the push
* {remote: "origin", "remote_branch": "main", "author": "admin", "message": "message"}
* @returns {Promise} A promise that returns the call response object, or an Error if rejected.
* @example
* client.push({remote: "origin", remote_branch: "main", message: "Pulling from remote"})
*/
WOQLClient.prototype.push = function (remoteTargetRepo) {
const rc_args = this.prepareRevisionControlArgs(remoteTargetRepo);
if (rc_args && rc_args.remote && rc_args.remote_branch) {
return this.dispatch(CONST.PUSH, this.connectionConfig.pushURL(), rc_args);
}
const errmsg = 'Push parameter error - you must specify a valid remote target';
return Promise.reject(new Error(ErrorMessage.getInvalidParameterMessage(CONST.PUSH, errmsg)));
};
/**
* Merges the passed branch into the current one using the rebase operation
* @param {object} rebaseSource - json describing the source branch to be used as a base
* @returns {Promise} A promise that returns the call response object, or an Error if rejected.
* @example
* //from the branch head
* client.rebase({rebase_from: "admin/db_name/local/branch/branch_name", message:
* "Merging from dev")
* //or from a commit id
* client.rebase({rebase_from: "admin/db_name/local/commit/9w8hk3y6rb8tjdy961de3i536ntkqd8",
* message: "Merging from dev")
*/
WOQLClient.prototype.rebase = function (rebaseSource) {
const rc_args = this.prepareRevisionControlArgs(rebaseSource);
if (rc_args && rc_args.rebase_from) {
return this.dispatch(CONST.REBASE, this.connectionConfig.rebaseURL(), rc_args);
}
const errmsg = 'Rebase parameter error - you must specify a valid rebase source to rebase from';
return Promise.reject(
new Error(ErrorMessage.getInvalidParameterMessage(CONST.REBASE, errmsg)),
);
};
/**
* Reset the current branch HEAD to the specified commit path
* @param {string} commitPath - The commit path to set the current branch to
* @returns {Promise} A promise that returns the call response object, or an Error if rejected.
*/
WOQLClient.prototype.reset = function (commitPath) {
return this.dispatch(CONST.RESET, this.connectionConfig.resetURL(), {
commit_descriptor: commitPath,
});
};
/**
* Clones a remote repo and creates a local copy
* @param {typedef.CloneSourceDetails} cloneSource - object describing the source branch
* to be used as a base
* @param {string} newDbId - id of the new cloned database on the local server
* @param {string} [orgId] - id of the local organization that the new cloned database
* will be created in (in desktop mode this is always “admin”)
* @returns {Promise} A promise that returns the call response object, or an Error if rejected.
* @example
* client.clonedb({remote_url: "https://my.terminusdb.com/myorg/mydb", label "Cloned DB", comment: "Cloned from mydb"}, newid: "mydb")
*/
WOQLClient.prototype.clonedb = function (cloneSource, newDbId, orgId) {
orgId = orgId || this.user_organization();
this.organization(orgId);
const rc_args = this.prepareRevisionControlArgs(cloneSource);
if (newDbId && rc_args && rc_args.remote_url) {
return this.dispatch(CONST.CLONE, this.connectionConfig.cloneURL(newDbId), rc_args);
}
const errmsg = 'Clone parameter error - you must specify a valid id for the cloned database';
return Promise.reject(new Error(ErrorMessage.getInvalidParameterMessage(CONST.BRANCH, errmsg)));
};
/**
* Common request dispatch function
* @property {string} action - the action name
* @property {string} apiUrl - the server call endpoint
* @property {object} [payload] - the post body
* @property {boolean} [getDataVersion] - If true return response with data version
* @property {boolean} [compress] - If true, compress the data if it is bigger than 1024 bytes
* @returns {Promise} A promise that returns the call response object, or an Error if rejected.
*/
WOQLClient.prototype.dispatch = function (
action,
apiUrl,
payload,
getDataVersion,
compress = false,
) {
if (!apiUrl) {
return Promise.reject(
new Error(
ErrorMessage.getInvalidParameterMessage(
action,
this.connectionConfig.connection_error,
),
),
);
}
// I have to review this I don't want a call everytime
/* if(this.connectionConfig.tokenParameter){
const param = this.connectionConfig.tokenParameter
axios.post(param.url,param.options).then(result=>result.data).then(data=>{
if(data.access_token){
console.log("ACCESS_TOKEN",data.access_token)
this.localAuth({"key":data.access_token,"type":"jwt"})
}
return DispatchRequest(
apiUrl,
action,
payload,
this.localAuth(),
this.remoteAuth(),
this.customHeaders(),
)
})
}else{ */
return DispatchRequest(
apiUrl,
action,
payload,
this.localAuth(),
this.remoteAuth(),
this.customHeaders(),
getDataVersion,
compress,
);
// }
};
/**
* Generates the json structure for commit messages
* @param {string} msg - textual string describing reason for the change
* @param {string} [author] - optional author id string - if absent current user id will be used
* @returns {object}
*/
WOQLClient.prototype.generateCommitInfo = function (msg, author) {
if (!author) {
author = this.author();
}
const commitInfo = { commit_info: { author, message: msg } };
return commitInfo;
};
/**
* Generates the json structure for commit descriptor
* @param {string} commitId - a valid commit id o
*/
WOQLClient.prototype.generateCommitDescriptor = function (commitId) {
const cd = this.connectionConfig.commitDescriptorUrl(commitId);
const ci = { commit_descriptor: cd };
return ci;
};
/**
* Adds an author string (from the user object returned by connect) to the commit message.
* @param {object} [rc_args]
* @returns {object | boolean}
*/
WOQLClient.prototype.prepareRevisionControlArgs = function (rc_args) {
if (!rc_args || typeof rc_args !== 'object') return false;
if (!rc_args.author) rc_args.author = this.author();
return rc_args;
};
/**
* to add a new document or a list of new documents into the instance or the schema graph.
* @param {object} json
* @param {typedef.DocParamsPost} [params] - the post parameters {@link #typedef.DocParamsPost}