document_client.js
17.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
var AWS = require('../core');
var Translator = require('./translator');
var DynamoDBSet = require('./set');
/**
* The document client simplifies working with items in Amazon DynamoDB
* by abstracting away the notion of attribute values. This abstraction
* annotates native JavaScript types supplied as input parameters, as well
* as converts annotated response data to native JavaScript types.
*
* ## Marshalling Input and Unmarshalling Response Data
*
* The document client affords developers the use of native JavaScript types
* instead of `AttributeValue`s to simplify the JavaScript development
* experience with Amazon DynamoDB. JavaScript objects passed in as parameters
* are marshalled into `AttributeValue` shapes required by Amazon DynamoDB.
* Responses from DynamoDB are unmarshalled into plain JavaScript objects
* by the `DocumentClient`. The `DocumentClient`, does not accept
* `AttributeValue`s in favor of native JavaScript types.
*
* | JavaScript Type | DynamoDB AttributeValue |
* |:----------------------------------------------------------------------:|-------------------------|
* | String | S |
* | Number | N |
* | Boolean | BOOL |
* | null | NULL |
* | Array | L |
* | Object | M |
* | Buffer, File, Blob, ArrayBuffer, DataView, and JavaScript typed arrays | B |
*
* ## Support for Sets
*
* The `DocumentClient` offers a convenient way to create sets from
* JavaScript Arrays. The type of set is inferred from the first element
* in the array. DynamoDB supports string, number, and binary sets. To
* learn more about supported types see the
* [Amazon DynamoDB Data Model Documentation](http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataModel.html)
* For more information see {AWS.DynamoDB.DocumentClient.createSet}
*
*/
AWS.DynamoDB.DocumentClient = AWS.util.inherit({
/**
* Creates a DynamoDB document client with a set of configuration options.
*
* @option options params [map] An optional map of parameters to bind to every
* request sent by this service object.
* @option options service [AWS.DynamoDB] An optional pre-configured instance
* of the AWS.DynamoDB service object to use for requests. The object may
* bound parameters used by the document client.
* @option options convertEmptyValues [Boolean] set to true if you would like
* the document client to convert empty values (0-length strings, binary
* buffers, and sets) to be converted to NULL types when persisting to
* DynamoDB.
* @see AWS.DynamoDB.constructor
*
*/
constructor: function DocumentClient(options) {
var self = this;
self.options = options || {};
self.configure(self.options);
},
/**
* @api private
*/
configure: function configure(options) {
var self = this;
self.service = options.service;
self.bindServiceObject(options);
self.attrValue = options.attrValue =
self.service.api.operations.putItem.input.members.Item.value.shape;
},
/**
* @api private
*/
bindServiceObject: function bindServiceObject(options) {
var self = this;
options = options || {};
if (!self.service) {
self.service = new AWS.DynamoDB(options);
} else {
var config = AWS.util.copy(self.service.config);
self.service = new self.service.constructor.__super__(config);
self.service.config.params =
AWS.util.merge(self.service.config.params || {}, options.params);
}
},
/**
* @api private
*/
makeServiceRequest: function(operation, params, callback) {
var self = this;
var request = self.service[operation](params);
self.setupRequest(request);
self.setupResponse(request);
if (typeof callback === 'function') {
request.send(callback);
}
return request;
},
/**
* @api private
*/
serviceClientOperationsMap: {
batchGet: 'batchGetItem',
batchWrite: 'batchWriteItem',
delete: 'deleteItem',
get: 'getItem',
put: 'putItem',
query: 'query',
scan: 'scan',
update: 'updateItem',
transactGet: 'transactGetItems',
transactWrite: 'transactWriteItems'
},
/**
* Returns the attributes of one or more items from one or more tables
* by delegating to `AWS.DynamoDB.batchGetItem()`.
*
* Supply the same parameters as {AWS.DynamoDB.batchGetItem} with
* `AttributeValue`s substituted by native JavaScript types.
*
* @see AWS.DynamoDB.batchGetItem
* @example Get items from multiple tables
* var params = {
* RequestItems: {
* 'Table-1': {
* Keys: [
* {
* HashKey: 'haskey',
* NumberRangeKey: 1
* }
* ]
* },
* 'Table-2': {
* Keys: [
* { foo: 'bar' },
* ]
* }
* }
* };
*
* var documentClient = new AWS.DynamoDB.DocumentClient();
*
* documentClient.batchGet(params, function(err, data) {
* if (err) console.log(err);
* else console.log(data);
* });
*
*/
batchGet: function(params, callback) {
var operation = this.serviceClientOperationsMap['batchGet'];
return this.makeServiceRequest(operation, params, callback);
},
/**
* Puts or deletes multiple items in one or more tables by delegating
* to `AWS.DynamoDB.batchWriteItem()`.
*
* Supply the same parameters as {AWS.DynamoDB.batchWriteItem} with
* `AttributeValue`s substituted by native JavaScript types.
*
* @see AWS.DynamoDB.batchWriteItem
* @example Write to and delete from a table
* var params = {
* RequestItems: {
* 'Table-1': [
* {
* DeleteRequest: {
* Key: { HashKey: 'someKey' }
* }
* },
* {
* PutRequest: {
* Item: {
* HashKey: 'anotherKey',
* NumAttribute: 1,
* BoolAttribute: true,
* ListAttribute: [1, 'two', false],
* MapAttribute: { foo: 'bar' }
* }
* }
* }
* ]
* }
* };
*
* var documentClient = new AWS.DynamoDB.DocumentClient();
*
* documentClient.batchWrite(params, function(err, data) {
* if (err) console.log(err);
* else console.log(data);
* });
*
*/
batchWrite: function(params, callback) {
var operation = this.serviceClientOperationsMap['batchWrite'];
return this.makeServiceRequest(operation, params, callback);
},
/**
* Deletes a single item in a table by primary key by delegating to
* `AWS.DynamoDB.deleteItem()`
*
* Supply the same parameters as {AWS.DynamoDB.deleteItem} with
* `AttributeValue`s substituted by native JavaScript types.
*
* @see AWS.DynamoDB.deleteItem
* @example Delete an item from a table
* var params = {
* TableName : 'Table',
* Key: {
* HashKey: 'hashkey',
* NumberRangeKey: 1
* }
* };
*
* var documentClient = new AWS.DynamoDB.DocumentClient();
*
* documentClient.delete(params, function(err, data) {
* if (err) console.log(err);
* else console.log(data);
* });
*
*/
delete: function(params, callback) {
var operation = this.serviceClientOperationsMap['delete'];
return this.makeServiceRequest(operation, params, callback);
},
/**
* Returns a set of attributes for the item with the given primary key
* by delegating to `AWS.DynamoDB.getItem()`.
*
* Supply the same parameters as {AWS.DynamoDB.getItem} with
* `AttributeValue`s substituted by native JavaScript types.
*
* @see AWS.DynamoDB.getItem
* @example Get an item from a table
* var params = {
* TableName : 'Table',
* Key: {
* HashKey: 'hashkey'
* }
* };
*
* var documentClient = new AWS.DynamoDB.DocumentClient();
*
* documentClient.get(params, function(err, data) {
* if (err) console.log(err);
* else console.log(data);
* });
*
*/
get: function(params, callback) {
var operation = this.serviceClientOperationsMap['get'];
return this.makeServiceRequest(operation, params, callback);
},
/**
* Creates a new item, or replaces an old item with a new item by
* delegating to `AWS.DynamoDB.putItem()`.
*
* Supply the same parameters as {AWS.DynamoDB.putItem} with
* `AttributeValue`s substituted by native JavaScript types.
*
* @see AWS.DynamoDB.putItem
* @example Create a new item in a table
* var params = {
* TableName : 'Table',
* Item: {
* HashKey: 'haskey',
* NumAttribute: 1,
* BoolAttribute: true,
* ListAttribute: [1, 'two', false],
* MapAttribute: { foo: 'bar'},
* NullAttribute: null
* }
* };
*
* var documentClient = new AWS.DynamoDB.DocumentClient();
*
* documentClient.put(params, function(err, data) {
* if (err) console.log(err);
* else console.log(data);
* });
*
*/
put: function(params, callback) {
var operation = this.serviceClientOperationsMap['put'];
return this.makeServiceRequest(operation, params, callback);
},
/**
* Edits an existing item's attributes, or adds a new item to the table if
* it does not already exist by delegating to `AWS.DynamoDB.updateItem()`.
*
* Supply the same parameters as {AWS.DynamoDB.updateItem} with
* `AttributeValue`s substituted by native JavaScript types.
*
* @see AWS.DynamoDB.updateItem
* @example Update an item with expressions
* var params = {
* TableName: 'Table',
* Key: { HashKey : 'hashkey' },
* UpdateExpression: 'set #a = :x + :y',
* ConditionExpression: '#a < :MAX',
* ExpressionAttributeNames: {'#a' : 'Sum'},
* ExpressionAttributeValues: {
* ':x' : 20,
* ':y' : 45,
* ':MAX' : 100,
* }
* };
*
* var documentClient = new AWS.DynamoDB.DocumentClient();
*
* documentClient.update(params, function(err, data) {
* if (err) console.log(err);
* else console.log(data);
* });
*
*/
update: function(params, callback) {
var operation = this.serviceClientOperationsMap['update'];
return this.makeServiceRequest(operation, params, callback);
},
/**
* Returns one or more items and item attributes by accessing every item
* in a table or a secondary index.
*
* Supply the same parameters as {AWS.DynamoDB.scan} with
* `AttributeValue`s substituted by native JavaScript types.
*
* @see AWS.DynamoDB.scan
* @example Scan the table with a filter expression
* var params = {
* TableName : 'Table',
* FilterExpression : 'Year = :this_year',
* ExpressionAttributeValues : {':this_year' : 2015}
* };
*
* var documentClient = new AWS.DynamoDB.DocumentClient();
*
* documentClient.scan(params, function(err, data) {
* if (err) console.log(err);
* else console.log(data);
* });
*
*/
scan: function(params, callback) {
var operation = this.serviceClientOperationsMap['scan'];
return this.makeServiceRequest(operation, params, callback);
},
/**
* Directly access items from a table by primary key or a secondary index.
*
* Supply the same parameters as {AWS.DynamoDB.query} with
* `AttributeValue`s substituted by native JavaScript types.
*
* @see AWS.DynamoDB.query
* @example Query an index
* var params = {
* TableName: 'Table',
* IndexName: 'Index',
* KeyConditionExpression: 'HashKey = :hkey and RangeKey > :rkey',
* ExpressionAttributeValues: {
* ':hkey': 'key',
* ':rkey': 2015
* }
* };
*
* var documentClient = new AWS.DynamoDB.DocumentClient();
*
* documentClient.query(params, function(err, data) {
* if (err) console.log(err);
* else console.log(data);
* });
*
*/
query: function(params, callback) {
var operation = this.serviceClientOperationsMap['query'];
return this.makeServiceRequest(operation, params, callback);
},
/**
* Synchronous write operation that groups up to 10 action requests
*
* Supply the same parameters as {AWS.DynamoDB.transactWriteItems} with
* `AttributeValue`s substituted by native JavaScript types.
*
* @see AWS.DynamoDB.transactWriteItems
* @example Get items from multiple tables
* var params = {
* TransactItems: [{
* Put: {
* TableName : 'Table0',
* Item: {
* HashKey: 'haskey',
* NumAttribute: 1,
* BoolAttribute: true,
* ListAttribute: [1, 'two', false],
* MapAttribute: { foo: 'bar'},
* NullAttribute: null
* }
* }
* }, {
* Update: {
* TableName: 'Table1',
* Key: { HashKey : 'hashkey' },
* UpdateExpression: 'set #a = :x + :y',
* ConditionExpression: '#a < :MAX',
* ExpressionAttributeNames: {'#a' : 'Sum'},
* ExpressionAttributeValues: {
* ':x' : 20,
* ':y' : 45,
* ':MAX' : 100,
* }
* }
* }]
* };
*
* documentClient.transactWrite(params, function(err, data) {
* if (err) console.log(err);
* else console.log(data);
* });
*/
transactWrite: function(params, callback) {
var operation = this.serviceClientOperationsMap['transactWrite'];
return this.makeServiceRequest(operation, params, callback);
},
/**
* Atomically retrieves multiple items from one or more tables (but not from indexes)
* in a single account and region.
*
* Supply the same parameters as {AWS.DynamoDB.transactGetItems} with
* `AttributeValue`s substituted by native JavaScript types.
*
* @see AWS.DynamoDB.transactGetItems
* @example Get items from multiple tables
* var params = {
* TransactItems: [{
* Get: {
* TableName : 'Table0',
* Key: {
* HashKey: 'hashkey0'
* }
* }
* }, {
* Get: {
* TableName : 'Table1',
* Key: {
* HashKey: 'hashkey1'
* }
* }
* }]
* };
*
* documentClient.transactGet(params, function(err, data) {
* if (err) console.log(err);
* else console.log(data);
* });
*/
transactGet: function(params, callback) {
var operation = this.serviceClientOperationsMap['transactGet'];
return this.makeServiceRequest(operation, params, callback);
},
/**
* Creates a set of elements inferring the type of set from
* the type of the first element. Amazon DynamoDB currently supports
* the number sets, string sets, and binary sets. For more information
* about DynamoDB data types see the documentation on the
* [Amazon DynamoDB Data Model](http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataModel.html#DataModel.DataTypes).
*
* @param list [Array] Collection to represent your DynamoDB Set
* @param options [map]
* * **validate** [Boolean] set to true if you want to validate the type
* of each element in the set. Defaults to `false`.
* @example Creating a number set
* var documentClient = new AWS.DynamoDB.DocumentClient();
*
* var params = {
* Item: {
* hashkey: 'hashkey'
* numbers: documentClient.createSet([1, 2, 3]);
* }
* };
*
* documentClient.put(params, function(err, data) {
* if (err) console.log(err);
* else console.log(data);
* });
*
*/
createSet: function(list, options) {
options = options || {};
return new DynamoDBSet(list, options);
},
/**
* @api private
*/
getTranslator: function() {
return new Translator(this.options);
},
/**
* @api private
*/
setupRequest: function setupRequest(request) {
var self = this;
var translator = self.getTranslator();
var operation = request.operation;
var inputShape = request.service.api.operations[operation].input;
request._events.validate.unshift(function(req) {
req.rawParams = AWS.util.copy(req.params);
req.params = translator.translateInput(req.rawParams, inputShape);
});
},
/**
* @api private
*/
setupResponse: function setupResponse(request) {
var self = this;
var translator = self.getTranslator();
var outputShape = self.service.api.operations[request.operation].output;
request.on('extractData', function(response) {
response.data = translator.translateOutput(response.data, outputShape);
});
var response = request.response;
response.nextPage = function(cb) {
var resp = this;
var req = resp.request;
var config;
var service = req.service;
var operation = req.operation;
try {
config = service.paginationConfig(operation, true);
} catch (e) { resp.error = e; }
if (!resp.hasNextPage()) {
if (cb) cb(resp.error, null);
else if (resp.error) throw resp.error;
return null;
}
var params = AWS.util.copy(req.rawParams);
if (!resp.nextPageTokens) {
return cb ? cb(null, null) : null;
} else {
var inputTokens = config.inputToken;
if (typeof inputTokens === 'string') inputTokens = [inputTokens];
for (var i = 0; i < inputTokens.length; i++) {
params[inputTokens[i]] = resp.nextPageTokens[i];
}
return self[operation](params, cb);
}
};
}
});
/**
* @api private
*/
module.exports = AWS.DynamoDB.DocumentClient;