# All files / modules/storage/providers s3.provider.ts

100% Statements 59/59
94.73% Branches 18/19
100% Functions 10/10
100% Lines 57/57

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    1643x
    3x
    3x

    3x

    3x
    41x

    41x

    41x

    36x
    36x
    36x
    36x
    36x
    36x

    36x
    7x
    7x

    29x
    29x

    29x

    29x
    2x
    2x

    29x
    29x
    29x

    7x

    2x

    4x

    5x
    1x

    4x

    4x

    4x
    4x

    4x

    4x
    1x

    3x

    3x
    3x

    3x

    3x
    1x

    2x

    2x

    6x
    1x

    5x
    5x

    5x
    3x

    2x
    1x

    1x

    5x
    5x

     import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
    import { ConfigService } from '@nestjs/config';
    import {
      S3Client,
      PutObjectCommand,
      GetObjectCommand,
      DeleteObjectCommand,
      HeadObjectCommand,
    } from '@aws-sdk/client-s3';
    import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
    import { StorageProvider } from '../entities/file.entity';

    export interface PresignedUrlOptions {
      bucket: string;
      key: string;
      contentType: string;
      contentLength: number;
      expiresIn?: number;
      metadata?: Record<string, string>;
    }

    export interface PresignedUrlResult {
      url: string;
      expiresAt: Date;
    }

    @Injectable()
    export class S3Provider implements OnModuleInit {
      private readonly logger = new Logger(S3Provider.name);
      private client: S3Client;
      private bucket: string;
      private provider: StorageProvider;
      private configured = false;

      constructor(private configService: ConfigService) {}

      onModuleInit() {
        const storageProvider = this.configService.get<string>('STORAGE_PROVIDER', 's3');
        const bucket = this.configService.get<string>('STORAGE_BUCKET');
        const region = this.configService.get<string>('AWS_REGION', 'us-east-1');
        const accessKeyId = this.configService.get<string>('AWS_ACCESS_KEY_ID');
        const secretAccessKey = this.configService.get<string>('AWS_SECRET_ACCESS_KEY');
        const endpoint = this.configService.get<string>('STORAGE_ENDPOINT');

        if (!bucket || !accessKeyId || !secretAccessKey) {
          this.logger.warn('Storage not configured - missing STORAGE_BUCKET or AWS credentials');
          return;
        }

        this.bucket = bucket;
        this.provider = storageProvider as StorageProvider;

        const config: any = {
          region,
          credentials: {
            accessKeyId,
            secretAccessKey,
          },
        };

        // For MinIO or R2, use custom endpoint
        if (endpoint) {
          config.endpoint = endpoint;
          config.forcePathStyle = true; // Required for MinIO
        }

        this.client = new S3Client(config);
        this.configured = true;
        this.logger.log(`Storage configured: ${storageProvider} - ${bucket}`);
      }

      isConfigured(): boolean {
        return this.configured;
      }

      getBucket(): string {
        return this.bucket;
      }

      getProvider(): StorageProvider {
        return this.provider;
      }

      async getUploadUrl(options: PresignedUrlOptions): Promise<PresignedUrlResult> {
        if (!this.configured) {
          throw new Error('Storage not configured');
        }

        const expiresIn = options.expiresIn || 900; // 15 minutes default

        const command = new PutObjectCommand({
          Bucket: options.bucket || this.bucket,
          Key: options.key,
          ContentType: options.contentType,
          ContentLength: options.contentLength,
          Metadata: options.metadata,
        });

        const url = await getSignedUrl(this.client, command, { expiresIn });
        const expiresAt = new Date(Date.now() + expiresIn * 1000);

        return { url, expiresAt };
      }

      async getDownloadUrl(key: string, expiresIn = 3600): Promise<PresignedUrlResult> {
        if (!this.configured) {
          throw new Error('Storage not configured');
        }

        const command = new GetObjectCommand({
          Bucket: this.bucket,
          Key: key,
        });

        const url = await getSignedUrl(this.client, command, { expiresIn });
        const expiresAt = new Date(Date.now() + expiresIn * 1000);

        return { url, expiresAt };
      }

      async deleteObject(key: string): Promise<void> {
        if (!this.configured) {
          throw new Error('Storage not configured');
        }

        const command = new DeleteObjectCommand({
          Bucket: this.bucket,
          Key: key,
        });

        await this.client.send(command);
      }

      async headObject(key: string): Promise<{ contentLength: number; contentType: string } | null> {
        if (!this.configured) {
          throw new Error('Storage not configured');
        }

        try {
          const command = new HeadObjectCommand({
            Bucket: this.bucket,
            Key: key,
          });

          const response = await this.client.send(command);
          return {
            contentLength: response.ContentLength || 0,
            contentType: response.ContentType || 'application/octet-stream',
          };
        } catch (error: any) {
          if (error.name === 'NotFound') {
            return null;
          }
          throw error;
        }
      }

      generatePath(tenantId: string, folder: string, uploadId: string, filename: string): string {
        // Sanitize filename
        const sanitized = filename.replace(/[^a-zA-Z0-9.-]/g, '_');
        return `${tenantId}/${folder}/${uploadId}/${sanitized}`;
      }
    }