UNPKG

dynamodb-ts-model

Version:

A DynamoDB model/client with full TypeScript typings

100 lines 3.63 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.DynamoWrapper = void 0; function getCommandType(command) { switch (command) { case 'BatchGetItemCommandInput': case 'GetItemCommandInput': case 'QueryCommandInput': case 'ScanCommandInput': return 'read'; case 'BatchWriteItemCommandInput': case 'DeleteItemCommandInput': case 'PutItemCommandInput': case 'UpdateItemCommandInput': return 'write'; } } function truncate(data) { if (data == null) { return data; } else if (Array.isArray(data)) { const result = data.slice(0, 2).map(truncate); const rest = data.length - result.length; if (rest > 0) { result.push(` ... ${rest} more items`); } return result; } else if (typeof data === 'object') { const result = {}; for (const [k, v] of Object.entries(data)) { result[k] = truncate(v); } return result; } else { return data; } } class DynamoWrapper { constructor(client, name) { this.client = client; this.name = name; } get logger() { return this.client.options.logger; } async command(cmd, executor = (client, cmd) => client.send(cmd)) { var _a, _b, _c; const command = cmd.constructor.name; const { input } = cmd; try { (_a = this.logger) === null || _a === void 0 ? void 0 : _a.debug({ input: truncate(input) }, `DynamoDB ${command} input`); const output = await executor(this.client.dc, cmd); if ('ConsumedCapacity' in output) { this.logConsumedCapacity(command, output.ConsumedCapacity); } (_b = this.logger) === null || _b === void 0 ? void 0 : _b.debug({ output: truncate(output) }, `DynamoDB ${command} output`); return output; } catch (err) { (_c = this.logger) === null || _c === void 0 ? void 0 : _c.debug({ err }, `DynamoDB ${command} error: ${err.message}`); throw err; } } logConsumedCapacity(command, consumedCapacity = []) { var _a, _b, _c; const type = getCommandType(command); const items = Array.isArray(consumedCapacity) ? consumedCapacity : [consumedCapacity]; const tableMetrics = this.client.getTableMetrics(); for (const item of items) { const { TableName: tableName, CapacityUnits: cu, ReadCapacityUnits: rcu = type === 'read' ? cu : undefined, WriteCapacityUnits: wcu = type === 'write' ? cu : undefined } = item; if (tableName) { const metrics = tableMetrics.get(tableName); if (metrics) { if (rcu) { metrics.rcu = ((_a = metrics.rcu) !== null && _a !== void 0 ? _a : 0) + rcu; } if (wcu) { metrics.wcu = ((_b = metrics.wcu) !== null && _b !== void 0 ? _b : 0) + wcu; } if (cu) { metrics.cu = ((_c = metrics.cu) !== null && _c !== void 0 ? _c : 0) + cu; } } else { tableMetrics.set(tableName, { tableName, rcu, wcu, cu }); } } } } } exports.DynamoWrapper = DynamoWrapper; //# sourceMappingURL=DynamoWrapper.js.map