Files
components/LiteCharms.Features/S3/BookstoreS3Service.cs
T
Khwezi Mngoma 89a343a85f
continuous-integration/drone/pr Build is passing
Updated how i use configs
2026-05-19 14:57:14 +02:00

39 lines
1.6 KiB
C#

using LiteCharms.Features.S3.Abstractions;
namespace LiteCharms.Features.S3;
public class BookstoreS3Service(IConfiguration configuration, [FromKeyedServices(Constants.BookshopBucketName)] IAmazonS3 amazonS3) :
S3ServiceBase(amazonS3), IS3Service
{
private readonly string bucketName = configuration.GetSection($"{Constants.BookshopS3SettingsSection}:BucketName").Value ?? "";
private readonly string cdnBaseUrl = configuration.GetSection($"{Constants.BookshopS3SettingsSection}:CdnBaseUrl").Value ?? "";
public override async Task<Result<string>> UploadFileAsync(string fileName, Stream fileStream, string contentType, CancellationToken cancellationToken = default)
{
try
{
if(string.IsNullOrWhiteSpace(bucketName))
return Result.Fail<string>("Bucket name is not configured.");
if (string.IsNullOrWhiteSpace(cdnBaseUrl))
return Result.Fail<string>("CDN base URL is not configured.");
var response = await client.PutObjectAsync(new PutObjectRequest
{
BucketName = bucketName,
Key = fileName,
InputStream = fileStream,
ContentType = contentType
}, cancellationToken);
return response.HttpStatusCode != System.Net.HttpStatusCode.OK
? Result.Fail<string>($"Failed to upload {fileName} to S3.")
: Result.Ok(string.Format(cdnBaseUrl, bucketName, fileName));
}
catch (Exception ex)
{
return Result.Fail<string>(new Error($"Error uploading {fileName} to S3: {ex.Message}").CausedBy(ex));
}
}
}