Skip to content
Open
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
1 change: 1 addition & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ function Cardboard(config) {
if (!config.prefix) throw new Error('No s3 prefix set');

var utils = require('./lib/utils')(config);
var ids = require('./lib/ids')(config.dyno);

/**
* A client configured to interact with a backend cardboard database
Expand Down
50 changes: 50 additions & 0 deletions lib/ids.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
module.exports = ids;

var IDS_PER_RESERVATION = 1000;

function ids(dyno) {
var reserved = {};
var numbers = {};

numbers.get = function(dataset, callback) {
if (reserved[dataset]) {
var val = reserved[dataset].get();
if (val) return callback(null, val);
}

numbers.reserve(dataset, function(err, values) {
if (err) return callback(err);
reserved[dataset] = new Range(values);
callback(null, reserved[dataset].get());
});
};

numbers.reserve = function(dataset, callback) {
dyno.updateItem({
Key: {
dataset: dataset,
id: 'autoid'
},
ExpressionAttributeNames: { '#v': 'value' },
ExpressionAttributeValues: { ':v': IDS_PER_RESERVATION },
UpdateExpression: 'add #v :v',
ReturnValues: 'ALL_NEW'
}, function(err, data) {
if (err) return callback(err);
var max = data.Attributes.value;
return callback(null, [max - (IDS_PER_RESERVATION - 1), max]);
});
};

return numbers;
}

function Range(values) {
this.next = values[0];
this.max = values[1];
}

Range.prototype.get = function() {
if (this.next + 1 > this.max) return null;
return ++this.next;
};