forked from canada-ca/tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.js
More file actions
1674 lines (1674 loc) · 52.9 KB
/
Copy pathdatabase.js
File metadata and controls
1674 lines (1674 loc) · 52.9 KB
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
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Database = exports.isArangoDatabase = void 0;
const analyzer_1 = require("./analyzer");
const aql_1 = require("./aql");
const collection_1 = require("./collection");
const connection_1 = require("./connection");
const cursor_1 = require("./cursor");
const error_1 = require("./error");
const graph_1 = require("./graph");
const codes_1 = require("./lib/codes");
const multipart_1 = require("./lib/multipart");
const route_1 = require("./route");
const transaction_1 = require("./transaction");
const view_1 = require("./view");
/**
* Indicates whether the given value represents a {@link Database}.
*
* @param database - A value that might be a database.
*/
function isArangoDatabase(database) {
return Boolean(database && database.isArangoDatabase);
}
exports.isArangoDatabase = isArangoDatabase;
/**
* @internal
* @hidden
*/
function coerceTransactionCollections(collections) {
if (typeof collections === "string") {
return { write: [collections] };
}
if (Array.isArray(collections)) {
return { write: collections.map(collection_1.collectionToString) };
}
if (collection_1.isArangoCollection(collections)) {
return { write: collection_1.collectionToString(collections) };
}
const cols = {};
if (collections) {
if (collections.allowImplicit !== undefined) {
cols.allowImplicit = collections.allowImplicit;
}
if (collections.read) {
cols.read = Array.isArray(collections.read)
? collections.read.map(collection_1.collectionToString)
: collection_1.collectionToString(collections.read);
}
if (collections.write) {
cols.write = Array.isArray(collections.write)
? collections.write.map(collection_1.collectionToString)
: collection_1.collectionToString(collections.write);
}
if (collections.exclusive) {
cols.exclusive = Array.isArray(collections.exclusive)
? collections.exclusive.map(collection_1.collectionToString)
: collection_1.collectionToString(collections.exclusive);
}
}
return cols;
}
/**
* An object representing a single ArangoDB database. All arangojs collections,
* cursors, analyzers and so on are linked to a `Database` object.
*/
class Database {
// There's currently no way to hide a single overload from typedoc
// /**
// * @internal
// * @hidden
// */
// constructor(database: Database, name?: string);
constructor(configOrDatabase = {}, name) {
this._analyzers = new Map();
this._collections = new Map();
this._graphs = new Map();
this._views = new Map();
if (isArangoDatabase(configOrDatabase)) {
const connection = configOrDatabase._connection;
const databaseName = name || configOrDatabase.name;
this._connection = connection;
this._name = databaseName;
const database = connection.database(databaseName);
if (database)
return database;
}
else {
const config = configOrDatabase;
const { databaseName, ...options } = typeof config === "string" || Array.isArray(config)
? { databaseName: name, url: config }
: config;
this._connection = new connection_1.Connection(options);
this._name = databaseName || "_system";
}
}
//#region misc
/**
* @internal
*
* Indicates that this object represents an ArangoDB database.
*/
get isArangoDatabase() {
return true;
}
/**
* Name of the ArangoDB database this instance represents.
*/
get name() {
return this._name;
}
/**
* Fetches version information from the ArangoDB server.
*
* @param details - If set to `true`, additional information about the
* ArangoDB server will be available as the `details` property.
*
* @example
* ```js
* const db = new Database();
* const version = await db.version();
* // the version object contains the ArangoDB version information.
* // license: "community" or "enterprise"
* // version: ArangoDB version number
* // server: description of the server
* ```
*/
version(details) {
return this.request({
method: "GET",
path: "/_api/version",
qs: { details },
}, (res) => res.body);
}
/**
* Returns a new {@link Route} instance for the given path (relative to the
* database) that can be used to perform arbitrary HTTP requests.
*
* @param path - The database-relative URL of the route. Defaults to the
* database API root.
* @param headers - Default headers that should be sent with each request to
* the route.
*
* @example
* ```js
* const db = new Database();
* const myFoxxService = db.route("my-foxx-service");
* const response = await myFoxxService.post("users", {
* username: "admin",
* password: "hunter2"
* });
* // response.body is the result of
* // POST /_db/_system/my-foxx-service/users
* // with JSON request body '{"username": "admin", "password": "hunter2"}'
* ```
*/
route(path, headers) {
return new route_1.Route(this, path, headers);
}
request({ absolutePath = false, basePath, ...opts }, transform) {
if (!absolutePath) {
basePath = `/_db/${this.name}${basePath || ""}`;
}
return this._connection.request({ basePath, ...opts }, transform);
}
/**
* Updates the URL list by requesting a list of all coordinators in the
* cluster and adding any endpoints not initially specified in the
* {@link Config}.
*
* For long-running processes communicating with an ArangoDB cluster it is
* recommended to run this method periodically (e.g. once per hour) to make
* sure new coordinators are picked up correctly and can be used for
* fail-over or load balancing.
*
* @example
* ```js
* const db = new Database();
* const interval = setInterval(
* () => db.acquireHostList(),
* 5 * 60 * 1000 // every 5 minutes
* );
*
* // later
* clearInterval(interval);
* db.close();
* ```
*/
async acquireHostList() {
const urls = await this.request({ path: "/_api/cluster/endpoints" }, (res) => res.body.endpoints.map((endpoint) => endpoint.endpoint));
this._connection.addToHostList(urls);
}
/**
* Closes all active connections of this database instance.
*
* Can be used to clean up idling connections during longer periods of
* inactivity.
*
* **Note**: This method currently has no effect in the browser version of
* arangojs.
*
* @example
* ```js
* const db = new Database();
* const sessions = db.collection("sessions");
* // Clean up expired sessions once per hour
* setInterval(async () => {
* await db.query(aql`
* FOR session IN ${sessions}
* FILTER session.expires < DATE_NOW()
* REMOVE session IN ${sessions}
* `);
* // Making sure to close the connections because they're no longer used
* db.close();
* }, 1000 * 60 * 60);
* ```
*/
close() {
this._connection.close();
}
async waitForPropagation({ basePath, ...request }, timeout) {
await this._connection.waitForPropagation({ ...request, basePath: `/_db/${this.name}${basePath || ""}` }, timeout);
}
//#endregion
//#region auth
/**
* Updates the `Database` instance and its connection string to use the given
* `databaseName`, then returns itself.
*
* **Note**: This also affects all collections, cursors and other arangojs
* objects originating from this database object, which may cause unexpected
* results.
*
* @param databaseName - Name of the database to use.
*
* @deprecated Use {@link Database.database} instead.
*
* @example
* ```js
* const systemDb = new Database();
* // systemDb.useDatabase("my_database"); // deprecated
* const myDb = systemDb.database("my_database");
* ```
*/
useDatabase(databaseName) {
this._connection.database(this._name, null);
this._name = databaseName;
return this;
}
/**
* Updates the `Database` instance's `authorization` header to use Basic
* authentication with the given `username` and `password`, then returns
* itself.
*
* @param username - The username to authenticate with.
* @param password - The password to authenticate with.
*
* @example
* ```js
* const db = new Database();
* db.useDatabase("test");
* db.useBasicAuth("admin", "hunter2");
* // The database instance now uses the database "test"
* // with the username "admin" and password "hunter2".
* ```
*/
useBasicAuth(username = "root", password = "") {
this._connection.setBasicAuth({ username, password });
return this;
}
/**
* Updates the `Database` instance's `authorization` header to use Bearer
* authentication with the given authentication `token`, then returns itself.
*
* @param token - The token to authenticate with.
*
* @example
* ```js
* const db = new Database();
* db.useBearerAuth("keyboardcat");
* // The database instance now uses Bearer authentication.
* ```
*/
useBearerAuth(token) {
this._connection.setBearerAuth({ token });
return this;
}
/**
* Validates the given database credentials and exchanges them for an
* authentication token, then uses the authentication token for future
* requests and returns it.
*
* @param username - The username to authenticate with.
* @param password - The password to authenticate with.
*
* @example
* ```js
* const db = new Database();
* db.useDatabase("test");
* await db.login("admin", "hunter2");
* // The database instance now uses the database "test"
* // with an authentication token for the "admin" user.
* ```
*/
login(username = "root", password = "") {
return this.request({
method: "POST",
path: "/_open/auth",
body: { username, password },
}, (res) => {
this.useBearerAuth(res.body.jwt);
return res.body.jwt;
});
}
//#endregion
//#region databases
/**
* Creates a new `Database` instance for the given `databaseName` that
* shares this database's connection pool.
*
* See also {@link Database.constructor}.
*
* @param databaseName - Name of the database.
*
* @example
* ```js
* const systemDb = new Database();
* const myDb = system.database("my_database");
* ```
*/
database(databaseName) {
const db = new Database(this, databaseName);
return db;
}
/**
* Fetches the database description for the active database from the server.
*
* @example
* ```js
* const db = new Database();
* const info = await db.get();
* // the database exists
* ```
*/
get() {
return this.request({ path: "/_api/database/current" }, (res) => res.body.result);
}
/**
* Checks whether the database exists.
*
* @example
* ```js
* const db = new Database();
* const result = await db.exists();
* // result indicates whether the database exists
* ```
*/
async exists() {
try {
await this.get();
return true;
}
catch (err) {
if (error_1.isArangoError(err) && err.errorNum === codes_1.DATABASE_NOT_FOUND) {
return false;
}
throw err;
}
}
createDatabase(databaseName, usersOrOptions) {
const { users, ...options } = Array.isArray(usersOrOptions)
? { users: usersOrOptions }
: usersOrOptions || {};
return this.request({
method: "POST",
path: "/_api/database",
body: { name: databaseName, users, options },
}, () => this.database(databaseName));
}
/**
* Fetches all databases from the server and returns an array of their names.
*
* See also {@link Database.databases} and
* {@link Database.listUserDatabases}.
*
* @example
* ```js
* const db = new Database();
* const names = await db.listDatabases();
* // databases is an array of database names
* ```
*/
listDatabases() {
return this.request({ path: "/_api/database" }, (res) => res.body.result);
}
/**
* Fetches all databases accessible to the active user from the server and
* returns an array of their names.
*
* See also {@link Database.userDatabases} and
* {@link Database.listDatabases}.
*
* @example
* ```js
* const db = new Database();
* const names = await db.listUserDatabases();
* // databases is an array of database names
* ```
*/
listUserDatabases() {
return this.request({ path: "/_api/database/user" }, (res) => res.body.result);
}
/**
* Fetches all databases from the server and returns an array of `Database`
* instances for those databases.
*
* See also {@link Database.listDatabases} and
* {@link Database.userDatabases}.
*
* @example
* ```js
* const db = new Database();
* const names = await db.databases();
* // databases is an array of databases
* ```
*/
databases() {
return this.request({ path: "/_api/database" }, (res) => res.body.result.map((databaseName) => this.database(databaseName)));
}
/**
* Fetches all databases accessible to the active user from the server and
* returns an array of `Database` instances for those databases.
*
* See also {@link Database.listUserDatabases} and
* {@link Database.databases}.
*
* @example
* ```js
* const db = new Database();
* const names = await db.userDatabases();
* // databases is an array of databases
* ```
*/
userDatabases() {
return this.request({ path: "/_api/database/user" }, (res) => res.body.result.map((databaseName) => this.database(databaseName)));
}
/**
* Deletes the database with the given `databaseName` from the server.
*
* @param databaseName - Name of the database to delete.
*
* @example
* ```js
* const db = new Database();
* await db.dropDatabase("mydb");
* // database "mydb" no longer exists
* ```
*/
dropDatabase(databaseName) {
return this.request({
method: "DELETE",
path: `/_api/database/${databaseName}`,
}, (res) => res.body.result);
}
//#endregion
//#region collections
/**
* Returns a `Collection` instance for the given collection name.
*
* In TypeScript the collection implements both the
* {@link DocumentCollection} and {@link EdgeCollection} interfaces and can
* be cast to either type to enforce a stricter API.
*
* @param T - Type to use for document data. Defaults to `any`.
* @param collectionName - Name of the edge collection.
*
* @example
* ```js
* const db = new Database();
* const collection = db.collection("potatoes");
* ```
*
* @example
* ```ts
* interface Person {
* name: string;
* }
* const db = new Database();
* const persons = db.collection<Person>("persons");
* ```
*
* @example
* ```ts
* interface Person {
* name: string;
* }
* interface Friend {
* startDate: number;
* endDate?: number;
* }
* const db = new Database();
* const documents = db.collection("persons") as DocumentCollection<Person>;
* const edges = db.collection("friends") as EdgeCollection<Friend>;
* ```
*/
collection(collectionName) {
if (!this._collections.has(collectionName)) {
this._collections.set(collectionName, new collection_1.Collection(this, collectionName));
}
return this._collections.get(collectionName);
}
async createCollection(collectionName, options) {
const collection = this.collection(collectionName);
await collection.create(options);
return collection;
}
/**
* Creates a new edge collection with the given `collectionName` and
* `options`, then returns an {@link EdgeCollection} instance for the new
* edge collection.
*
* This is a convenience method for calling {@link Database.createCollection}
* with `options.type` set to `EDGE_COLLECTION`.
*
* @param T - Type to use for edge document data. Defaults to `any`.
* @param collectionName - Name of the new collection.
* @param options - Options for creating the collection.
*
* @example
* ```js
* const db = new Database();
* const edges = db.createEdgeCollection("friends");
* ```
*
* @example
* ```ts
* interface Friend {
* startDate: number;
* endDate?: number;
* }
* const db = new Database();
* const edges = db.createEdgeCollection<Friend>("friends");
* ```
*/
async createEdgeCollection(collectionName, options) {
return this.createCollection(collectionName, {
...options,
type: collection_1.CollectionType.EDGE_COLLECTION,
});
}
/**
* Renames the collection `collectionName` to `newName`.
*
* Additionally removes any stored `Collection` instance for
* `collectionName` from the `Database` instance's internal cache.
*
* **Note**: Renaming collections may not be supported when ArangoDB is
* running in a cluster configuration.
*
* @param collectionName - Current name of the collection.
* @param newName - The new name of the collection.
*/
async renameCollection(collectionName, newName) {
const result = await this.request({
method: "PUT",
path: `/_api/collection/${collectionName}/rename`,
body: { name: newName },
}, (res) => res.body);
this._collections.delete(collectionName);
return result;
}
/**
* Fetches all collections from the database and returns an array of
* collection descriptions.
*
* See also {@link Database.collections}.
*
* @param excludeSystem - Whether system collections should be excluded.
*
* @example
* ```js
* const db = new Database();
* const collections = await db.listCollections();
* // collections is an array of collection descriptions
* // not including system collections
* ```
*
* @example
* ```js
* const db = new Database();
* const collections = await db.listCollections(false);
* // collections is an array of collection descriptions
* // including system collections
* ```
*/
listCollections(excludeSystem = true) {
return this.request({
path: "/_api/collection",
qs: { excludeSystem },
}, (res) => res.body.result);
}
/**
* Fetches all collections from the database and returns an array of
* `Collection` instances.
*
* In TypeScript these instances implement both the
* {@link DocumentCollection} and {@link EdgeCollection} interfaces and can
* be cast to either type to enforce a stricter API.
*
* See also {@link Database.listCollections}.
*
* @param excludeSystem - Whether system collections should be excluded.
*
* @example
* ```js
* const db = new Database();
* const collections = await db.collections();
* // collections is an array of DocumentCollection
* // and EdgeCollection instances
* // not including system collections
* ```
*
* @example
* ```js
* const db = new Database();
* const collections = await db.collections(false);
* // collections is an array of DocumentCollection
* // and EdgeCollection instances
* // including system collections
* ```
*/
async collections(excludeSystem = true) {
const collections = await this.listCollections(excludeSystem);
return collections.map((data) => this.collection(data.name));
}
//#endregion
//#region graphs
/**
* Returns a {@link Graph} instance representing the graph with the given
* `graphName`.
*
* @param graphName - Name of the graph.
*
* @example
* ```js
* const db = new Database();
* const graph = db.graph("some-graph");
* ```
*/
graph(graphName) {
if (!this._graphs.has(graphName)) {
this._graphs.set(graphName, new graph_1.Graph(this, graphName));
}
return this._graphs.get(graphName);
}
/**
* Creates a graph with the given `graphName` and `edgeDefinitions`, then
* returns a {@link Graph} instance for the new graph.
*
* @param graphName - Name of the graph to be created.
* @param edgeDefinitions - An array of edge definitions.
* @param options - An object defining the properties of the graph.
*/
async createGraph(graphName, edgeDefinitions, options) {
const graph = this.graph(graphName);
await graph.create(edgeDefinitions, options);
return graph;
}
/**
* Fetches all graphs from the database and returns an array of graph
* descriptions.
*
* See also {@link Database.graphs}.
*
* @example
* ```js
* const db = new Database();
* const graphs = await db.listGraphs();
* // graphs is an array of graph descriptions
* ```
*/
listGraphs() {
return this.request({ path: "/_api/gharial" }, (res) => res.body.graphs);
}
/**
* Fetches all graphs from the database and returns an array of {@link Graph}
* instances for those graphs.
*
* See also {@link Database.listGraphs}.
*
* @example
* ```js
* const db = new Database();
* const graphs = await db.graphs();
* // graphs is an array of Graph instances
* ```
*/
async graphs() {
const graphs = await this.listGraphs();
return graphs.map((data) => this.graph(data._key));
}
//#endregion
//#region views
/**
* Returns an {@link ArangoSearchView} instance for the given `viewName`.
*
* @param viewName - Name of the ArangoSearch View.
*
* @example
* ```js
* const db = new Database();
* const view = db.view("potatoes");
* ```
*/
view(viewName) {
if (!this._views.has(viewName)) {
this._views.set(viewName, new view_1.View(this, viewName));
}
return this._views.get(viewName);
}
/**
* Creates a new ArangoSearch View with the given `viewName` and `options`
* and returns an {@link ArangoSearchView} instance for the created View.
*
* @param viewName - Name of the ArangoSearch View.
* @param options - An object defining the properties of the View.
*
* @example
* ```js
* const db = new Database();
* const view = await db.createView("potatoes");
* // the ArangoSearch View "potatoes" now exists
* ```
*/
async createView(viewName, options) {
const view = this.view(viewName);
await view.create({ ...options, type: view_1.ViewType.ARANGOSEARCH_VIEW });
return view;
}
/**
* Renames the view `viewName` to `newName`.
*
* Additionally removes any stored {@link View} instance for `viewName` from
* the `Database` instance's internal cache.
*
* **Note**: Renaming views may not be supported when ArangoDB is running in
* a cluster configuration.
*
* @param viewName - Current name of the view.
* @param newName - The new name of the view.
*/
async renameView(viewName, newName) {
const result = await this.request({
method: "PUT",
path: `/_api/view/${viewName}/rename`,
body: { name: newName },
}, (res) => res.body);
this._views.delete(viewName);
return result;
}
/**
* Fetches all Views from the database and returns an array of View
* descriptions.
*
* See also {@link Database.views}.
*
* @example
* ```js
* const db = new Database();
*
* const views = await db.listViews();
* // views is an array of View descriptions
* ```
*/
listViews() {
return this.request({ path: "/_api/view" }, (res) => res.body.result);
}
/**
* Fetches all Views from the database and returns an array of
* {@link ArangoSearchView} instances for the Views.
*
* See also {@link Database.listViews}.
*
* @example
* ```js
* const db = new Database();
* const views = await db.views();
* // views is an array of ArangoSearch View instances
* ```
*/
async views() {
const views = await this.listViews();
return views.map((data) => this.view(data.name));
}
//#endregion
//#region analyzers
/**
* Returns an {@link Analyzer} instance representing the Analyzer with the
* given `analyzerName`.
*
* @example
* ```js
* const db = new Database();
* const analyzer = db.analyzer("some-analyzer");
* const info = await analyzer.get();
* ```
*/
analyzer(analyzerName) {
if (!this._analyzers.has(analyzerName)) {
this._analyzers.set(analyzerName, new analyzer_1.Analyzer(this, analyzerName));
}
return this._analyzers.get(analyzerName);
}
/**
* Creates a new Analyzer with the given `analyzerName` and `options`, then
* returns an {@link Analyzer} instance for the new Analyzer.
*
* @param analyzerName - Name of the Analyzer.
* @param options - An object defining the properties of the Analyzer.
*
* @example
* ```js
* const db = new Database();
* const analyzer = await db.createAnalyzer("potatoes", { type: "identity" });
* // the identity Analyzer "potatoes" now exists
* ```
*/
async createAnalyzer(analyzerName, options) {
const analyzer = this.analyzer(analyzerName);
await analyzer.create(options);
return analyzer;
}
/**
* Fetches all Analyzers visible in the database and returns an array of
* Analyzer descriptions.
*
* See also {@link Database.analyzers}.
*
* @example
* ```js
* const db = new Database();
* const analyzers = await db.listAnalyzers();
* // analyzers is an array of Analyzer descriptions
* ```
*/
listAnalyzers() {
return this.request({ path: "/_api/analyzer" }, (res) => res.body.result);
}
/**
* Fetches all Analyzers visible in the database and returns an array of
* {@link Analyzer} instances for those Analyzers.
*
* See also {@link Database.listAnalyzers}.
*
* @example
* ```js
* const db = new Database();
* const analyzers = await db.analyzers();
* // analyzers is an array of Analyzer instances
* ```
*/
async analyzers() {
const analyzers = await this.listAnalyzers();
return analyzers.map((data) => this.analyzer(data.name));
}
executeTransaction(collections, action, options) {
return this.request({
method: "POST",
path: "/_api/transaction",
body: {
collections: coerceTransactionCollections(collections),
action,
...options,
},
}, (res) => res.body.result);
}
/**
* Returns a {@link Transaction} instance for an existing streaming
* transaction with the given `id`.
*
* See also {@link Database.beginTransaction}.
*
* @param id - The `id` of an existing stream transaction.
*
* @example
* ```js
* const trx1 = await db.beginTransaction(collections);
* const id = trx1.id;
* // later
* const trx2 = db.transaction(id);
* await trx2.commit();
* ```
*/
transaction(transactionId) {
return new transaction_1.Transaction(this, transactionId);
}
beginTransaction(collections, options) {
return this.request({
method: "POST",
path: "/_api/transaction/begin",
body: {
collections: coerceTransactionCollections(collections),
...options,
},
}, (res) => new transaction_1.Transaction(this, res.body.result.id));
}
/**
* Fetches all active transactions from the database and returns an array of
* transaction descriptions.
*
* See also {@link Database.transactions}.
*
* @example
* ```js
* const db = new Database();
* const transactions = await db.listTransactions();
* // transactions is an array of transaction descriptions
* ```
*/
listTransactions() {
return this._connection.request({ path: "/_api/transaction" }, (res) => res.body.transactions);
}
/**
* Fetches all active transactions from the database and returns an array of
* {@link Transaction} instances for those transactions.
*
* See also {@link Database.listTransactions}.
*
* @example
* ```js
* const db = new Database();
* const transactions = await db.transactions();
* // transactions is an array of transactions
* ```
*/
async transactions() {
const transactions = await this.listTransactions();
return transactions.map((data) => this.transaction(data.id));
}
query(query, bindVars, options) {
if (aql_1.isAqlQuery(query)) {
options = bindVars;
bindVars = query.bindVars;
query = query.query;
}
else if (aql_1.isAqlLiteral(query)) {
query = query.toAQL();
}
const { allowDirtyRead, count, batchSize, cache, memoryLimit, ttl, timeout, ...opts } = options || {};
return this.request({
method: "POST",
path: "/_api/cursor",
body: {
query,
bindVars,
count,
batchSize,
cache,
memoryLimit,
ttl,
options: opts,
},
allowDirtyRead,
timeout,
}, (res) => new cursor_1.BatchedArrayCursor(this, res.body, res.arangojsHostId, allowDirtyRead).items);
}
explain(query, bindVars, options) {
if (aql_1.isAqlQuery(query)) {
options = bindVars;
bindVars = query.bindVars;
query = query.query;
}
else if (aql_1.isAqlLiteral(query)) {
query = query.toAQL();
}
return this.request({
method: "POST",
path: "/_api/explain",
body: { query, bindVars, options },
}, (res) => res.body);
}
/**
* Parses the given query and returns the result.
*
* See the {@link aql} template string handler for information about how
* to create a query string without manually defining bind parameters nor
* having to worry about escaping variables.
*
* @param query - An AQL query string or an object containing an AQL query
* string and bind parameters, e.g. the object returned from an {@link aql}
* template string.
*
* @example
* ```js
* const db = new Database();
* const collection = db.collection("some-collection");
* const ast = await db.parse(aql`
* FOR doc IN ${collection}
* FILTER doc.flavor == "strawberry"
* RETURN doc._key
* `);