@incdevco/framework
Version:
node.js lambda framework
199 lines (105 loc) • 3.46 kB
JavaScript
var Util = require('util');
var Base = require('../index');
function Lambda(config) {
'use strict';
Base.call(this, config);
this.handlers = config.handlers || {};
}
Util.inherits(Lambda, Base);
Lambda.prototype.attributeToData = function (attribute) {
'use strict';
if (attribute.BOOL) {
return attribute.BOOL;
} else if (attribute.L) {
var array = new Array(attribute.L.length), self = this;
attribute.L.forEach(function (item, index) {
array[index] = self.attributeToData(item);
});
return array;
} else if (attribute.M) {
return this.itemToObject(attribute.M);
} else if (attribute.N) {
return parseFloat(attribute.N);
} else if (attribute.NULL) {
return null;
} else if (attribute.S) {
return attribute.S;
} else {
return undefined;
}
};
Lambda.prototype.getTableNameFromEventSourceArn = function (eventSourceARN) {
'use strict';
return eventSourceARN.split('/')[1];
};
Lambda.prototype.handler = function (event, context) {
'use strict';
var count, promise, self = this;
count = 0;
promise = this.Promise.resolve(true);
this.log('original-event', JSON.stringify(event, null, 2));
event.Records.forEach(function (record, index) {
count++;
promise = promise.then(function () {
return self.handleRecord(event, record)
.catch(function (exception) {
exception.recordIndex = index;
throw exception;
});
});
});
promise
.then(function () {
return self.afterAllRecords(event);
})
.then(function () {
context.succeed(count);
})
.catch(function (exception) {
context.fail(exception);
});
};
Lambda.prototype.handleRecord = function (event, record) {
'use strict';
var keys, newImage, oldImage, promise, self = this;
promise = this.Promise.resolve(true);
record.table = this.getTableNameFromEventSourceArn(record.eventSourceARN);
this.log('table', record.table);
if (this.handlers[record.table]
&& this.handlers[record.table][record.eventName]) {
this.log('handler found');
keys = this.itemToObject(record.dynamodb.Keys);
if (record.dynamodb.NewImage) {
newImage = this.itemToObject(record.dynamodb.NewImage);
}
if (record.dynamodb.OldImage) {
oldImage = this.itemToObject(record.dynamodb.OldImage);
}
promise = this.Promise.try(function () {
return self.handlers[record.table][record.eventName](event, record, keys, newImage, oldImage);
});
}
return promise;
};
Lambda.prototype.itemToObject = function (item) {
'use strict';
var obj = {}, self = this;
Object.keys(item).forEach(function (key) {
obj[key] = self.attributeToData(item[key]);
});
return obj;
};
Lambda.prototype.afterAllRecords = function (event) {
return true;
};
Lambda.prototype.register = function (table, event, handler) {
'use strict';
if (typeof event === 'string') {
this.handlers[table] = this.handlers[table] || {};
this.handlers[table][event] = handler;
} else {
this.handlers[table] = event;
}
return this;
};
module.exports = Lambda;