-
Notifications
You must be signed in to change notification settings - Fork 8
/
atomic-counter.js
225 lines (199 loc) · 9.45 KB
/
atomic-counter.js
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
/**
* dynamodb-atomic-counter - (c) 2015 Sergio Alcantara
* Generates unique identifiers using DynamoDB atomic counter update operations.
*
* @author Sergio Alcantara
*/
/**
* Default name of the DynamoDB table where the atomic counters will be stored.
*/
var DEFAULT_TABLE_NAME = 'AtomicCounters',
/**
* Default attribute name that will identify each counter.
*/
DEFAULT_KEY_ATTRIBUTE = 'id',
/**
* Default attribute name of the count value attribute.
* The count attribute indicates the "last value" used in the last increment operation.
*/
DEFAULT_COUNT_ATTRIBUTE = 'lastValue',
/**
* Default increment value.
*/
DEFAULT_INCREMENT = 1;
var dynamo,
AWS = require( 'aws-sdk' ),
_ = require( 'underscore' );
_.mixin( require('underscore.deferred') );
/**
* A convinience "no operation" function.
*/
var noop = function(){};
/**
* Make the `AWS.DynamoDB.config` method available.
*/
exports.config = AWS.config;
/**
* Increments the counter for the specified `counterId`.
* It returns an AWS-SDK request instance with a jQuery style promise interface applied to it.
* See [jQuery documentation](http://api.jquery.com/category/deferred-object/) to find out how to attach callbacks
* to the returned object using the methods: done, fail, always, and then.
*
* @method increment
* @param {String} counterId The name or identifier of the counter to increment.
* @param {Object} options An options object to overwrite some of the default behaviour of the increment operation.
* @param {String} options.tableName The name of the DynamoDB table that stores the counters. If not specified, it uses "AtomicCounters" by default.
* @param {String} options.keyAttribute The name of the attribute that stores the counter name/identifier. If not specified, it uses "id" by default.
* @param {String} options.countAttribute The name of the attribute that stores the last value generated for the specified `counterId`.
* If not specified, it uses "lastValue" by default.
* @param {Integer} options.increment Specifies by how much the counter should be incremented. If not specified, it uses 1 by default.
* @param {Function} options.success Success callback function. It receives a single argument: the value (integer) generated by this
* increment operation for the specified `counterId`.
* @param {Function} options.error Error callback function. If the DynamoDB UpdateItem request fails, the error callback is executed.
* It receives a single argument: the error object returned from AWS-SDK.
* @param {Function} options.complete Complete callback function. This callback is executed when the increment operation is completed,
* whether or not it was successful. It receives a single argument: a number, if the operation was successful, or an error object if it failed.
* @param options.context The context object to use in all callbacks. If specified, the value of `this`
* within all callbacks will be `options.context`.
* @param {Object} options.dynamodb Additional DynamoDB parameters. These parameters will be added to the parameters sent in the
* [update item](http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#updateItem-property) request.
* @return {Request} A DynamoDB UpdateItem [request](http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Request.html) object,
* with a [jQuery](http://api.jquery.com/category/deferred-object/) style promise interface applied to it.
*/
exports.increment = function ( counterId, options ) {
options || ( options = {} );
var request,
deferred = new _.Deferred(),
params = {
Key: {},
AttributeUpdates: {},
ReturnValues: 'UPDATED_NEW',
TableName: options.tableName || DEFAULT_TABLE_NAME
},
keyAttribute = options.keyAttribute || DEFAULT_KEY_ATTRIBUTE,
countAttribute = options.countAttribute || DEFAULT_COUNT_ATTRIBUTE,
errorFn = _.isFunction( options.error ) ? options.error : noop,
successFn = _.isFunction( options.success ) ? options.success : noop,
completeFn = _.isFunction( options.complete ) ? options.complete : noop;
params.Key[ keyAttribute ] = { S: counterId };
params.AttributeUpdates[ countAttribute ] = {
Action: 'ADD',
Value: {
N: '' + ( options.increment || DEFAULT_INCREMENT )
}
};
_.extend( params, options.dynamodb );
dynamo || ( dynamo = new AWS.DynamoDB() );
request = dynamo.updateItem(params, function (error, data) {
var newCountValue;
try {
if ( error ) {
throw error;
}
// Try to parse the count value. An exception will be thrown if it's not a valid number.
newCountValue = parseInt( data.Attributes[ countAttribute ].N, 10 );
if ( !_.isNumber( newCountValue ) || _.isNaN( newCountValue ) ) {
throw 'Could not parse incremented value (' + newCountValue + ').';
}
} catch ( e ) {
if ( options.context ) {
deferred.rejectWith( options.context, [ e ] );
} else {
deferred.reject( e );
}
return;
}
if ( options.context ) {
deferred.resolveWith( options.context, [ newCountValue ] );
} else {
deferred.resolve( newCountValue );
}
});
/**
* Apply a promise interface to `request`, set the success, error, and complete callback, and return the promise.
*/
return deferred.promise( request ).done( successFn ).fail( errorFn ).always( completeFn );
};
/**
* Gets the last value previously generated for the specified `counterId`.
* It returns an AWS-SDK request instance with a jQuery style promise interface applied to it.
* See [jQuery documentation](http://api.jquery.com/category/deferred-object/) to find out how to attach callbacks
* to the returned object using the methods: done, fail, always, and then.
*
* @method getLastValue
* @param {String} counterId The name or identifier of the counter.
* @param {Object} options An options object to overwrite some of the default options.
* @param {String} options.tableName The name of the DynamoDB table that stores the counters. If not specified, it uses "AtomicCounters" by default.
* @param {String} options.keyAttribute The name of the attribute that stores the counter name/identifier. If not specified, it uses "id" by default.
* @param {String} options.countAttribute The name of the attribute that stores the last value generated for the specified `counterId`.
* If not specified, it uses "lastValue" by default.
* @param {Function} options.success Success callback function. It receives a single argument: the last value (integer) previously generated
* for the specified `counterId`.
* @param {Function} options.error Error callback function. If the DynamoDB GetItem request fails, the error callback is executed.
* It receives a single argument: the error object returned from AWS-SDK or the exception thrown when attempting to parse the response.
* @param {Function} options.complete Complete callback function. This callback is executed when the GetItem request is completed,
* whether or not it was successful. It receives a single argument: a number, if it was successful, or an error object if it failed.
* @param options.context The context object to use in all callbacks. If specified, the value of `this`
* within all callbacks will be `options.context`.
* @param {Object} options.dynamodb Additional DynamoDB parameters. These parameters will be added to the parameters sent in the
* [get item](http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#getItem-property) request.
* @return {Request} A DynamoDB GetItem [request](http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Request.html) object,
* with a [jQuery](http://api.jquery.com/category/deferred-object/) style promise interface applied to it.
*/
exports.getLastValue = function ( counterId, options ) {
options || ( options = {} );
var request,
deferred = new _.Deferred(),
keyAttribute = options.keyAttribute || DEFAULT_KEY_ATTRIBUTE,
countAttribute = options.countAttribute || DEFAULT_COUNT_ATTRIBUTE,
params = {
Key: {},
AttributesToGet: [ countAttribute ],
TableName: options.tableName || DEFAULT_TABLE_NAME
},
errorFn = _.isFunction( options.error ) ? options.error : noop,
successFn = _.isFunction( options.success ) ? options.success : noop,
completeFn = _.isFunction( options.complete ) ? options.complete : noop;
params.Key[ keyAttribute ] = { S: counterId };
_.extend( params, options.dynamodb );
dynamo || ( dynamo = new AWS.DynamoDB() );
request = dynamo.getItem(params, function (errorObject, data) {
var error, lastValue;
if ( errorObject ) {
error = errorObject;
} else if ( _.isEmpty( data ) ) {
/**
* If the item doesn't exist, the response would be empty.
* Set `lastValue` to 0 when the item doesn't exist.
*/
lastValue = 0;
} else {
try {
// Try to parse the count value. An exception will be thrown if it's not a valid number.
lastValue = parseInt( data.Item[ countAttribute ].N, 10 );
if ( !_.isNumber( lastValue ) || _.isNaN( lastValue ) ) {
throw 'Could not parse incremented value (' + lastValue + ').';
}
} catch ( e ) {
error = e;
}
}
if ( error ) {
if ( options.context ) {
deferred.rejectWith( options.context, [ e ] );
} else {
deferred.reject( e );
}
} else {
if ( options.context ) {
deferred.resolveWith( options.context, [ lastValue ] );
} else {
deferred.resolve( lastValue );
}
}
});
/**
* Apply a promise interface to `request`, set the success, error, and complete callback, and return the promise.
*/
return deferred.promise( request ).done( successFn ).fail( errorFn ).always( completeFn );
};