-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDynamoDBGlobalSecondaryIndex.js
More file actions
1275 lines (1212 loc) · 46.8 KB
/
DynamoDBGlobalSecondaryIndex.js
File metadata and controls
1275 lines (1212 loc) · 46.8 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
require('rubico/global')
const crypto = require('crypto')
const HTTP = require('./HTTP')
const userAgent = require('./userAgent')
const AwsAuthorization = require('./internal/AwsAuthorization')
const AmzDate = require('./internal/AmzDate')
const Readable = require('./Readable')
const DynamoDBIndexname = require('./internal/DynamoDBIndexname')
const DynamoDBKeySchema = require('./internal/DynamoDBKeySchema')
const DynamoDBAttributeDefinitions =
require('./internal/DynamoDBAttributeDefinitions')
const DynamoDBAttributeType =
require('./internal/DynamoDBAttributeType')
const DynamoDBAttributeValue =
require('./internal/DynamoDBAttributeValue')
const DynamoDBAttributeValueJSON =
require('./internal/DynamoDBAttributeValueJSON')
const hashJSON = require('./internal/hashJSON')
const sleep = require('./internal/sleep')
const createExpressionAttributeNames =
require('./internal/createExpressionAttributeNames')
const createExpressionAttributeValues =
require('./internal/createExpressionAttributeValues')
const createKeyConditionExpression =
require('./internal/createKeyConditionExpression')
const createFilterExpression = require('./internal/createFilterExpression')
const AwsError = require('./internal/AwsError')
/**
* @name DynamoDBGlobalSecondaryIndex
*
* @docs
* ```coffeescript [specscript]
* new DynamoDBGlobalSecondaryIndex(options {
* table: string,
* key: [
* { [hashKey string]: 'S'|'string'|'N'|'number'|'B'|'binary' },
* { [sortKey string]: 'S'|'string'|'N'|'number'|'B'|'binary' },
* ],
* accessKeyId: string,
* secretAccessKey: string,
* region: string,
* autoReady: boolean,
* }) -> gsi DynamoDBGlobalSecondaryIndex
* ```
*
* Presidium DynamoDBGlobalSecondaryIndex client for [AWS DynamoDB](https://aws.amazon.com/dynamodb/). Creates the DynamoDB Global Secondary Index (GSI) if it doesn't exist.
*
* DynamoDBGlobalSecondaryIndex instances have a `ready` promise that resolves when the GSI is active.
*
* Arguments:
* * `options`
* * `table` - the name of the DynamoDB Table to which the DynamoDB Global Secondary Index belongs.
* * `key` - the primary key of the DynamoDB Global Secondary Index.
* * `accessKeyId` - the AWS access key id.
* * `secretAccessKey` - the AWS secret access key.
* * `region` - the AWS region.
* * `autoReady` - whether to automatically create the DynamoDB Global Secondary Index if it doesn't exist. Defaults to `true`.
*
* Return:
* * `gsi` - a DynamoDBGlobalSecondaryIndex instance.
*
* ```javascript
* const awsCreds = await AwsCredentials('my-profile')
* awsCreds.region = 'us-east-1'
*
* const env = process.env.NODE_ENV
*
* const myTable = new DynamoTable({
* name: `${env}-my-table`,
* key: [{ id: 'string' }],
* ...awsCreds,
* })
* await myTable.ready
*
* const myStatusUpdateTimeGSI = new DynamoDBGlobalSecondaryIndex({
* table: `${env}-my-table`,
* key: [{ status: 'string' }, { updateTime: 'number' }],
* ...awsCreds,
* })
* ```
*
* References:
* * [AWS DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Introduction.html)
*/
class DynamoDBGlobalSecondaryIndex {
constructor(options) {
this.table = options.table
this.key = options.key
this.name = DynamoDBIndexname(this.key)
this.accessKeyId = options.accessKeyId ?? ''
this.secretAccessKey = options.secretAccessKey ?? ''
this.region = options.region ?? ''
this.apiVersion = '2012-08-10'
this.endpoint = `dynamodb.${this.region}.amazonaws.com`
this.protocol = 'https'
this.BillingMode = options.BillingMode ?? 'PAY_PER_REQUEST'
if (this.BillingMode == 'PROVISIONED') {
this.ProvisionedThroughput = options.ProvisionedThroughput ?? {
ReadCapacityUnits: 5,
WriteCapacityUnits: 5
}
}
this.http = new HTTP(`${this.protocol}://${this.endpoint}`)
/**
* @name ready
*
* @docs
* ```coffeescript [specscript]
* ready -> promise Promise<>
* ```
*
* The ready promise for the DynamoDBGlobalSecondaryIndex instance. Resolves when the DynamoDB Global Secondary Index is active.
*
* ```javascript
* const awsCreds = await AwsCredentials('default')
* awsCreds.region = 'us-east-1'
*
* const env = process.env.NODE_ENV
*
* const myTable = new DynamoDBTable({
* name: `${env}-my-table`,
* key: [{ id: 'string' }],
* ...awsCreds,
* })
* await myTable.ready
*
* const myTypeTimeGSI = new DynamoDBGlobalSecondaryIndex({
* table: `${env}-my-table`,
* key: [{ type: 'string' }, { time: 'number' }],
* ...awsCreds,
* })
* await myTypeTimeGSI.ready
* ```
*/
this.autoReady = options.autoReady ?? true
if (this.autoReady) {
this.ready = this._readyPromise()
}
}
/**
* @name _readyPromise
*
* @docs
* ```coffeescript [specscript]
* _readyPromise() -> ready Promise<>
* ```
*/
async _readyPromise() {
try {
await this.describe()
await this.waitForActive()
return { message: 'global-secondary-index-exists' }
} catch (error) {
await this.create()
await this.waitForActive()
return { message: 'created-global-secondary-index' }
}
}
/**
* @name _awsRequest
*
* @docs
* ```coffeescript [specscript]
* module http 'https://nodejs.org/api/http.html'
*
* _awsRequest(
* method string,
* url string,
* action string,
* payload string
* ) -> response Promise<http.ServerResponse>
* ```
*/
_awsRequest(method, url, action, payload) {
const amzDate = AmzDate()
const amzTarget = `DynamoDB_${this.apiVersion.replace(/-/g, '')}.${action}`
const headers = {
'Host': this.endpoint,
'Accept-Encoding': 'identity',
'Content-Length': Buffer.byteLength(payload, 'utf8'),
'User-Agent': userAgent,
'Content-Type': 'application/x-amz-json-1.0',
'X-Amz-Date': amzDate,
'X-Amz-Target': amzTarget
}
const amzHeaders = {}
for (const key in headers) {
if (key.toLowerCase().startsWith('x-amz')) {
amzHeaders[key] = headers[key]
}
}
headers['Authorization'] = AwsAuthorization({
accessKeyId: this.accessKeyId,
secretAccessKey: this.secretAccessKey,
region: this.region,
method,
endpoint: this.endpoint,
protocol: this.protocol,
canonicalUri: url,
serviceName: 'dynamodb',
payloadHash:
crypto.createHash('sha256').update(payload, 'utf8').digest('hex'),
expires: 300,
queryParams: new URLSearchParams(),
headers: {
'Host': this.endpoint,
...amzHeaders
}
})
return this.http[method](url, { headers, body: payload })
}
/**
* @name describeTable
*
* @docs
* ```coffeescript [specscript]
* module AWSDynamoDBDocs 'https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Types.html'
*
* describeTable() -> data Promise<{
* Table: AWSDynamoDBDocs.TableDescription,
* }>
* ```
*
* Returns information about the DynamoDB Table of the DynamoDB Global Secondary Index.
*
* Arguments:
* * (none)
*
* Return:
* * `data`
* * `Table` - [`AWSDynamoDBDocs.TableDescription`](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_TableDescription.html) - the DynamoDB Table properties.
*
* ```javascript
* const awsCreds = await AwsCredentials('my-profile')
* awsCreds.region = 'us-east-1'
*
* const myTable = new DynamoDBTable({
* name: 'my-table'
* key: [{ id: 'string' }],
* ...awsCreds,
* })
* await myTable.ready
*
* const myTypeTimeGSI = new DynamoDBGlobalSecondaryIndex({
* table: 'my-table',
* key: [{ type: 'string' }, { time: 'number' }],
* ...awsCreds,
* })
* await myTypeTimeGSI.ready
*
* const data = await myTypeTimeGSI.describeTable()
* ```
*
* References:
* * [AWS DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Introduction.html)
*/
async describeTable() {
const payload = JSON.stringify({
TableName: this.table,
})
const response =
await this._awsRequest('POST', '/', 'DescribeTable', payload)
if (response.ok) {
return Readable.JSON(response)
}
throw new AwsError(await Readable.Text(response), response.status)
}
/**
* @name describe
*
* @docs
* ```coffeescript [specscript]
* module AWSDynamoDBDocs 'https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Types.html'
*
* describe() -> indexData Promise<{
* IndexArn: string,
* IndexName: string,
* IndexStatus: 'CREATING'|'UPDATING'|'DELETING'|'ACTIVE',
* KeySchema: [
* { AttributeName: string, KeyType: 'HASH' },
* { AttributeName: string, KeyType: 'RANGE' },
* ]
* BillingModeSummary: {
* BillingMode: 'PAY_PER_REQUEST'|'PROVISIONED',
* },
* ProvisionedThroughput: {
* ReadCapacityUnits: number,
* WriteCapacityUnits: number,
* },
* }>
* ```
*
* Returns information about the DynamoDB Global Secondary Index.
*
* Arguments:
* * (none)
*
* Return:
* * `IndexArn` - the ARN (Amazon Resource Name) of the Global Secondary Index.
* * `IndexName` - the name of the Global Secondary Index.
* * `IndexStatus` - the currentn status of the Global Secondary Index.
* * `KeySchema` - the [key schema](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_KeySchemaElement.html) of the Global Secondary Index.
* * `BillingModeSummary` - information about the read/write capacity mode of the Global Secondary Index.
* * `BillingMode` - a mode that controls how read and write throughput is billed and how DynamoDB manages capacity for the Global Secondary Index.
* * `ProvisionedThroughput` - information about the provisioned throughput settings of the Global Secondary Index.
* * `ReadCapacityUnits` - number of 4KB strong reads per second.
* * `WriteCapacityUnits` - number of 1KB writes per second.
*
* `BillingModes` values:
* * `PAY_PER_REQUEST` - on-demand capacity mode. The AWS account is billed per read and write request.
* * `PROVISIONED` - a capacity mode where the reads (RCUs) and writes (WCUs) are predefined.
*
* ```javascript
* const awsCreds = await AwsCredentials('my-profile')
* awsCreds.region = 'us-east-1'
*
* const myTable = new DynamoDBTable({
* name: 'my-table'
* key: [{ id: 'string' }],
* ...awsCreds,
* })
* await myTable.ready
*
* const myTypeTimeGSI = new DynamoDBGlobalSecondaryIndex({
* table: 'my-table',
* key: [{ type: 'string' }, { time: 'number' }],
* ...awsCreds,
* })
* await myTypeTimeGSI.ready
*
* const data = await myTypeTimeGSI.describe()
* ```
*
* References:
* * [AWS DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Introduction.html)
*/
async describe() {
const payload = JSON.stringify({
TableName: this.table,
})
const response =
await this._awsRequest('POST', '/', 'DescribeTable', payload)
if (response.ok) {
const data = await Readable.JSON(response)
const indexData =
data.Table.GlobalSecondaryIndexes?.find(eq(this.name, get('IndexName')))
if (indexData == null) {
throw new Error(`DynamoDB Global Secondary Index ${this.name} not found`)
}
indexData.BillingModeSummary = data.Table.BillingModeSummary
return indexData
}
throw new AwsError(await Readable.Text(response), response.status)
}
/**
* @name create
*
* @docs
* ```coffeescript [specscript]
* create() -> indexData Promise<{
* IndexArn: string,
* IndexName: string,
* IndexStatus: string,
* KeySchema: [
* { AttributeName: string, KeyType: 'HASH' },
* { AttributeName: string, KeyType: 'RANGE' },
* ]
* BillingModeSummary: {
* BillingMode: 'PAY_PER_REQUEST'|'PROVISIONED',
* },
* ProvisionedThroughput: {
* ReadCapacityUnits: number,
* WriteCapacityUnits: number,
* },
* }>
* ```
*
* Creates the DynamoDB Global Secondary Index.
*
* Arguments:
* * (none)
*
* Return:
* * `IndexArn` - the ARN (Amazon Resource Name) of the Global Secondary Index.
* * `IndexName` - the name of the Global Secondary Index.
* * `IndexStatus` - the currentn status of the Global Secondary Index.
* * `KeySchema` - the [key schema](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_KeySchemaElement.html) of the Global Secondary Index.
* * `BillingModeSummary` - information about the read/write capacity mode of the Global Secondary Index.
* * `BillingMode` - a mode that controls how read and write throughput is billed and how DynamoDB manages capacity for the Global Secondary Index.
* * `ProvisionedThroughput` - information about the provisioned throughput settings of the Global Secondary Index.
* * `ReadCapacityUnits` - number of 4KB strong reads per second.
* * `WriteCapacityUnits` - number of 1KB writes per second.
*
* Billing Modes:
* * `PAY_PER_REQUEST` - on-demand capacity mode. The AWS account is billed per read and write request.
* * `PROVISIONED` - a capacity mode where the reads (RCUs) and writes (WCUs) are predefined.
*
* ```javascript
* const awsCreds = await AwsCredentials('my-profile')
* awsCreds.region = 'us-east-1'
*
* const myTable = new DynamoDBTable({
* name: 'my-table'
* key: [{ id: 'string' }],
* ...awsCreds,
* })
* await myTable.ready
*
* const myTypeTimeGSI = new DynamoDBGlobalSecondaryIndex({
* table: 'my-table',
* key: [{ type: 'string' }, { time: 'number' }],
* ...awsCreds,
* autoReady: false,
* })
*
* await myTypeTimeGSI.create()
* ```
*
* References:
* * [AWS DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Introduction.html)
*/
async create() {
const tableData = await this.describeTable()
let createIndexParams = {
IndexName: this.name,
KeySchema: DynamoDBKeySchema(this.key),
Projection: {
ProjectionType: 'ALL',
},
}
if (tableData.Table.BillingModeSummary.BillingMode == 'PROVISIONED') {
createIndexParams.ProvisionedThroughput = this.ProvisionedThroughput
}
const payload = JSON.stringify({
TableName: this.table,
AttributeDefinitions: DynamoDBAttributeDefinitions(this.key),
GlobalSecondaryIndexUpdates: [{ Create: createIndexParams }],
})
const response =
await this._awsRequest('POST', '/', 'UpdateTable', payload)
if (response.ok) {
const data = await Readable.JSON(response)
const indexData =
data
.TableDescription
.GlobalSecondaryIndexes
?.find(eq(this.name, get('IndexName')))
return indexData
}
throw new AwsError(await Readable.Text(response), response.status)
}
/**
* @name waitForActive
*
* @docs
* ```coffeescript [specscript]
* waitForActive() -> promise Promise<>
* ```
*
* Waits for the DynamoDB Global Secondary Index to be active.
*
* Arguments:
* * (none)
*
* Return:
* * `promise` - a JavaScript promise that resolves when the DynamoDB Global Secondary Index is active.
*
* ```javascript
* const awsCreds = await AwsCredentials('my-profile')
* awsCreds.region = 'us-east-1'
*
* const myTable = new DynamoDBTable({
* name: 'my-table'
* key: [{ id: 'string' }],
* ...awsCreds,
* })
* await myTable.ready
*
* const myTypeTimeGSI = new DynamoDBGlobalSecondaryIndex({
* table: 'my-table',
* key: [{ type: 'string' }, { time: 'number' }],
* ...awsCreds,
* })
*
* await myTypeTimeGSI.waitForActive()
* ```
*
* References:
* * [AWS DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Introduction.html)
*/
async waitForActive() {
let indexData = await this.describe()
while (indexData.IndexStatus != 'ACTIVE') {
await sleep(100)
indexData = await this.describe()
}
}
/**
* @name query
*
* @docs
* ```coffeescript [specscript]
* type DynamoDBJSONKey = {
* [hashKey string]: { S: string }|{ N: number }|{ B: Buffer },
* [sortKey string]: { S: string }|{ N: number }|{ B: Buffer },
* }
*
* type DynamoDBJSONObject = Object<
* [key string]: { S: string }
* |{ N: number }
* |{ B: Buffer }
* |{ L: Array<DynamoDBJSONObject> }
* |{ M: Object<DynamoDBJSONObject> }
* >
*
* query(
* keyConditionExpression string, # 'hashKey = :a AND sortKey < :b'
* Values DynamoDBJSONObject,
* options {
* Limit: number,
* ExclusiveStartKey: DynamoDBJSONKey,
* ScanIndexForward: boolean, # defaults to true for ASC
* ProjectionExpression: string, # 'fieldA,fieldB,fieldC'
* FilterExpression: string, # 'fieldA >= :someValue'
* },
* ) -> data Promise<{
* Items: Array<DynamoDBJSONObject>,
* LastEvaluatedKey: DynamoDBJSONKey,
* }>
* ```
*
* Query a DynamoDB Global Secondary Index using DynamoDB JSON format.
*
* Use the hash and sort keys as query parameters and to construct the key condition expression. The key condition expression is a SQL-like query language comprised of the table's hashKey and sortKey, e.g. `myHashKey = :a AND mySortKey < :b`. Read more about [key condition expressions](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.KeyConditionExpressions.html).
*
* Arguments:
* * `keyConditionExpression` - a query on the hash key and/or sort key of the Global Secondary Index.
* * `Values` - DynamoDB JSON values for each variable (prefixed by `:`) of the query.
* * `options`
* * `Limit` - Maximum number of items (hard limited by the total size of the response).
* * `ExclusiveStartKey` - the primary key after which to start reading.
* * `ScanIndexForward` - if `true`, returned items are sorted in ascending order. If `false` returned items are sorted in descending order. Defaults to `true`.
* * `ProjectionExpression` - list of comma-separated attribute names to be returned for each item in query result, e.g. `fieldA,fieldB,fieldC`.
* * `FilterExpression` - filter queried results by this expression, e.g. `fieldA >= :someValue`.
*
* Return:
* * `data`
* * `Items` - the items of the DynamoDB Global Secondary Index returned from the query.
* * `LastEvaluatedKey` - the primary key of the item where the query stopped.
*
* ```javascript
* const awsCreds = await AwsCredentials('my-profile')
* awsCreds.region = 'us-east-1'
*
* const myTable = new DynamoDBTable({
* name: 'my-table'
* key: [{ id: 'string' }],
* ...awsCreds,
* })
* await myTable.ready
*
* const myStatusTimeIndex = new DynamoDBGlobalSecondaryIndex({
* table: 'my-table',
* key: [{ status: 'string' }, { time: 'number' }],
* ...awsCreds,
* })
* await myStatusTimeIndex.ready
*
* const pendingItemsLast24h = await myStatusTimeIndex.query(
* 'status = :status AND time > :time',
* {
* status: { S: 'pending' },
* time: { N: Date.now() - (24 * 60 * 60 * 1000) },
* },
* { ScanIndexForward: true },
* )
* console.log(pendingItemsLast24h)
* // [
* // { id: { S: 'a' }, status: { S: 'pending' }, time: { N: 1749565352158 } },
* // { id: { S: 'b' }, status: { S: 'pending' }, time: { N: 1749565352159 } },
* // { id: { S: 'c' }, status: { S: 'pending' }, time: { N: 1749565352160 } },
* // ...
* // ]
* ```
*
* References:
* * [AWS DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Introduction.html)
*
* ### FilterExpression Syntax
* ```sh [DynamoDB_ConditionExpression_Syntax]
* <attribute_name> = :<variable_name>
* <attribute_name> <> :<variable_name>
* <attribute_name> < :<variable_name>
* <attribute_name> <= :<variable_name>
* <attribute_name> > :<variable_name>
* <attribute_name> >= :<variable_name>
*
* <attribute_name> BETWEEN :<variable_name1> AND :<variable_name2>
*
* <attribute_name> IN (:<variable_name1>[, :<variable_name2>[, ...]])
*
* <function_name>(<attribute_name>[, :<variable_name>])
*
* <function_name>(<attribute_name>[, :<variable_name1>]) = :<variable_name2>
* <function_name>(<attribute_name>[, :<variable_name1>]) <> :<variable_name2>
* <function_name>(<attribute_name>[, :<variable_name1>]) < :<variable_name2>
* <function_name>(<attribute_name>[, :<variable_name1>]) <= :<variable_name2>
* <function_name>(<attribute_name>[, :<variable_name1>]) > :<variable_name2>
* <function_name>(<attribute_name>[, :<variable_name1>]) >= :<variable_name2>
*
* <expression> AND <expression>
*
* NOT <expression>
*
* (<expression>)
* ```
*
* `FilterExpression` Functions:
* * `attribute_exists(<attribute_name>)` - test if `<attribute_name>` exists.
* * `attribute_not_exists(<attribute_name>)` - test if `<attribute_name>` does not exist.
* * `attribute_type(<attribute_name>, <attribute_type>)` - test if the DynamoDB attribute type of the DynamoDB attribute value of `<attribute_name>` equals `attribute_type`.
* * `contains(<attribute_name>, :<variable_name>)` - test if the DynamoDB attribute value of `<attribute_name>` equals the attribute value provided in `Updates` corresponding to `<variable_name>`.
* * `begins_with(<attribute_name>, :<variable_name>)` - test if the DynamoDB attribute value of `<attribute_name>` equals the attribute value provided in `Updates` corresponding to `<variable_name>`.
* * `size(<attribute_name>)` - returns for evaluation a number that represents the size of the attribute value of `<attribute_name>`
*
* `FilterExpression` Logical Operators:
* * `=` - equals.
* * `<>` - does not equal.
* * `<` - less than.
* * `>` - greater than.
* * `<=` - less than or equal to .
* * `>=` - greater than or equal to.
* * `BETWEEN` - between.
* * `IN` - in.
* * `AND` - and.
* * `OR` - or.
* * `NOT` - not.
*/
async query(keyConditionExpression, Values, options = {}) {
const values = map(Values, DynamoDBAttributeValueJSON)
const keyConditionStatements = keyConditionExpression.trim().split(/\s+AND\s+/)
let statementsIndex = -1
while (++statementsIndex < keyConditionStatements.length) {
if (keyConditionStatements[statementsIndex].includes('BETWEEN')) {
keyConditionStatements[statementsIndex] +=
` AND ${keyConditionStatements.splice(statementsIndex + 1, 1)}`
}
}
const filterExpressionStatements =
options.FilterExpression == null ? []
: options.FilterExpression.trim().split(/\s+AND\s+/)
statementsIndex = -1
while (++statementsIndex < filterExpressionStatements.length) {
if (filterExpressionStatements[statementsIndex].includes('BETWEEN')) {
filterExpressionStatements[statementsIndex] +=
` AND ${filterExpressionStatements.splice(statementsIndex + 1, 1)}`
}
}
const ExpressionAttributeNames = createExpressionAttributeNames({
keyConditionStatements,
filterExpressionStatements,
...options,
})
const ExpressionAttributeValues = createExpressionAttributeValues({ values })
const KeyConditionExpression = createKeyConditionExpression({
keyConditionStatements,
})
const FilterExpression = createFilterExpression({
filterExpressionStatements,
})
const payload = JSON.stringify({
TableName: this.table,
IndexName: this.name,
ExpressionAttributeNames,
ExpressionAttributeValues,
KeyConditionExpression,
ScanIndexForward: options.ScanIndexForward ?? true,
...filterExpressionStatements.length > 0 ? { FilterExpression } : {},
...options.Limit ? { Limit: options.Limit } : {},
...options.ExclusiveStartKey
? { ExclusiveStartKey: options.ExclusiveStartKey }
: {},
...options.ProjectionExpression ? {
ProjectionExpression: options.ProjectionExpression
.split(',').map(field => `#${hashJSON(field)}`).join(','),
} : {},
})
const response = await this._awsRequest('POST', '/', 'Query', payload)
if (response.ok) {
return Readable.JSON(response)
}
throw new AwsError(await Readable.Text(response), response.status)
}
/**
* @name queryJSON
*
* @docs
* ```coffeescript [specscript]
* type DynamoDBJSONKey = {
* [hashKey string]: { S: string }|{ N: number }|{ B: Buffer },
* [sortKey string]: { S: string }|{ N: number }|{ B: Buffer },
* }
*
* type DynamoDBJSONObject = Object<
* [key string]: { S: string }
* |{ N: number }
* |{ B: Buffer }
* |{ L: Array<DynamoDBJSONObject> }
* |{ M: Object<DynamoDBJSONObject> }
* >
*
* type JSONArray = Array<string|number|Buffer|JSONArray|JSONObject>
* type JSONObject = Object<string|number|Buffer|JSONArray|JSONObject>
*
* queryJSON(
* keyConditionExpression string, # 'hashKey = :a AND sortKey < :b'
* values JSONObject,
* options {
* Limit: number,
* ExclusiveStartKey: DynamoDBJSONKey,
* ScanIndexForward: boolean, # defaults to true for ASC
* ProjectionExpression: string, # 'fieldA,fieldB,fieldC'
* FilterExpression: string, # 'fieldA >= :someValue'
* },
* ) -> data Promise<{
* ItemsJSON: Array<JSONObject>,
* LastEvaluatedKey: DynamoDBJSONKey,
* }>
* ```
*
* Query a DynamoDB Global Secondary Index using JSON format.
*
* Use the hash and sort keys as query parameters and to construct the key condition expression. The key condition expression is a SQL-like query language comprised of the table's hashKey and sortKey, e.g. `myHashKey = :a AND mySortKey < :b`. Read more about [key condition expressions](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.KeyConditionExpressions.html).
*
* Arguments:
* * `keyConditionExpression` - a query on the hash key and/or sort key of the Global Secondary Index.
* * `values` - values for each variable (prefixed by `:`) of the query.
* * `options`
* * `Limit` - Maximum number of items (hard limited by the total size of the response).
* * `ExclusiveStartKey` - the primary key after which to start reading.
* * `ScanIndexForward` - if `true`, returned items are sorted in ascending order. If `false` returned items are sorted in descending order. Defaults to `true`.
* * `ProjectionExpression` - list of comma-separated attribute names to be returned for each item in query result, e.g. `fieldA,fieldB,fieldC`.
* * `FilterExpression` - filter queried results by this expression, e.g. `fieldA >= :someValue`.
*
* Return:
* * `data`
* * `ItemsJSON` - the items of the DynamoDB Global Secondary Index returned from the query.
* * `LastEvaluatedKey` - the primary key of the item where the query stopped.
*
* ```javascript
* const awsCreds = await AwsCredentials('my-profile')
* awsCreds.region = 'us-east-1'
*
* const myTable = new DynamoDBTable({
* name: 'my-table'
* key: [{ id: 'string' }],
* ...awsCreds,
* })
* await myTable.ready
*
* const myStatusTimeIndex = new DynamoDBGlobalSecondaryIndex({
* table: 'my-table',
* key: [{ status: 'string' }, { time: 'number' }],
* ...awsCreds,
* })
* await myStatusTimeIndex.ready
*
* const pendingItemsJSONLast24h = await myStatusTimeIndex.queryJSON(
* 'status = :status AND time > :time',
* {
* status: 'pending',
* time: Date.now() - (24 * 60 * 60 * 1000),
* },
* { ScanIndexForward: true },
* )
* console.log(pendingItemsJSONLast24h)
* // [
* // { id: 'a', status: 'pending', time: 1749565352158 },
* // { id: 'b', status: 'pending', time: 1749565352159 },
* // { id: 'c', status: 'pending', time: 1749565352160 },
* // ...
* // ]
* ```
*
* References:
* * [AWS DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Introduction.html)
*
* ### FilterExpression Syntax
* ```sh [DynamoDB_ConditionExpression_Syntax]
* <attribute_name> = :<variable_name>
* <attribute_name> <> :<variable_name>
* <attribute_name> < :<variable_name>
* <attribute_name> <= :<variable_name>
* <attribute_name> > :<variable_name>
* <attribute_name> >= :<variable_name>
*
* <attribute_name> BETWEEN :<variable_name1> AND :<variable_name2>
*
* <attribute_name> IN (:<variable_name1>[, :<variable_name2>[, ...]])
*
* <function_name>(<attribute_name>[, :<variable_name>])
*
* <function_name>(<attribute_name>[, :<variable_name1>]) = :<variable_name2>
* <function_name>(<attribute_name>[, :<variable_name1>]) <> :<variable_name2>
* <function_name>(<attribute_name>[, :<variable_name1>]) < :<variable_name2>
* <function_name>(<attribute_name>[, :<variable_name1>]) <= :<variable_name2>
* <function_name>(<attribute_name>[, :<variable_name1>]) > :<variable_name2>
* <function_name>(<attribute_name>[, :<variable_name1>]) >= :<variable_name2>
*
* <expression> AND <expression>
*
* NOT <expression>
*
* (<expression>)
* ```
*
* `FilterExpression` Functions:
* * `attribute_exists(<attribute_name>)` - test if `<attribute_name>` exists.
* * `attribute_not_exists(<attribute_name>)` - test if `<attribute_name>` does not exist.
* * `attribute_type(<attribute_name>, <attribute_type>)` - test if the DynamoDB attribute type of the DynamoDB attribute value of `<attribute_name>` equals `attribute_type`.
* * `contains(<attribute_name>, :<variable_name>)` - test if the DynamoDB attribute value of `<attribute_name>` equals the attribute value provided in `Updates` corresponding to `<variable_name>`.
* * `begins_with(<attribute_name>, :<variable_name>)` - test if the DynamoDB attribute value of `<attribute_name>` equals the attribute value provided in `Updates` corresponding to `<variable_name>`.
* * `size(<attribute_name>)` - returns for evaluation a number that represents the size of the attribute value of `<attribute_name>`
*
* `FilterExpression` Logical Operators:
* * `=` - equals.
* * `<>` - does not equal.
* * `<` - less than.
* * `>` - greater than.
* * `<=` - less than or equal to .
* * `>=` - greater than or equal to.
* * `BETWEEN` - between.
* * `IN` - in.
* * `AND` - and.
* * `OR` - or.
* * `NOT` - not.
*/
async queryJSON(keyConditionExpression, values, options = {}) {
const keyConditionStatements = keyConditionExpression.trim().split(/\s+AND\s+/)
let statementsIndex = -1
while (++statementsIndex < keyConditionStatements.length) {
if (keyConditionStatements[statementsIndex].includes('BETWEEN')) {
keyConditionStatements[statementsIndex] +=
` AND ${keyConditionStatements.splice(statementsIndex + 1, 1)}`
}
}
const filterExpressionStatements =
options.FilterExpression == null ? []
: options.FilterExpression.trim().split(/\s+AND\s+/)
statementsIndex = -1
while (++statementsIndex < filterExpressionStatements.length) {
if (filterExpressionStatements[statementsIndex].includes('BETWEEN')) {
filterExpressionStatements[statementsIndex] +=
` AND ${filterExpressionStatements.splice(statementsIndex + 1, 1)}`
}
}
const ExpressionAttributeNames = createExpressionAttributeNames({
keyConditionStatements,
filterExpressionStatements,
...options,
})
const ExpressionAttributeValues = createExpressionAttributeValues({ values })
const KeyConditionExpression = createKeyConditionExpression({
keyConditionStatements,
})
const FilterExpression = createFilterExpression({
filterExpressionStatements,
})
const payload = JSON.stringify({
TableName: this.table,
IndexName: this.name,
ExpressionAttributeNames,
ExpressionAttributeValues,
KeyConditionExpression,
ScanIndexForward: options.ScanIndexForward ?? true,
...filterExpressionStatements.length > 0 ? { FilterExpression } : {},
...options.Limit ? { Limit: options.Limit } : {},
...options.ExclusiveStartKey
? { ExclusiveStartKey: options.ExclusiveStartKey }
: {},
...options.ProjectionExpression ? {
ProjectionExpression: options.ProjectionExpression
.split(',').map(field => `#${hashJSON(field)}`).join(','),
} : {},
})
const response = await this._awsRequest('POST', '/', 'Query', payload)
if (response.ok) {
const data = await Readable.JSON(response)
data.ItemsJSON = map(data.Items, map(DynamoDBAttributeValueJSON))
delete data.Items
return data
}
throw new AwsError(await Readable.Text(response), response.status)
}
/**
* @name queryItemsIterator
*
* @docs
* ```coffeescript [specscript]
* type JSONObject = Object<[key string]: string|number|binary|Array|Object>
* type DynamoDBJSONObject = Object<
* [key string]: { S: string }
* |{ N: number }
* |{ B: Buffer }
* |{ L: Array<DynamoDBJSONObject> }
* |{ M: Object<DynamoDBJSONObject> }
* >
*
* queryItemsIterator(
* keyConditionExpression string,
* Values DynamoDBJSONObject,
* options {
* BatchLimit: number,
* Limit: number,
* ScanIndexForward: boolean, // default true for ASC
* ProjectionExpression: string, // 'fieldA,fieldB,fieldC'
* FilterExpression: string, // 'fieldA >= :someValue'
* }
* ) -> asyncIterator AsyncIterator<DynamoDBJSONObject>
* ```
*
* Returns an async iterator of all items represented by a query on a DynamoDB Global Secondary Index (GSI) in DynamoDB JSON format.
*
* The key condition expression is a SQL-like query language comprised of the table's hashKey and sortKey, e.g. `myHashKey = :a AND mySortKey < :b`. Read more about [key condition expressions](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.KeyConditionExpressions.html).
*
* Arguments:
* * `keyConditionExpression` - a query on the hash key and/or sort key of the Global Secondary Index.
* * `Values` - DynamoDB JSON values for each variable (prefixed by `:`) of the query.
* * `options`
* * `BatchLimit` - Maximum number of items to retrieve per `query` call.
* * `Limit` - the maximum number of items to return for the [DynamoDB Query](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Query.html) operation. If the processed dataset size exceeds 1MB during the operation, DynamoDB will stop the operation before reaching the maximum number of items specified by `Limit`.
* * `ScanIndexForward` - if `true`, returned items are sorted in ascending order. If `false` returned items are sorted in descending order. Defaults to `true`.
* * `ProjectionExpression` - list of comma-separated attribute names to be returned for each item in query result, e.g. `fieldA,fieldB,fieldC`.
* * `FilterExpression` - filter queried results by this expression, e.g. `fieldA >= :someValue`.
*
* Return:
* * `asyncIterator` - an async iterator of all items in DynamoDB JSON format represented by the query on the DynamoDB Global Secondary Index.
*
* ```javascript
* const awsCreds = await AwsCredentials('my-profile')
* awsCreds.region = 'us-east-1'
*
* const myTable = new DynamoDBTable({
* name: 'my-table'