Skip to content

Version 0.1.0 #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 10, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Change Log

## [0.0.3] - 2015-05-10
### Added
- New `getLastValue` method that retrieves a previously generated value for an
specified counter.
- Request parameters sent to DynamoDB can be extended using `options.dynamodb`.
35 changes: 32 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,26 +22,43 @@ To configure the internal instance of [AWS.DynamoDB](http://docs.aws.amazon.com/
you can follow one of the many methods described [here](http://docs.aws.amazon.com/AWSJavaScriptSDK/guide/node-configuring.html) or
manually using this `config` instance.

`increment`
-----------
`increment( counterId, options )`
---------------------------------

This method increments the counter for the specified `counterId`.
It returns an AWS-SDK [request](http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Request.html)
instance with a jQuery style promise interface applied to it.
See the [jQuery documentation](http://api.jquery.com/category/deferred-object/) for details on how the promises work.
[underscore.deferred](https://github.com/wookiehangover/underscore.deferred) is used to add the Promise interface to the returned request object.
Additionally, success, error, and complete callback can be provided in the second argument.
The increment method takes the following arguments:
The `increment` method takes the following arguments:

* `counterId`: The unique name/identifier of the counter.
* `options` (optional): An options object to overwrite some of the default behaviour of the increment operation. All attributes in this object are optional.
* `options.tableName`: The name of the DynamoDB table that stores the counters. If not specified, it uses "AtomicCounters" by default.
* `options.keyAttribute`: The name of the attribute that stores the counter name/identifier. If not specified, it uses "id" by default.
* `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.
* `options.increment`: Specifies by how much the counter should be incremented. If not specified, it uses 1 by default.
* `options.success`: Success callback function. It receives a single argument: the value (integer) generated by this increment operation for the specified `counterId`.
* `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.
* `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: an integer, if the operation was successful, or an error object if it failed.
* `options.context`: The context object to use in all callbacks. If specified, the value of `this` within all callbacks will be `options.context`.

`getLastValue( counterId, options )`
------------------------------------

This method retrieves, from DynamoDB, the last generated value for the specified `counterId`. If the counter doesn't exist,
the success callback would receive 0 as the first argument.
It returns an AWS-SDK [request](http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Request.html)
instance with a jQuery style promise interface applied to it.
See the [jQuery documentation](http://api.jquery.com/category/deferred-object/) for details on how the promises work.
[underscore.deferred](https://github.com/wookiehangover/underscore.deferred) is used to add the Promise interface to the returned request object.
Additionally, success, error, and complete callback can be provided in the second argument.
The `getLastValue` method takes the following arguments:

* `counterId`: The unique name/identifier of the counter.
* `options` (optional): The same options supported by the `increment` method are also supported by this method.


Basic Usage
-----------
Expand All @@ -64,4 +81,16 @@ The following few lines of code demonstrate basic usage of this library. Additio
// An error occurred
}).always(function (valueOrError) {
// Executed whether or not the increment operation was successful
});

/**
* Retrieve the last value generated for the "Clients" counter.
*/
atomicCounter.getLastValue( 'Clients' ).done(function (lastValue) {
// `lastValue` is the last value generated for the "Clients" counter.
// If a values has not been generated before, `lastValue` would be 0.
}).fail(function (error) {
// An error occurred
}).always(function (valueOrError) {
// Executed whether or not the request was successful
});
109 changes: 102 additions & 7 deletions atomic-counter.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,18 +48,22 @@ exports.config = dynamo.config;
*
* @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.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`.
* @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 {Function} options.success Success callback function. It receives a single argument: the value (integer) generated by this
* @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.
* @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,
* @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 {Function} options.context The context object to use in all callbacks. If specified, the value of `this`
* @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.
*/
Expand Down Expand Up @@ -87,6 +91,7 @@ exports.increment = function ( counterId, options ) {
N: '' + ( options.increment || DEFAULT_INCREMENT )
}
};
_.extend( params, options.dynamodb );

request = dynamo.updateItem(params, function (error, data) {
var newCountValue;
Expand Down Expand Up @@ -119,6 +124,96 @@ exports.increment = function ( counterId, options ) {
}
});

/**
* 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 );

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.
*/
Expand Down
21 changes: 21 additions & 0 deletions examples.js
Original file line number Diff line number Diff line change
Expand Up @@ -120,4 +120,25 @@ exports[ 'Concurrent increments/requests' ] = function (test) {
test.ok( true ); // always was executed
test.done();
});
};

/**
* This function demonstrates how to use the getLastValue method.
*/
exports[ 'Get last value generated for a counter using ConsistentRead' ] = function (test) {
var options = {
dynamodb: {
ConsistentRead: true
}
};
test.expect( 2 );

atomicCounter.getLastValue( 'Users', options ).done(function (lastValue) {
test.ok( true ); // success was executed
}).fail(function (error) {
test.ok( false, 'Failed to retrieve the last value used: ' + JSON.stringify( error ) );
}).always(function (valueOrError) {
test.ok( true ); // complete was executed
test.done();
});
};
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "dynamodb-atomic-counter",
"author": "Sergio Alcantara <[email protected]> (https://github.com/serg-io)",
"description": "This library provides atomic counters using Amazon DynamoDB.",
"version": "0.0.2",
"version": "0.1.0",
"homepage": "https://github.com/serg-io/dynamodb-atomic-counter",
"keywords": [ "atomic-counter", "atomic", "counter", "dynamodb", "aws", "amazon" ],
"repository": {
Expand All @@ -18,4 +18,4 @@
"devDependencies": {
"nodeunit": "0.9.1"
}
}
}