qus-node-aws-clients
Version:
client api for aws tools
239 lines (238 loc) • 11.9 kB
JavaScript
;
var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
var _, done = false;
for (var i = decorators.length - 1; i >= 0; i--) {
var context = {};
for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
for (var p in contextIn.access) context.access[p] = contextIn.access[p];
context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
if (kind === "accessor") {
if (result === void 0) continue;
if (result === null || typeof result !== "object") throw new TypeError("Object expected");
if (_ = accept(result.get)) descriptor.get = _;
if (_ = accept(result.set)) descriptor.set = _;
if (_ = accept(result.init)) initializers.unshift(_);
}
else if (_ = accept(result)) {
if (kind === "field") initializers.unshift(_);
else descriptor[key] = _;
}
}
if (target) Object.defineProperty(target, contextIn.name, descriptor);
done = true;
};
var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
var useValue = arguments.length > 2;
for (var i = 0; i < initializers.length; i++) {
value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
}
return useValue ? value : void 0;
};
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());
});
};
var __setFunctionName = (this && this.__setFunctionName) || function (f, name, prefix) {
if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
};
var __asyncValues = (this && this.__asyncValues) || function (o) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.S3Service = void 0;
/*
* MIT License
*
* Copyright (c) 2024 Quantum Unit Solutions
* Author: David Meikle
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
const client_s3_1 = require("@aws-sdk/client-s3");
const stream_1 = require("stream");
const common_1 = require("@nestjs/common");
let S3Service = (() => {
let _classDecorators = [(0, common_1.Injectable)()];
let _classDescriptor;
let _classExtraInitializers = [];
let _classThis;
var S3Service = _classThis = class {
constructor(s3Client, region) {
this.s3Client = s3Client;
this.region = region;
}
/**
* Uploads a file to S3.
*
* @param bucketName
* @param filePath
* @param data
* @param mimeType
*/
uploadToS3(bucketName, filePath, data, mimeType) {
return __awaiter(this, void 0, void 0, function* () {
const input = {
Bucket: bucketName,
Key: filePath,
Body: data,
ContentType: mimeType,
};
const command = new client_s3_1.PutObjectCommand(input);
try {
return yield this.s3Client.send(command);
}
catch (error) {
throw new Error(`Error uploading to S3: ${error.message}`);
}
});
}
/**
* Retrieves an item from S3.
*
* @param bucketName
* @param filePath
*/
getFromS3(bucketName, filePath) {
return __awaiter(this, void 0, void 0, function* () {
var _a, e_1, _b, _c;
const input = {
Bucket: bucketName,
Key: filePath,
};
const command = new client_s3_1.GetObjectCommand(input);
try {
const response = yield this.s3Client.send(command);
if (response.Body instanceof stream_1.Readable) {
const chunks = [];
try {
for (var _d = true, _e = __asyncValues(response.Body), _f; _f = yield _e.next(), _a = _f.done, !_a; _d = true) {
_c = _f.value;
_d = false;
const chunk = _c;
chunks.push(chunk);
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (!_d && !_a && (_b = _e.return)) yield _b.call(_e);
}
finally { if (e_1) throw e_1.error; }
}
// Concatenate all chunks into a single Buffer
return Buffer.concat(chunks).toString('utf-8');
}
else {
throw new Error('Unexpected response body type');
}
}
catch (error) {
throw new Error(`Error retrieving from S3: ${error.message}`);
}
});
}
getFromS3AsBinary(bucketName, filePath) {
return __awaiter(this, void 0, void 0, function* () {
var _a, e_2, _b, _c;
const input = {
Bucket: bucketName,
Key: filePath,
};
const command = new client_s3_1.GetObjectCommand(input);
try {
const response = yield this.s3Client.send(command);
if (response.Body instanceof stream_1.Readable) {
const chunks = [];
try {
for (var _d = true, _e = __asyncValues(response.Body), _f; _f = yield _e.next(), _a = _f.done, !_a; _d = true) {
_c = _f.value;
_d = false;
const chunk = _c;
chunks.push(chunk);
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (!_d && !_a && (_b = _e.return)) yield _b.call(_e);
}
finally { if (e_2) throw e_2.error; }
}
return Buffer.concat(chunks);
}
else {
throw new Error('Unexpected response body type');
}
}
catch (error) {
throw new Error(`Error retrieving from S3: ${error.message}`);
}
});
}
/**
* Retrieves the most recent file from S3 based on a prefix.
*
* @param bucketName
* @param prefix
*/
getMostRecentFile(bucketName, prefix) {
return __awaiter(this, void 0, void 0, function* () {
const command = new client_s3_1.ListObjectsV2Command({ Bucket: bucketName, Prefix: prefix });
const response = yield this.s3Client.send(command);
if (!response.Contents || response.Contents.length === 0) {
console.log('No files found.');
return undefined;
}
// Extract filenames and sort by date
const files = response.Contents.map((item) => item.Key).filter((key) => key.includes('_'));
const sortedFiles = files.sort((a, b) => {
const dateA = new Date(a.slice(-14, -4)); // Extract last 10 characters before '.pdf'
const dateB = new Date(b.slice(-14, -4));
return dateB.getTime() - dateA.getTime();
});
return sortedFiles[0]; // Most recent file
});
}
};
__setFunctionName(_classThis, "S3Service");
(() => {
const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0;
__esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
S3Service = _classThis = _classDescriptor.value;
if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
__runInitializers(_classThis, _classExtraInitializers);
})();
return S3Service = _classThis;
})();
exports.S3Service = S3Service;