@takentrade/takentrade-libs
Version:
TakeNTrade shared libraries
66 lines (65 loc) • 2.94 kB
JavaScript
;
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.StorageService = void 0;
const common_1 = require("@nestjs/common");
const cloudinary_1 = require("cloudinary");
let StorageService = class StorageService {
/**
* Uploads a file to Cloudinary using a stream.
* @param file - The file to upload, provided as a FileUpload object.
* @param options - Optional Cloudinary upload options (e.g., folder, tags).
* @returns A promise resolving to the upload response containing file details.
* @throws Error if the upload fails or no result is returned from Cloudinary.
*/
async uploadFile(file, options) {
try {
const result = await new Promise((resolve, reject) => {
cloudinary_1.v2.uploader
.upload_stream({ resource_type: 'auto', ...options }, (error, result) => {
if (error)
return reject(error);
if (!result)
return reject(new Error('No result from Cloudinary'));
resolve(result);
})
.end(file.buffer);
});
return {
public_id: result.public_id,
url: result.url,
secure_url: result.secure_url,
format: result.format,
resource_type: result.resource_type,
created_at: result.created_at,
};
}
catch (error) {
throw new Error(`Upload failed: ${error instanceof Error ? error.message : String(error)}`);
}
}
/**
* Deletes a file from Cloudinary using its public ID.
* @param publicId - The public ID of the file to delete.
* @returns A promise resolving to the deletion response.
* @throws Error if the deletion fails.
*/
async deleteFile(publicId) {
try {
const result = await cloudinary_1.v2.uploader.destroy(publicId);
return { result: result.result };
}
catch (error) {
throw new Error(`Deletion failed: ${error instanceof Error ? error.message : String(error)}`);
}
}
};
exports.StorageService = StorageService;
exports.StorageService = StorageService = __decorate([
(0, common_1.Injectable)()
], StorageService);