dynamit-cli
Version:
The DynamoDB migrations tool CLI
83 lines (82 loc) • 3.44 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const dynamodb_1 = require("aws-sdk/clients/dynamodb");
const ramda_1 = require("ramda");
/**
* @class DynamoDBStorage
*/
class DynamoDBStorage {
/**
* Constructs DynamoDB table storage.
*
* @param options
* @param options.dynamodb - a DynamoDB document client instance
* @param options.tableName - name of migration table in DynamoDB
* @param options.attributeName - name of the table primaryKey attribute in DynamoDB
* @param options.timestamp - option to add timestamps to the DynamoDB table
*/
constructor({ dynamodb, tableName, attributeName, timestamp } = {}) {
if (dynamodb && !(dynamodb instanceof dynamodb_1.DocumentClient)) {
throw new Error('"dynamodb" must be a DocumentClient instance');
}
this.dynamodb = dynamodb || new dynamodb_1.DocumentClient();
this.tableName = tableName || 'migrations';
this.attributeName = attributeName || 'name';
this.timestamp = timestamp || false;
}
/**
* Logs migration to be considered as executed.
*
* @param migrationName - Name of the migration to be logged.
*/
logMigration(migrationName) {
return __awaiter(this, void 0, void 0, function* () {
const item = { [this.attributeName]: migrationName };
if (this.timestamp) {
item.createdAt = Date.now();
}
yield this.dynamodb.put({ TableName: this.tableName, Item: item }).promise();
});
}
/**
* Unlogs migration to be considered as pending.
*
* @param migrationName - Name of the migration to be unlogged.
*/
unlogMigration(migrationName) {
return __awaiter(this, void 0, void 0, function* () {
const key = { [this.attributeName]: migrationName };
yield this.dynamodb.delete({ TableName: this.tableName, Key: key }).promise();
});
}
/**
* Gets list of executed migrations.
*/
executed() {
return __awaiter(this, void 0, void 0, function* () {
const executedItems = [];
let startKey;
do {
const { Items, LastEvaluatedKey } = yield this.dynamodb.scan({
TableName: this.tableName,
ExclusiveStartKey: startKey,
}).promise();
for (const item of Items) {
executedItems.push(item[this.attributeName]);
}
startKey = LastEvaluatedKey;
} while (startKey);
return ramda_1.sort((a, b) => a.localeCompare(b), executedItems);
});
}
}
exports.default = DynamoDBStorage;