Debian Codegraph @

dojox/store/DynamoDB.js

raw symbols SCIP
1 define([
2 'dojo/_base/declare',
3 'dojo/Stateful',
4 'dojo/request',
5 'dojo/store/util/QueryResults',
6 'dojo/store/util/SimpleQueryEngine',
7 'dojo/_base/lang',
8 'dojo/_base/array',
9 'dojo/errors/RequestError',
10 'dojo/Deferred',
11 '../encoding/digests/SHA256',
12 '../encoding/digests/_base',
13 'dojo/has!host-node?dojo/node!url'
14 ], function (
15 declare,
16 Stateful,
17 request,
18 createQueryResults,
19 SimpleQueryEngine,
20 lang,
21 arrayUtil,
22 RequestError,
23 Deferred,
24 hash,
25 digests,
26 nodeUrl
27 ) {
28 // summary:
29 // This module provides a `dojo/store` interface to an Amazon DynamoDB table. It must be configured for a
30 // specific AWS region, and the user must provide permanent or temporary authorization credentials to allow
31 // access to the table.
32 //
33 // A typical store creation using temporary access credentials would look like:
34 // | var store new DynamoDB({
35 // | tableName: 'myData',
36 // | idProperty: 'id',
37 // | region: 'us-east-1',
38 // | credentials: {
39 // | AccessKeyId: 'abc123',
40 // | SecretAccessKey: 'def456',
41 // | SessionToken: 'ghi6789'
42 // | }
43 // | }));
44 //
45 // Note that this module supports version 4 AWS signatures, which is the version supported by the AWS SDKs.
46 // See http://docs.aws.amazon.com/general/latest/gr/signing_aws_api_requests.html for additional information
47 // about AWS request signing.
48
49 function hmac(key, data, outputType) {
50 // summary:
51 // Convenience function for computing the HMAC. Output is returned as a binary string by default to allow
52 // for successive calls.
53 // returns: string
54
55 outputType = outputType || digests.outputTypes.String;
56 return hash._hmac(data, key, outputType);
57 }
58
59 function getSigningKey(shortDate, secretKey, region) {
60 // summary:
61 // Get an AWS signing key for the current date.
62 // returns: string
63
64 this._signingDate = shortDate;
65 var kDate = hmac('AWS4' + secretKey, shortDate);
66 var kRegion = hmac(kDate, region);
67 var kService = hmac(kRegion, 'dynamodb');
68 return hmac(kService, 'aws4_request');
69 }
70
71 function toUTCString(date) {
72 // summary:
73 // Convert a given date to a UTC datetime string.
74 // returns: string
75
76 function twoDigit(value) {
77 value = String(value);
78 return value.length === 1 ? '0' + value : value;
79 }
80 var year = String(date.getUTCFullYear());
81 var month = twoDigit(date.getUTCMonth() + 1);
82 var day = twoDigit(date.getUTCDate());
83 var hour = twoDigit(date.getUTCHours());
84 var minute = twoDigit(date.getUTCMinutes());
85 var second = twoDigit(date.getUTCSeconds());
86 return year + month + day + 'T' + hour + minute + second + 'Z';
87 }
88
89 function getHostName(url) {
90 // summary:
91 // Extract the hostname from a URL.
92 // returns: string
93
94 if (typeof document !== 'undefined') {
95 var a = document.createElement('a');
96 a.href = url;
97 return a.hostname;
98 }
99 else {
100 url = nodeUrl.parse(url);
101 return url.hostname;
102 }
103 }
104
105 function getDynamoType(value) {
106 // summary:
107 // Return the corresponding DynamoDB type for the given value
108 // returns: string
109
110 if (value == null) {
111 // return NULL for null or undefined values
112 return 'NULL';
113 }
114
115 var type = typeof value;
116
117 if (type === 'string') {
118 return 'S';
119 }
120
121 if (type === 'boolean') {
122 return 'BOOL';
123 }
124
125 if (type === 'number') {
126 return 'N';
127 }
128
129 if (value instanceof Array) {
130 // DynamoDB array equivalent is 'List'
131 return 'L';
132 }
133
134 // default to 'Map', the DynamoDB equivalent to a JavaScript object
135 return 'M';
136 }
137
138 function getDynamoValue(value) {
139 // summary:
140 // Convert a JavaScript value into a DynamoDB typed object.
141 // returns: Object
142
143 var type = getDynamoType(value);
144 var dynamoValue = {};
145 var returnValue;
146
147 switch (type) {
148 case 'BOOL':
149 case 'S':
150 returnValue = value;
151 break;
152 case 'N':
153 returnValue = String(value);
154 break;
155 case 'NULL':
156 returnValue = true;
157 break;
158 case 'M':
159 returnValue = {};
160 for (var key in value) {
161 returnValue[key] = getDynamoValue(value[key]);
162 }
163 break;
164 case 'L':
165 returnValue = [];
166 for (var i = 0; i < value.length; i++) {
167 returnValue[i] = getDynamoValue(value[i]);
168 }
169 break;
170 default:
171 throw new Error('Unknown Dynamo type: ' + type);
172 }
173
174 dynamoValue[type] = returnValue;
175 return dynamoValue;
176 }
177
178 function getNativeValue(dynamoValue) {
179 // summary:
180 // Convert a DynamoDB value into a JavaScript value.
181 // returns: any
182
183 var type;
184 var value;
185
186 // fill in the type and value variables from the dynamoValue, which is a { type: value } object
187 for (type in dynamoValue) {
188 value = dynamoValue[type];
189 }
190
191 function parse(value) {
192 if (type === 'N') {
193 return Number(value);
194 }
195 if (type === 'NULL') {
196 return null;
197 }
198 if (type === 'L') {
199 return arrayUtil.map(value, function (value) {
200 return getNativeValue(value);
201 });
202 }
203 if (type === 'M') {
204 var returnValue = {};
205 for (var key in value) {
206 returnValue[key] = getNativeValue(value[key]);
207 }
208 return returnValue;
209 }
210
211 // strings, booleans, and binary data are returned as-is
212 return value;
213 }
214
215 if (type.charAt(1) === 'S') {
216 // type is a StringSet, NumberSet, or BinarySet -- set type to the contained type, parse each contained
217 // element, and return in an array
218 type = type.charAt(0);
219 return arrayUtil.map(value, parse);
220 }
221
222 return parse(value);
223 }
224
225 function toDynamoObject(object) {
226 // summary:
227 // Convert a JavaScript object to a format consumable by DynamoDB.
228 // returns: Object
229
230 var dynamoObject = {};
231 for (var k in object) {
232 dynamoObject[k] = getDynamoValue(object[k]);
233 }
234 return dynamoObject;
235 }
236
237 function fromDynamoObject(dynamoObject) {
238 // summary:
239 // Converts a DynamoDB hash map to one that conforms to normal JavaScript object conventions.
240 // returns: Object|null
241
242 if (!dynamoObject) {
243 return null;
244 }
245
246 var object = {};
247 for (var k in dynamoObject) {
248 object[k] = getNativeValue(dynamoObject[k]);
249 }
250
251 return object;
252 }
253
254 return declare(Stateful, {
255 // summary:
256 // DynamoDB provides a `dojo/store` interface to an Amazon DynamoDB table.
257
258 // tableName: string
259 // The name of the DynamoDB table being accessed by this store.
260 tableName: '',
261
262 // attributesToGet: Array?
263 // An optional array of attribute key names that should be fetched when retrieving an object from the
264 // table. If `null`, all attributes will be retrieved.
265 attributesToGet: null,
266
267 // consistentRead: boolean
268 // Whether or not to enforce consistent reads on the table.
269 consistentRead: false,
270
271 // maxRetries: number
272 // The maximum number of times a request to the server should be retried before treating it as a failure.
273 maxRetries: 5,
274
275 // idProperty: string|string[]
276 // The names of the property or properties that are used as the primary key within the DynamoDB. If using
277 // a hash table, this should be the hash key name; if using a hash+range table, this should be an array
278 // of both the hash and range key names.
279 idProperty: 'id',
280
281 // queryEngine: SimpleQueryEngine
282 // Provides basic support for using DynamoDB with Observable. Not necessarily reliable since it does
283 // not account for record changes on the server or any special server sort ordering.
284 queryEngine: SimpleQueryEngine,
285
286 // region: string
287 // The AWS region that the target DynamoDB instance is running in.
288 region: null,
289
290 // endpointUrl: string?
291 // An optional URL to the DynamoDB endpoint. If this URL not specified, it will be generated using the
292 // region property.
293 endpointUrl: null,
294
295 // credentials: object?
296 // An optional object containing AWS authorization credentials. Currently three properties are
297 // used:
298 // AccessKeyId: string
299 // An AWS access key, temporary or permanent.
300 // SecretAccessKey: string
301 // An AWS secret key, temporary or permanent.
302 // SessionToken: string?
303 // An optional temporary session token.
304 //
305 // The credentials object uses AWS standard property names, so the Credentials property of a
306 // credentials object returned by the Security Token Service can be used directly with the DynamoDB
307 // store. More information about temporary credentials and security tokens is available at
308 // http://docs.aws.amazon.com/STS/latest/UsingSTS/Welcome.html
309 credentials: null,
310
311 _signRequest: function (/*object*/ request, /*Date?*/ date) {
312 // summary:
313 // Sign an object containing request data. The result of signing is that three additional headers
314 // will be added to the request. See http://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html
315 // for more information about the signing process.
316 //
317 // request: Object
318 // Object with keys:
319 // body: request body
320 // host: DynamoDB host
321 // headers: Request headers -- these will be updated
322 // method: HTTP method
323 // date: Date
324 // Optional time of the request. If not specified, the current time is used.
325 // returns:
326 // None
327
328 date = toUTCString(date || new Date());
329 var shortDate = date.slice(0, 8);
330 var secretKey = this.credentials.SecretAccessKey;
331 var accessKey = this.credentials.AccessKeyId;
332 var sessionToken = this.credentials.SessionToken;
333 var tokenHeader = '';
334 var tokenTag = '';
335
336 request.headers['x-amz-date'] = date;
337
338 if (sessionToken) {
339 tokenHeader = 'x-amz-security-token:' + sessionToken + '\n';
340 tokenTag = ';x-amz-security-token';
341 request.headers['x-amz-security-token'] = sessionToken;
342 }
343
344 var canonicalRequest = request.method + '\n/\n\n' +
345 'host:' + request.host + '\n' +
346 'x-amz-date:' + date + '\n' +
347 tokenHeader +
348 'x-amz-target:' + request.headers['x-amz-target'] + '\n' +
349 '\n' +
350 'host;x-amz-date' + tokenTag +
351 ';x-amz-target\n' + hash(request.body, digests.outputTypes.Hex);
352
353 var key = getSigningKey(shortDate, secretKey, this.region);
354
355 var stringToSign = 'AWS4-HMAC-SHA256\n' +
356 date + '\n' +
357 shortDate + '/' + this.region + '/dynamodb/aws4_request\n' +
358 hash(canonicalRequest, digests.outputTypes.Hex);
359
360 var signature = hmac(key, stringToSign, digests.outputTypes.Hex);
361
362 request.headers.authorization = 'AWS4-HMAC-SHA256 Credential=' + accessKey + '/' + shortDate + '/' +
363 this.region + '/dynamodb/aws4_request,SignedHeaders=host;x-amz-date;x-amz-target' + tokenTag +
364 ',Signature=' + signature;
365 },
366
367 _rpc: function (/**string*/ action, /**Object*/ data) {
368 // summary:
369 // A convenience method for sending requests to DynamoDB with improved error reporting and error
370 // retries
371 // (<http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ErrorHandling.html#APIRetries>).
372 // action:
373 // The name of the action to perform. See
374 // <http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Operations.html> for a list.
375 // data:
376 // The request payload.
377 // returns: dojo/promise/Promise -> Object
378
379 var timeoutId;
380 var requestPromise;
381 var dfd = new Deferred(function () {
382 requestPromise && requestPromise.cancel.apply(request, arguments);
383 clearTimeout(timeoutId);
384 });
385 var headers = {
386 'Content-Type': 'application/x-amz-json-1.0',
387 'x-amz-target': 'DynamoDB_20120810.' + action
388 };
389
390 data.TableName = this.tableName;
391 data = JSON.stringify(data);
392
393 // if no endpoint URL has been specified, create one from the AWS region
394 if (!this.endpointUrl) {
395 this.endpointUrl = 'https://dynamodb.' + this.region + '.amazonaws.com';
396 }
397
398 // only sign the request if credentials were provided
399 if (this.credentials) {
400 this._signRequest({
401 body: data,
402 host: getHostName(this.endpointUrl),
403 method: 'POST',
404 headers: headers
405 });
406 }
407
408 var endpointUrl = this.endpointUrl;
409 var maxRetries = this.maxRetries;
410 var currentRetry = 0;
411
412 (function sendRequest() {
413 requestPromise = request.post(endpointUrl, {
414 data: data,
415 headers: headers,
416 handleAs: 'json'
417 }).then(lang.hitch(dfd, 'resolve'), function (error) {
418 var response = error.response;
419
420 if (++currentRetry === maxRetries) {
421 dfd.reject(error);
422 return;
423 }
424
425 if (response.status >= 500 || response.status < 400 ||
426 (response.status === 400 && response.data && response.data.__type &&
427 (response.data.__type.indexOf('#ProvisionedThroughputExceededException') > -1 ||
428 response.data.__type.indexOf('#ThrottlingException') > -1))
429 ) {
430 timeoutId = setTimeout(sendRequest, Math.pow(2, currentRetry) * 50);
431 }
432 else {
433 dfd.reject(error);
434 }
435 });
436 })();
437
438 return dfd.promise.then(function (response) {
439 return response;
440 }, function (error) {
441 var errorInfo = error.response && error.response.data;
442 if (errorInfo) {
443 throw new RequestError(errorInfo.__type + ': ' + errorInfo.message, error.response);
444 }
445
446 throw error;
447 });
448 },
449
450 _getKeyFromId: function (/**string|Array*/ id) {
451 // summary:
452 // Generates a DynamoDB attribute map from a DynamoDB scalar identity value.
453 // id:
454 // An opaque record identifier created by `DynamoDB#getIdentity`, or an array of primary key
455 // values.
456 // returns: Object
457
458 var key = {};
459
460 if (this.idProperty instanceof Array) {
461 if (typeof id === 'string') {
462 id = arrayUtil.map(id.split('/'), function (value) {
463 var type = value.charAt(0);
464 value = value.slice(1);
465
466 if (type === 'N') {
467 value = +value;
468 }
469
470 return value;
471 });
472 }
473
474 arrayUtil.forEach(id, function (value, index) {
475 key[this.idProperty[index]] = getDynamoValue(value);
476 }, this);
477 }
478 else {
479 key[this.idProperty] = getDynamoValue(id);
480 }
481
482 return key;
483 },
484
485 get: function (/**string|number|Array*/ id) {
486 // summary:
487 // Retrieves a single record from the table.
488 // id:
489 // The identifier for the record. If using a hash table, a scalar value corresponding to the hash key
490 // of the table. If using a hash+range table, an array of values corresponding to the keys specified
491 // in the `DynamoDB#idProperty` array, or a serialized ID in the format of `type + value + "/" +
492 // type + value` (e.g. `N1234/Sfoo`).
493 // returns: dojo/promise/Promise -> Object
494 // The object from the server, or `null` if it does not exist.
495
496 var data = {
497 Key: this._getKeyFromId(id),
498 ConsistentRead: this.consistentRead
499 };
500
501 if (this.attributesToGet) {
502 data.AttributesToGet = this.attributesToGet;
503 }
504
505 return this._rpc('GetItem', data).then(function (object) {
506 return fromDynamoObject(object.Item);
507 });
508 },
509
510 getIdentity: function (/**Object*/ object) {
511 // summary:
512 // Generates and returns an opaque scalar identifier for a given object.
513 // object:
514 // A data object from this store.
515 // returns: string
516
517 var id;
518 if (this.idProperty instanceof Array) {
519 id = arrayUtil.map(this.idProperty, function (property) {
520 return getDynamoType(object[property]) + object[property];
521 }).join('/');
522 }
523 else {
524 id = object[this.idProperty];
525 }
526
527 return id;
528 },
529
530 query: function (/**Object*/ query, /**Object?*/ options) {
531 // summary:
532 // Retrieves multiple records from the table. Additional restrictions exist for DynamoDB that
533 // do not exist with a standard SQL database.
534 // query:
535 // A hash map of values to query for. If the value is an array, DynamoDB will search for any of the
536 // specified values for that array. The result sets are combined using an AND operator, so all
537 // specified attributes must match for a record to be returned.
538 //
539 // For a query on a table, you can only have conditions on the table primary key attributes. You can
540 // optionally specify a second condition, referring to the range key attribute.
541 //
542 // For a query on a secondary index, you can only have conditions on the index key attributes. You
543 // can optionally specify a second condition, referring to the index key range attribute.
544 // options:
545 // A set of options. The following options are supported by DynamoDB, with limitations described
546 // below:
547 // * `start` (number|Object): The record to start querying from. Because DynamoDB does not support
548 // starting a set of query results from an arbitrary numeric index, if a number is provided, all
549 // results up to `start + count` will be retrieved on each request.
550 // * `count` (number): The number of records to retrieve. If `start` is a number, this will be
551 // combined with `start` and used as the Limit for the request.
552 // * `indexName` (string): The name of the secondary index to query against. If this property
553 // is not explicitly specified but a `sort` option is specified, the name of the sort attribute
554 // will be used as the name of the index to use.
555 // * `sort` (Array): An array containing a single `{ attribute, descending }` object. Only a single
556 // sort dimension is supported, and the attribute must match the range key of the index being
557 // queried.
558 // * `fetchTotal` (boolean): Whether or not to retrieve the total number of available records. This
559 // requires multiple requests to DynamoDB. Defaults to `true`.
560 // * `filter`: (Object): An object defining a DynamoDB filter expression. This object must contain
561 // the following properties:
562 // * `FilterExpression`: (string) A filter expression string. This property is required.
563 // * `ExpressionAttributeValues`: (Object) An optional mapping of value placeholder strings to
564 // actual values. Note that value placeholders must start with ':'.
565 // * `ExpressionAttributeNames`: (Object) An optional mapping of name placeholder strings to full
566 // name strings. This is typically used when a filter expression uses a property name that is a
567 // DynamoDB reserved word, such as 'name'. Note that name placeholders must start with '#'.
568 // Below is an example filter that will cause the result set to contain only items whose `name`
569 // property contains tthe word "The".
570 // | filter: {
571 // | FilterExpression: 'contains(#n, :word)',
572 // | ExpressionAttributeNames: { '#n': 'name' },
573 // | ExpressionAttributeValues: { ':word': 'The' }
574 // | }
575 // For more information about DynamoDB query syntax, see:
576 // http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/QueryAndScan.html.
577 // returns: dojo/store/util/QueryResults
578 // A list of objects matching the query.
579
580 // jshint maxcomplexity:17
581
582 function copyFilterMap(map) {
583 var values = {};
584 for (var key in map) {
585 values[key] = getDynamoValue(map[key]);
586 }
587 return values;
588 }
589
590 options = options || {};
591
592 var data = {
593 KeyConditions: {},
594 ConsistentRead: this.consistentRead
595 };
596
597 if (this.attributesToGet) {
598 data.AttributesToGet = this.attributesToGet;
599 }
600
601 if (options.indexName) {
602 data.IndexName = options.indexName;
603 }
604
605 if (options.sort && options.sort.length) {
606 if (options.sort.length > 1) {
607 throw new Error('Cannot sort by more than one dimension');
608 }
609
610 if (!data.IndexName) {
611 data.IndexName = options.sort[0].attribute;
612 }
613
614 data.ScanIndexForward = !options.sort[0].descending;
615 }
616
617 for (var k in query) {
618 var value = query[k];
619
620 data.KeyConditions[k] = {
621 AttributeValueList: value instanceof Array ? arrayUtil.map(value, getDynamoValue) :
622 [ getDynamoValue(value) ],
623 ComparisonOperator: 'EQ'
624 };
625 }
626
627 if (options.filter) {
628 var filter = options.filter;
629 data.FilterExpression = filter.FilterExpression;
630
631 if (filter.ExpressionAttributeValues) {
632 data.ExpressionAttributeValues = copyFilterMap(filter.ExpressionAttributeValues);
633 }
634
635 if (filter.ExpressionAttributeNames) {
636 data.ExpressionAttributeNames = filter.ExpressionAttributeNames;
637 }
638 }
639
640 var dfd = new Deferred(function () {
641 request && request.cancel.apply(request, arguments);
642 });
643 var response = createQueryResults(dfd.promise);
644
645 if (options.fetchTotal !== false) {
646 response.total = this._rpc('Query', lang.mixin({}, data, {
647 Select: 'COUNT'
648 })).then(function (response) {
649 return response.Count;
650 });
651 }
652
653 var self = this;
654 var result = [];
655 var skipRecords = typeof options.start === 'number' ? options.start : 0;
656 var recordsToRetrieve = (skipRecords + (options.count || 0)) || Infinity;
657 var request;
658
659 (function nextQuery(nextStartKey) {
660 data.Limit = recordsToRetrieve < Infinity ? recordsToRetrieve : undefined;
661 data.ExclusiveStartKey = nextStartKey;
662
663 request = self._rpc('Query', data).then(function (response) {
664 if (response.Items.length) {
665 var newData = arrayUtil.map(response.Items.slice(skipRecords), fromDynamoObject);
666
667 if (skipRecords > 0) {
668 skipRecords = Math.max(skipRecords - newData.length, 0);
669 }
670
671 recordsToRetrieve -= newData.length;
672 result = result.concat(newData);
673 }
674
675 // DynamoDB has a 1MB limit per request; if we have not retrieved all the requested records when the
676 // limit is reached, the response will contain a LastEvaluatedKey value that can be used to continue
677 // the query in a subsequent operation.
678 if (recordsToRetrieve > 0 && response.LastEvaluatedKey) {
679 nextQuery(response.LastEvaluatedKey);
680 }
681 else {
682 dfd.resolve(result);
683 }
684 }, lang.hitch(dfd, 'reject'));
685 })(typeof options.start === 'object' ? toDynamoObject(options.start) : undefined);
686
687 return response;
688 },
689
690 remove: function (/**string|number|Array*/ id, /**Object*/ options) {
691 // summary:
692 // Removes a record from the table.
693 // id:
694 // See `DynamoDB#get` for information on the structure of the identifier. Note that you must use the
695 // serialized ID format if using a hash+range table and wrapping DynamoDB with Observable.
696 // options:
697 // Additional options for the remove operation:
698 // * `expected` (Object): The object expected to exist on the server for the given identifier. If the
699 // expected object does not match the object on the server, the remove operation will fail.
700 // returns: dojo/promise/Promise -> Object
701 // The old object that was removed from the server, or `null` if there was no old object.
702
703 options = options || {};
704
705 var data = {
706 Key: this._getKeyFromId(id),
707 ReturnValues: 'ALL_OLD'
708 };
709
710 if (options.expected) {
711 data.Expected = {};
712 for (var k in options.expected) {
713 data.Expected[k] = {
714 Value: getDynamoValue(options.expected[k])
715 };
716 }
717 }
718
719 return this._rpc('DeleteItem', data).then(function (object) {
720 return fromDynamoObject(object.Attributes);
721 });
722 },
723
724 put: function (/**Object*/ object, /**Object?*/ options) {
725 // summary:
726 // Puts an object into the table.
727 // object:
728 // The object to put into the table.
729 // options:
730 // Additional options for the put operation:
731 // * `overwrite` (boolean): If set to `false`, and an object with the same identifier as the one
732 // being put into the table already exists, the put will fail.
733 // * `id` (string|number|Array): An identifier that will be assigned to the object before it is put
734 // to the store, overriding any identifier that already exists on the object. Note that you must
735 // use the serialized ID format if using a hash+range table and wrapping DynamoDB with Observable.
736 // * `expected` (Object): The object expected to exist on the server for the given identifier. If the
737 // expected object does not match the object on the server, the remove operation will fail.
738 // returns: dojo/promise/Promise
739
740 options = options || {};
741
742 var data = {
743 Item: toDynamoObject(object)
744 };
745
746 if (options.id) {
747 lang.mixin(data.Item, this._getKeyFromId(options.id));
748 }
749
750 if (options.overwrite === false) {
751 data.Expected = {};
752 var idProperties = this.idProperty instanceof Array ? this.idProperty : [ this.idProperty ];
753 arrayUtil.forEach(idProperties, function (property) {
754 data.Expected[property] = { Exists: false };
755 });
756 }
757 else if (options.expected) {
758 data.Expected = {};
759 for (var k in options.expected) {
760 data.Expected[k] = {
761 Value: getDynamoValue(options.expected[k])
762 };
763 }
764 }
765
766 return this._rpc('PutItem', data).then(function () {
767 // Ensure that no data is returned from the rpc promise chain since a returned object would override the
768 // object passed to `put` by Observable
769 });
770 },
771
772 add: function (/**Object*/ object, /**Object?*/ options) {
773 // summary:
774 // Puts an object to the table only if it does not already exist. See `DynamoDB#put` for more
775 // information.
776 // returns: dojo/promise/Promise
777 // See `DynamoDB#put` for more information.
778
779 options = options || {};
780 options.overwrite = false;
781 return this.put(object, options);
782 }
783 });
784 });