@rewaa/event-broker
Version:
A broker for all the events that Rewaa will ever produce or consume
86 lines • 3.41 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.DynamoClient = void 0;
const client_dynamodb_1 = require("@aws-sdk/client-dynamodb");
const constants_1 = require("./constants");
class DynamoClient {
constructor(logger, config) {
this.logger = logger;
this.dynamoDB = new client_dynamodb_1.DynamoDB(config);
}
get client() {
return this.dynamoDB;
}
async exists(input) {
const item = await this.getItem(input);
return !!item;
}
async getItem(input) {
const item = await this.client.getItem(input);
return item.Item;
}
async putItem(input, expiry) {
try {
let expiresAt = undefined;
const expiryKey = constants_1.DynamoTablesStructure[input.TableName].expiryKey;
// Default expiry is 5 min
expiresAt = Math.floor((new Date().getTime() + (expiry || 5 * 60) * 1000) / 1000);
await this.client.putItem(Object.assign(Object.assign({}, input), { Item: Object.assign(Object.assign({}, input.Item), (expiryKey && { [expiryKey]: { N: expiresAt.toString() } })) }));
}
catch (error) {
this.logger.error(`Failed to put item: ${JSON.stringify(error)}`);
throw error;
}
}
async createTable(command) {
try {
const output = await this.client.createTable(command);
const expiryKey = constants_1.DynamoTablesStructure[command.TableName].expiryKey;
if (expiryKey) {
await this.waitForTableActive(command.TableName);
await this.client.updateTimeToLive({
TableName: command.TableName,
TimeToLiveSpecification: {
AttributeName: expiryKey,
Enabled: true,
},
});
}
this.logger.info(`Table ${command.TableName} Created`);
return output;
}
catch (error) {
if (error.name === "ResourceInUseException") {
this.logger.warn(`Table ${command.TableName} already exists, ignoring creation`);
return;
}
this.logger.error(`Table ${command.TableName} Creation failed: ${JSON.stringify(error)}`);
throw error;
}
}
async waitForTableActive(tableName) {
var _a;
this.logger.info(`Waiting for table ${tableName} to become ACTIVE`);
let status = "CREATING";
while (status === "CREATING") {
try {
const data = await this.client.describeTable({ TableName: tableName });
status = (_a = data.Table) === null || _a === void 0 ? void 0 : _a.TableStatus;
this.logger.debug(`Current status of table ${tableName}: ${status}`);
}
catch (error) {
if (error.name === "ResourceNotFoundException") {
this.logger.debug(`Table ${tableName} not found, retrying...`);
}
else {
throw error;
}
}
if (status !== "ACTIVE") {
await new Promise((resolve) => setTimeout(resolve, 5000)); // Wait 5 seconds
}
}
}
}
exports.DynamoClient = DynamoClient;
//# sourceMappingURL=dynamo.client.js.map