-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathdocuments.js
More file actions
4086 lines (3658 loc) · 141 KB
/
Copy pathdocuments.js
File metadata and controls
4086 lines (3658 loc) · 141 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
/*
* Copyright (c) 2015-2025 Progress Software Corporation and/or its subsidiaries or affiliates. All Rights Reserved.
*/
'use strict';
const requester = require('./requester.js');
const mlutil = require('./mlutil.js');
const Operation = require('./operation.js');
const qb = require('./query-builder.js').lib;
const pathModule = require('path');
const fs = require('fs');
const stream = require('stream');
const bldrbase = require('./plan-builder-base.js');
const duplexify = require('duplexify');
/** @ignore */
function addDocumentUri(documents, document) {
if (document != null) {
const uri = document.uri;
if ((typeof uri === 'string' || uri instanceof String) && uri.length > 0) {
documents.push(uri);
}
}
return documents;
}
/** @ignore */
function getDocumentUris(documents) {
if (!Array.isArray(documents) || documents.length === 0) {
return [];
}
return documents.reduce(addDocumentUri, []);
}
/** @ignore */
function compareDocuments(firstDoc, secondDoc) {
const hasFirstDoc = (firstDoc !== null);
const hasSecondDoc = (secondDoc !== null);
if (!hasFirstDoc && !hasSecondDoc) {return 0;}
if (!hasFirstDoc && hasSecondDoc) {return -1;}
if (hasFirstDoc && !hasSecondDoc) {return 1;}
const firstUri = firstDoc.uri;
const secondUri = secondDoc.uri;
const hasFirstUri = ((typeof firstUri === 'string' || firstUri instanceof String) && firstUri.length > 0);
const hasSecondUri = ((typeof secondUri === 'string' || secondUri instanceof String) && secondUri.length > 0);
if (!hasFirstUri && !hasSecondUri) {return 0;}
if (!hasFirstUri && hasSecondUri) {return -1;}
if (hasFirstUri && !hasSecondUri) {return 1;}
if (firstUri < secondUri) {return -1;}
if (firstUri > secondUri) {return 1;}
return 0;
}
/** @ignore */
function uriErrorTransform(message) {
/*jshint validthis:true */
const operation = this;
const uri = operation.uri;
return (uri == null) ? message :
(message+' (on '+uri+')');
}
/** @ignore */
function uriListErrorTransform(message) {
/*jshint validthis:true */
const operation = this;
const uris = operation.uris;
return ((!Array.isArray(uris)) || uris.length === 0) ?
message : (message+' (on '+uris.join(', ')+')');
}
/** @ignore */
function Documents(client) {
if (!(this instanceof Documents)) {
return new Documents(client);
}
this.client = client;
}
/**
* Provides functions to write, read, query, or perform other operations
* on documents in the database. For operations that modify the database,
* the client must have been created for a user with the rest-writer role.
* For operations that read or query the database, the user need only have
* the rest-reader role.
* @namespace documents
*/
/** @ignore */
function probeOutputTransform(/*headers, data*/) {
/*jshint validthis:true */
const operation = this;
const statusCode = operation.responseStatusCode;
const exists = (statusCode === 200) ? true : false;
if (operation.contentOnly === true) {
return exists;
}
const output = exists ? operation.responseHeaders : {};
output.uri = operation.uri;
output.exists = exists;
return output;
}
function protectOutputTransform(/*headers, data*/) {
/*jshint validthis:true */
const operation = this;
const output = {
uri: operation.uri,
temporalCollection: operation.temporalCollection,
level: operation.level
};
return output;
}
function wipeOutputTransform(/*headers, data*/) {
/*jshint validthis:true */
const operation = this;
const output = {
uri: operation.uri,
temporalCollection: operation.temporalCollection,
wiped: true
};
return output;
}
function advanceLsqtOutputTransform(headers) {
/*jshint validthis:true */
const output = {
lsqt: headers.lsqt
};
return output;
}
/**
* An object offering the alternative of a {@link ResultProvider#result} function
* or a {@link ResultProvider#stream} function for receiving the results
* @namespace ResultProvider
*/
/**
* Accepts success and/or failure callbacks and returns a
* {@link https://www.promisejs.org/|Promises} object for chaining
* actions with then() functions.
* @name ResultProvider#result
* @since 1.0
* @function
* @param {function} [success] - a callback invoked when the request succeeds
* @param {function} [failure] - a callback invoked when the request fails
* @returns {object} a Promises object
*/
/**
* Returns a ReadableStream object in object mode for receiving results as
* complete objects.
* @name ResultProvider#stream
* @since 1.0
* @function
* @returns {object} a {@link http://nodejs.org/api/stream.html#stream_class_stream_readable|ReadableStream}
* object
*/
/**
* Provides a description of a document to write to the server, after reading
* from the server, or for another document operation. The descriptor may have
* more or fewer properties depending on the operation.
* @typedef {object} documents.DocumentDescriptor
* @since 1.0
* @property {string} uri - the identifier for the document in the database
* @property {object|string|Buffer|ReadableStream} [content] - the content
* of the document; when writing a ReadableStream for the content, first pause
* the stream
* @property {string[]} [collections] - the collections to which the document belongs
* @property {object[]} [permissions] - the permissions controlling which users can read or
* write the document
* @property {object[]} [properties] - additional properties of the document
* @property {number} [quality] - a weight to increase or decrease the rank of the document
* @property {object[]} [metadataValues] - the metadata values of the document
* @property {number} [versionId] - an identifier for the currently stored version of the
* document
* @property {string} [temporalDocument] - the collection URI for a temporal document;
* use only when writing a document to a temporal collection
*/
/**
* Categories of information to read or write for documents.
* The possible values of the enumeration are
* content|collections|metadataValues|permissions|properties|quality|metadata|rawContent|none where
* metadata is an alias for all of the categories other than content.
* @typedef {enum} documents.categories
* @since 1.0
*/
/**
* A success callback for {@link ResultProvider} that receives the result from
* the {@link documents#probe}.
* @callback documents#probeResult
* @since 1.0
* @param {documents.DocumentDescriptor} document - a sparse document descriptor with an exists
* property that identifies whether the document exists
*/
/**
* Probes whether a document exists; takes a configuration
* object with the following named parameters or, as a shortcut,
* a uri string.
* @method documents#probe
* @since 1.0
* @param {string} uri - the uri for the database document
* @param {string|transactions.Transaction} [txid] - a string
* transaction id or Transaction object identifying an open
* multi-statement transaction
* @returns {ResultProvider} an object whose result() function takes
* a {@link documents#probeResult} success callback.
*/
Documents.prototype.probe = function probeDocument() {
return probeDocumentsImpl.call(this, false, mlutil.asArray.apply(null, arguments));
};
function probeDocumentsImpl(contentOnly, args) {
/*jshint validthis:true */
if (args.length !== 1 && args.length !== 2) {
throw new Error('must supply uri for document check()');
}
const params = (args.length === 1 && typeof args[0] !== 'string' && !(args[0] instanceof String)) ? args[0] : null;
let uri = null;
let txid = null;
let path = '/v1/documents?format=json';
// params as list
if (params === null) {
uri = args[0];
path += '&uri='+encodeURIComponent(uri);
txid = mlutil.convertTransaction(args[1]);
if (txid != null) {
path += '&txid='+mlutil.getTxidParam(txid);
}
}
// params as object
else {
uri = params.uri;
if (uri == null) {
throw new Error('must specify the uri parameter for the document to check');
}
path += '&uri='+encodeURIComponent(uri);
txid = mlutil.convertTransaction(params.txid);
if (txid != null) {
path += '&txid='+mlutil.getTxidParam(txid);
}
}
const requestOptions = mlutil.newRequestOptions(this.client.getConnectionParams(), path, 'HEAD');
mlutil.addTxidHeaders(requestOptions, txid);
const operation = new Operation(
'probe document', this.client, requestOptions, 'empty', 'empty'
);
operation.uri = uri;
operation.validStatusCodes = [200, 404];
operation.outputTransform = probeOutputTransform;
operation.errorTransform = uriErrorTransform;
operation.contentOnly = (contentOnly === true);
return requester.startRequest(operation);
}
/**
* A success callback for {@link ResultProvider} that receives the result from
* the {@link documents#protect}.
* @callback documents#protectResult
* @since 2.0.1
* @param {documents.DocumentDescriptor} document - a sparse document descriptor
* for the protected document
*/
/**
* Protects a temporal document from temporal operations for a
* period of time.
* @method documents#protect
* @since 2.0.1
* @param {string} uri - the uri for the temporal document to protect
* @param {string} temporalCollection - the temporal collection for the document
* @param {string} [duration] - a protection duration; either a duration or an
* expire time must be provided
* @param {string} [expireTime] - an expiration time; either an expiration time
* or a duration must be provided
* @param {string} [level] - a protection level of 'noWipe'|'noDelete'|'noUpdate'
* (default is 'noDelete')
* @param {string} [archivePath] - an archive path
* @returns {ResultProvider} an object whose result() function takes
* a {@link documents#protectResult} success callback.
*/
Documents.prototype.protect = function protectDocument() {
/*jshint validthis:true */
const args = mlutil.asArray.apply(null, arguments);
const argLen = args.length;
let uri = null;
let tempColl = null;
let duration = null;
let expireTime = null;
let level = 'noDelete';
let archivePath = null;
// Params as single object
if (argLen === 1) {
const obj = args[0];
if (obj.uri === void 0) {
throw new Error('must specify uri');
} else {
uri = obj.uri;
}
if (obj.temporalCollection === void 0) {
throw new Error('must specify temporalCollection');
} else {
tempColl = obj.temporalCollection;
}
if (obj.expireTime !== void 0) {
expireTime = obj.expireTime;
} else if (obj.duration !== void 0) {
duration = obj.duration;
} else {
throw new Error('must specify duration or expireTime');
}
if (obj.level !== void 0) {
level = obj.level;
}
if (obj.archivePath !== void 0) {
archivePath = obj.archivePath;
}
}
// Multiple params
else {
if (argLen < 3) {
throw new Error('must specify uri, temporalCollection, and duration or expireTime');
}
uri = args[0];
tempColl = args[1];
// see: https://www.w3.org/TR/xmlschema-2/#duration
if (args[2].charAt(0) === 'P' || args[2].substring(0, 2) === '-P') {
duration = args[2];
} else {
expireTime = args[2];
}
const levels = ['noWipe', 'noDelete', 'noUpdate'];
if (levels.indexOf(args[3]) !== -1) {
level = args[3];
} else {
archivePath = args[3] || null;
}
if (args[4] && archivePath === null) {
archivePath = args[4];
}
}
if (archivePath !== null) {
try {
fs.accessSync(pathModule.dirname(archivePath));
} catch (e) {
throw new Error('archive directory does not exist: ' + archivePath);
}
}
let path = '/v1/documents/protection?uri=' + encodeURIComponent(uri);
path += '&temporal-collection=' + encodeURIComponent(tempColl);
if (duration !== null) {
path += '&duration=' + encodeURIComponent(duration);
} else {
path += '&expireTime=' + encodeURIComponent(expireTime);
}
path += '&level=' + encodeURIComponent(level);
if (archivePath !== null) {
path += '&archivePath=' + encodeURIComponent(archivePath);
}
const requestOptions = mlutil.newRequestOptions(this.client.getConnectionParams(), path, 'POST');
const operation = new Operation(
'protect document', this.client, requestOptions, 'empty', 'empty'
);
operation.uri = uri;
operation.temporalCollection = tempColl;
operation.level = level;
operation.validStatusCodes = [204];
operation.outputTransform = protectOutputTransform;
operation.errorTransform = uriErrorTransform;
return requester.startRequest(operation);
};
/**
* A success callback for {@link ResultProvider} that receives the result from
* the {@link documents#wipe}.
* @callback documents#wipeResult
* @since 2.0.1
* @param {documents.DocumentDescriptor} document - a sparse document descriptor
* for the wipe command
*/
/**
* Deletes all versions of a temporal document.
* @method documents#wipe
* @since 2.0.1
* @param {string} uri - the uri for the temporal document to wipe
* @param {string} temporalCollection - the name of the temporal collection
* @returns {ResultProvider} an object whose result() function takes
* a {@link documents#wipeResult} success callback.
*/
Documents.prototype.wipe = function wipeDocument() {
/*jshint validthis:true */
const args = mlutil.asArray.apply(null, arguments);
const argLen = args.length;
let uri = null;
let tempColl = null;
// Params as single object
if (argLen === 1) {
const obj = args[0];
if (obj.uri === void 0) {
throw new Error('must specify uri');
} else {
uri = obj.uri;
}
if (obj.temporalCollection === void 0) {
throw new Error('must specify temporalCollection');
} else {
tempColl = obj.temporalCollection;
}
}
// Multiple params
else {
if (argLen < 2) {
throw new Error('must specify uri and temporalCollection');
}
uri = args[0];
tempColl = args[1];
}
let path = '/v1/documents?uri=' + encodeURIComponent(uri);
path += '&temporal-collection=' + encodeURIComponent(tempColl);
path += '&result=wiped';
const requestOptions = mlutil.newRequestOptions(this.client.getConnectionParams(), path, 'DELETE');
const operation = new Operation(
'wipe document', this.client, requestOptions, 'empty', 'empty'
);
operation.uri = uri;
operation.temporalCollection = tempColl;
operation.validStatusCodes = [204];
operation.outputTransform = wipeOutputTransform;
operation.errorTransform = uriErrorTransform;
return requester.startRequest(operation);
};
/**
* Advances the LSQT (Last Stable Query Time) of a temporal collection.
* @method documents#advanceLsqt
* @since 2.1.1
* @param {string} temporalCollection - The name of the temporal collection
* for which to advance the LSQT.
* @param {string} [lag] - The lag (in seconds (???)) to subtract from the
* maximum system start time in the temporal collection to determine the LSQT.
* @returns {ResultProvider} an object whose result() function takes
* an object with the new LSQT as an 'lsqt' property.
*/
Documents.prototype.advanceLsqt = function temporalAdvanceLsqt() {
/*jshint validthis:true */
const args = mlutil.asArray.apply(null, arguments);
let tempColl = null;
let lag = null;
// Positional case
if (typeof args[0] === 'string' || args[0] instanceof String) {
tempColl = args[0];
if (args[1] !== void 0) {
if (typeof args[1] === 'number' || args[0] instanceof Number) {
lag = args[1];
} else {
throw new Error('lag parameter takes a number in seconds');
}
}
}
// Object case
else {
const obj = args[0];
if (obj.temporalCollection === void 0) {
throw new Error('must specify temporalCollection');
} else {
tempColl = obj.temporalCollection;
}
if (obj.lag !== void 0) {
if (typeof obj.lag === 'number' || obj.lag instanceof Number) {
lag = obj.lag;
} else {
throw new Error('lag parameter takes a number in seconds');
}
}
}
let path = '/v1/temporal/collections/' + encodeURIComponent(tempColl);
path += '?result=advance-lsqt';
if (lag !== null) {
path += '&lag=' + encodeURIComponent(lag);
}
const requestOptions = mlutil.newRequestOptions(this.client.getConnectionParams(), path, 'POST');
const operation = new Operation(
'advance LSQT', this.client, requestOptions, 'empty', 'empty'
);
// operation.temporalCollection = tempColl;
operation.validStatusCodes = [204];
operation.outputTransform = advanceLsqtOutputTransform;
operation.errorTransform = uriErrorTransform;
return requester.startRequest(operation);
};
/** @ignore */
function readStatusValidator(statusCode) {
return (statusCode < 400 || statusCode === 404) ?
null : 'response with invalid '+statusCode+' status';
}
/** @ignore */
function singleReadOutputTransform(headers, data) {
/*jshint validthis:true */
const operation = this;
const hasData = (data != null);
if (hasData &&
(data.errorResponse != null) &&
data.errorResponse.statusCode === 404
) {
return [];
}
const content = hasData ? data : null;
if (operation.contentOnly === true) {
return [content];
}
const categories = operation.categories;
const document = (categories.length === 1 && categories[0] === 'content') ?
{content: content} : collectMetadata(content);
if(operation.uris){
document.uri = operation.uris[0];
}
document.category = categories;
const format = headers.format;
if (typeof format === 'string' || format instanceof String) {
document.format = format;
if (format !== 'json') {
const contentLength = headers.contentLength;
if (contentLength != null) {
document.contentLength = contentLength;
}
}
}
const headerList = ['contentType', 'versionId'];
let headerKey = null;
let headerValue = null;
let i = 0;
for (i = 0; i < headerList.length; i++) {
headerKey = headerList[i];
headerValue = headers[headerKey];
if (headerValue != null) {
document[headerKey] = headerValue;
}
}
return [document];
}
/**
* A success callback for {@link ResultProvider} that receives the result from
* the {@link documents#read}.
* @callback documents#resultList
* @since 1.0
* @param {documents.DocumentDescriptor[]} documents - an array of
* {@link documents.DocumentDescriptor} objects with the requested
* metadata and/or content for the documents
*/
/**
* Reads one or more documents; takes a configuration object with
* the following named parameters or, as a shortcut, one or more
* uri strings or an array of uri strings.
* @method documents#read
* @since 1.0
* @param {string|string[]} uris - the uri string or an array of uri strings
* for the database documents
* @param {documents.categories|documents.categories[]} [categories] - the categories of information
* to retrieve for the documents
* @param {string|transactions.Transaction} [txid] - a string
* transaction id or Transaction object identifying an open
* multi-statement transaction
* @param {string|mixed[]} [transform] - the name of a transform extension to apply to each document
* or an array with the name of the transform extension and an object of parameter values; the
* transform must have been installed using the {@link transforms#write} function.
* @param {number[]} [range] - the range of bytes to extract
* from a binary document; the range is specified with a zero-based
* start byte and the position after the end byte as in Array.slice()
* @param {DatabaseClient.Timestamp} [timestamp] - a Timestamp object for point-in-time
* operations.
* @returns {ResultProvider} an object whose result() function takes
* a {@link documents#resultList} success callback.
*/
Documents.prototype.read = function readDocuments() {
return readDocumentsImpl.call(this, false, mlutil.asArray.apply(null, arguments));
};
function readDocumentsImpl(contentOnly, args) {
/*jshint validthis:true */
if (args.length === 0) {
throw new Error('must specify at least one document to read');
}
let uris = null;
let categories = null;
let txid = null;
let transform = null;
let contentType = null;
let range = null;
let timestamp = null;
const arg = args[0];
if (Array.isArray(arg)) {
uris = arg;
} else if (typeof arg === 'string' || arg instanceof String) {
uris = args;
} else {
uris = arg.uris;
if (uris == null) {
throw new Error('must specify the uris parameters with at least one document to read');
}
if (!Array.isArray(uris)) {
uris = [uris];
}
categories = arg.categories;
txid = mlutil.convertTransaction(arg.txid);
transform = arg.transform;
contentType = arg.contentType;
range = arg.range;
timestamp = arg.timestamp;
}
if (categories == null) {
categories = ['content'];
} else if (typeof categories === 'string' || categories instanceof String) {
categories = [categories];
}
if (categories != null) {
let i = 0;
for (i = 0; i < categories.length; i++) {
if(categories[i] === 'rawContent'){
if(categories.length>1) {
throw new Error('Categories should not have other option(s) if rawContent is needed.');
} else {
categories = ['content'];
contentOnly = true;
}
}
categories[i] = categories[i] === 'metadataValues' ? 'metadata-values' : categories[i];
}
}
let path = '/v1/documents?format=json&uri='+
uris.map(encodeURIComponent).join('&uri=');
path += '&category=' + categories.join('&category=');
if (txid != null) {
path += '&txid='+mlutil.getTxidParam(txid);
}
if (transform != null) {
path += '&'+mlutil.endpointTransform(transform);
}
if (timestamp !== null && timestamp !== void 0) {
if (timestamp.value !== null) {
path += '×tamp='+timestamp.value;
}
}
const isSinglePayload = (
uris.length === 1 && (
(categories.length === 1 && categories[0] === 'content') ||
categories.indexOf('content') === -1
));
const requestOptions = mlutil.newRequestOptions(this.client.getConnectionParams(), path, 'GET');
if (!isSinglePayload) {
requestOptions.headers = {
Accept: 'multipart/mixed; boundary='+mlutil.multipartBoundary
};
} else {
let hasContentType = false;
if (contentType != null) {
if (typeof contentType === 'string' || contentType instanceof String) {
hasContentType = true;
} else {
throw new Error('contentType is not string: '+contentType);
}
}
if (range != null) {
if (!Array.isArray(range)) {
throw new Error('byte range parameter for reading binary document is not an array: '+range);
}
let bytes = null;
switch (range.length) {
case 0:
throw new Error('no start length for byte range parameter for reading binary document');
case 1:
if (typeof range[0] !== 'number' && !(range[0] instanceof Number)) {
throw new Error('start length for byte range parameter is not integer: '+range[0]);
}
bytes = 'bytes=' + range[0] + '-';
break;
case 2:
if (typeof range[0] !== 'number' && !(range[0] instanceof Number)) {
throw new Error('start length for byte range parameter is not integer: '+range[0]);
}
if (typeof range[1] !== 'number' && !(range[1] instanceof Number)) {
throw new Error('end length for byte range parameter is not integer: '+range[1]);
}
if (range[0] >= range[1]) {
throw new Error('start length greater than or equal to end length for byte range: '+range);
}
bytes = 'bytes=' + range[0] + '-' + (range[1] - 1);
break;
default:
throw new Error('byte range parameter has more than start and end length: '+range);
}
if (!hasContentType) {
requestOptions.headers = {
Range: bytes
};
} else if (contentType.search(/^(application\/([^+]+\+)?(json|xml)|text\/.*)$/) > -1) {
throw new Error('cannot request byte range for JSON, text, or XML document: '+contentType);
} else {
requestOptions.headers = {
Range: bytes,
'Content-Type': contentType
};
}
} else if (hasContentType) {
requestOptions.headers = {
'Content-Type': contentType
};
}
}
mlutil.addTxidHeaders(requestOptions, txid);
const operation = new Operation(
'read documents', this.client, requestOptions, 'empty',
(isSinglePayload ? 'single' : 'multipart')
);
operation.uris = uris;
operation.categories = categories;
operation.errorTransform = uriListErrorTransform;
if (isSinglePayload) {
operation.contentOnly = (contentOnly === true);
operation.outputTransform = singleReadOutputTransform;
operation.statusCodeValidator = readStatusValidator;
} else if (contentOnly === true) {
operation.subdata = ['content'];
}
operation.timestamp = (timestamp !== null) ? timestamp : null;
return requester.startRequest(operation);
}
/**
* Writes a large document (typically a binary) in incremental chunks with
* a stream; takes a {@link documents.DocumentDescriptor} object with the
* following properties (but not a content property).
* @method documents#createWriteStream
* @since 1.0
* @param {string} uri - the identifier for the document to write to the database
* @param {string[]} [collections] - the collections to which the document should belong
* @param {object[]} [permissions] - the permissions controlling which users can read or
* write the document
* @param {object[]} [properties] - additional properties of the document
* @param {number} [quality] - a weight to increase or decrease the rank of the document
* @param {object[]} [metadataValues] - the metadata values of the document
* @param {number} [versionId] - an identifier for the currently stored version of the
* document (when enforcing optimistic locking)
* @param {string|transactions.Transaction} [txid] - a string
* transaction id or Transaction object identifying an open
* multi-statement transaction
* @param {string|mixed[]} [transform] - the name of a transform extension to apply to each document
* or an array with the name of the transform extension and an object of parameter values; the
* transform must have been installed using the {@link transforms#write} function.
* @returns {WritableStream} a stream for writing the database document; the
* stream object also has a result() function that takes
* a {@link documents#writeResult} success callback.
*/
Documents.prototype.createWriteStream = function createWriteStream(document) {
if ((document == null) ||
(document.uri == null)) {
throw new Error('must specify document for write stream');
}
if (document.content != null) {
throw new Error('must write to stream to supply document content');
}
let categories = document.categories;
const hasCategories = Array.isArray(categories) && categories.length > 0;
if (!hasCategories && (typeof categories === 'string' || categories instanceof String)) {
categories = [categories];
}
if (document.properties == null) {
return writeContent.call(this, false, document, document, categories, 'chunked');
}
return writeStreamImpl.call(this, document, categories);
};
/** @ignore */
function writeStreamImpl(document, categories) {
/*jshint validthis:true */
let endpoint = '/v1/documents';
const txid = getTxid(document);
const writeParams = addWriteParams(document, categories, txid);
if (writeParams.length > 0) {
endpoint += writeParams;
}
const multipartBoundary = mlutil.multipartBoundary;
const requestOptions = mlutil.newRequestOptions(this.client.getConnectionParams(), endpoint, 'POST');
requestOptions.headers = {
'Content-Type': 'multipart/mixed; boundary='+multipartBoundary,
'Accept': 'application/json'
};
mlutil.addTxidHeaders(requestOptions, txid);
const operation = new Operation(
'write document stream', this.client, requestOptions, 'chunkedMultipart', 'single'
);
operation.isReplayable = false;
operation.uri = document.uri;
// TODO: treat as chunked single document if no properties
const requestPartList = [];
addDocumentParts(operation, requestPartList, document, true);
operation.requestDocument = requestPartList;
operation.multipartBoundary = mlutil.multipartBoundary;
operation.errorTransform = uriErrorTransform;
return requester.startRequest(operation);
}
/** @ignore */
function singleWriteOutputTransform(headers, data) {
/*jshint validthis:true */
const operation = this;
let uri = operation.uri;
if (uri == null) {
const location = headers.location;
if (location != null) {
const startsWith = '/v1/documents?uri=';
if (location.length > startsWith.length &&
location.substr(0, startsWith.length) === startsWith) {
uri = location.substr(startsWith.length);
}
}
}
if (operation.contentOnly === true) {
return [uri];
}
const document = {uri: uri};
const categories = operation.categories;
if (categories == null) {
document.categories = categories;
}
const contentType = (data == null) ? null : data['mime-type'];
if (contentType == null) {
document.contentType = contentType;
}
const wrapper = {documents: [document]};
const systemTime = headers.systemTime;
if (systemTime != null) {
wrapper.systemTime = systemTime;
}
return wrapper;
}
/** @ignore */
function writeListOutputTransform(headers, data) {
// var operation = this;
const systemTime = headers.systemTime;
if (systemTime == null) {
return data;
}
return {
documents: data.documents,
systemTime: systemTime
};
}
/**
* A success callback for {@link ResultProvider} that receives the result from
* the {@link documents#write} or the {@link documents#createWriteStream}
* functions.
* @callback documents#writeResult
* @since 1.0
* @param {object} response - a response with a documents property providing
* a sparse array of array of {@link documents.DocumentDescriptor} objects
* providing the uris of the written documents.
*/
/**
* Writes one or more documents; takes a configuration object with
* the following named parameters or, as a shortcut, a document descriptor.
* @method documents#write
* @since 1.0
* @param {DocumentDescriptor|DocumentDescriptor[]} documents - one descriptor
* or an array of document descriptors to write
* @param {documents.categories|documents.categories[]} [categories] - the categories of information
* to write for the documents
* @param {string|transactions.Transaction} [txid] - a string
* transaction id or Transaction object identifying an open
* multi-statement transaction
* @param {string|mixed[]} [transform] - the name of a transform extension to apply to each document
* or an array with the name of the transform extension and an object of parameter values; the
* transform must have been installed using the {@link transforms#write} function.
* @param {string} [forestName] - the name of a forest in which to write
* the documents.
* @param {string} [temporalCollection] - the name of the temporal collection;
* use only when writing temporal documents that have the JSON properties or XML elements
* specifying the valid and system start and end times as defined by the valid and
* system axis for the temporal collection
* @param {string|Date} [systemTime] - a datetime to use as the system start time
* instead of the current time of the database server; can only be supplied
* if the temporalCollection parameter is also supplied
* @returns {ResultProvider} an object whose result() function takes
* a {@link documents#writeResult} success callback.
*/
Documents.prototype.write = function writeDocuments() {
return writeDocumentsImpl.call(this, false, mlutil.asArray.apply(null, arguments));
};
function writeDocumentsImpl(contentOnly, args) {
/*jshint validthis:true */
if (args.length < 1) {
throw new Error('must provide uris for document write()');
}
const arg = args[0];
let documents = arg.documents;
const params = (documents == null) ? null : arg;
if (params !== null) {
if (!Array.isArray(documents)) {
documents = [documents];
}
} else if (Array.isArray(arg)) {
documents = arg;
} else {
documents = args;
}
const isSingleDoc = (documents.length === 1);
const document = isSingleDoc ? documents[0] : null;
const hasDocument = (document != null);
const hasContent = hasDocument && (document.content != null);
const requestParams =
(params !== null) ? params :
(hasDocument) ? document :
null;
let categories = (requestParams == null) ? null : requestParams.categories;
if (typeof categories === 'string' || categories instanceof String) {
categories = [categories];
}