Skip to content

A NestJS module for interacting with AWS S3. This module simplifies the integration of AWS S3 within a NestJS application by providing injectable services and configuration options.

License

Notifications You must be signed in to change notification settings

OpenNebel/NestJS-S3Client

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

46 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

COVER IMAGE OF PACKAGE

NPM Version NPM Downloads License

Buy Me A Coffee

@open-nebel/nest-s3

đź“– Docs: https://nestjs-s3.netlify.app

A NestJS module for interacting with AWS S3. This module simplifies the integration of AWS S3 within a NestJS application by providing injectable services and configuration options.

Note: This library is compatible with AWS SDK V3.

⚠️ AWS SDK Version 2.x Upcoming End-of-Support

We announced the upcoming end-of-support for AWS SDK for JavaScript v2. We recommend that you migrate to AWS SDK for JavaScript v3. For dates, additional details, and information on how to migrate, please refer to the linked announcement.

The AWS SDK for JavaScript v3 is the latest and recommended version, which has been GA since December 2020. Here is why and how you should use AWS SDK for JavaScript v3. You can try our experimental migration scripts in aws-sdk-js-codemod to migrate your application from v2 to v3.

Table of Contents

Installation

To install the package, use the following commands:

npm install @open-nebel/nest-s3 @aws-sdk/client-s3 @aws-sdk/s3-request-presigner

or

yarn add @open-nebel/nest-s3 @aws-sdk/client-s3 @aws-sdk/s3-request-presigner

Usage

Configuration

You can configure the S3 module using either synchronous or asynchronous configuration.

Synchronous Configuration

import { Module } from '@nestjs/common';
import { S3Module } from '@open-nebel/nest-s3';

@Module({
  imports: [
    S3Module.forRoot({
      region: 'your-region',
      accessKeyId: 'your-access-key-id',
      secretAccessKey: 'your-secret-access-key',
    }),
  ],
})
export class AppModule {}

Asynchronous Configuration

import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { S3Module } from '@open-nebel/nest-s3';

@Module({
  imports: [
    ConfigModule.forRoot(),
    S3Module.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: (configService: ConfigService) => ({
        region: configService.get<string>('AWS_REGION'),
        accessKeyId: configService.get<string>('AWS_ACCESS_KEY_ID'),
        secretAccessKey: configService.get<string>('AWS_SECRET_ACCESS_KEY'),
      }),
    }),
  ],
})
export class AppModule {}

Using the S3Service

The S3Service provides methods to interact with AWS S3, such as creating buckets, uploading objects, and generating presigned URLs. Additionally, it exposes an instance of S3Client configured with the module settings, allowing direct interaction with S3.

Example Usage in a Service

import { Injectable } from '@nestjs/common';
import { S3Service } from '@open-nebel/nest-s3';
import { S3Client, ListBucketsCommand } from '@aws-sdk/client-s3';

@Injectable()
export class MyService {
  constructor(private readonly s3Service: S3Service) {}

  async useS3ClientOriginal(): Promise<void> {
    const s3Client: S3Client = this.s3Service.getClient();

    const buckets = await s3Client.send(new ListBucketsCommand({}));

    console.log('Buckets:', buckets.Buckets);
  }

  async useS3Methods() {
    const bucketName = 'your-bucket-name';
    const key = 'your-file-key';
    const body = 'your-file-content';

    // Create a bucket
    await this.s3Service.createBucket(bucketName);

    // Upload an object
    await this.s3Service.uploadObject(bucketName, key, body);

    // Get an object
    const objectContent = await this.s3Service.getObject(bucketName, key);
    console.log('Object Content:', objectContent);

    // Generate a presigned URL
    const presignedUrl = await this.s3Service.createPresignedUrlWithClient({ bucket: bucketName, key });
    console.log('Presigned URL:', presignedUrl);

    // Delete an object
    await this.s3Service.deleteOneObject(bucketName, key);

    // Delete all objects in the bucket
    await this.s3Service.deleteAllObjects(bucketName);

    // Delete the bucket
    await this.s3Service.deleteBucket(bucketName);
    
    // Copy an object
    await this.s3Service.copyObject('source-bucket', 'source-key', 'destination-bucket', 'destination-key');

    // List all buckets
    const { owner, buckets } = await this.s3Service.listBuckets();
    console.log('Owner:', owner);
    console.log('Buckets:', buckets);
  }
}

Available Methods

Given below are the available methods provided by the S3Client and S3Service classes.

getClient(): S3Client

Returns the configured S3Client instance for direct interaction with AWS S3.

const s3Client: S3Client = this.s3Service.getClient();

createBucket(bucketName: string): Promise<void>

Creates a new S3 bucket with the specified name.

await this.s3Service.createBucket('my-new-bucket');

uploadObject(bucketName: string, key: string, body: string | Uint8Array | Buffer | ReadableStream<any> | Blob): Promise<void>

Uploads an object to the specified S3 bucket.

await this.s3Service.uploadObject('my-new-bucket', 'my-object-key', 'Hello, world!');

getObject(bucketName: string, key: string): Promise<string | undefined>

Retrieves an object from the specified S3 bucket.

const content = await this.s3Service.getObject('my-new-bucket', 'my-object-key');
console.log('Object content:', content);

deleteOneObject(bucketName: string, key: string): Promise<void>

Deletes an object from the specified S3 bucket.

await this.s3Service.deleteOneObject('my-new-bucket', 'my-object-key');

deleteAllObjects(bucketName: string): Promise<void>

Deletes all objects from the specified S3 bucket.

await this.s3Service.deleteAllObjects('my-new-bucket');

deleteBucket(bucketName: string): Promise<void>

Deletes the specified S3 bucket.

await this.s3Service.deleteBucket('my-new-bucket');

createPresignedUrlWithClient(params: { bucket: string; key: string }): Promise<string>

Generates a presigned URL for accessing an object in the specified S3 bucket.

const presignedUrl = await this.s3Service.createPresignedUrlWithClient({ bucket: 'my-new-bucket', key: 'my-object-key' });
console.log('Presigned URL:', presignedUrl);

copyObject(sourceBucket: string, sourceKey: string, destinationBucket: string, destinationKey: string): Promise<void>

Copies an object from one bucket to another in AWS S3.

await this.s3Service.copyObject('source-bucket', 'source-key', 'destination-bucket', 'destination-key');

listBuckets(): Promise<{ owner: { name: string }; buckets: { name: string }[] }>

Lists all buckets in AWS S3.

const { owner, buckets } = await this.s3Service.listBuckets();
console.log('Owner:', owner);
console.log('Buckets:', buckets);

License

This project is licensed under the MIT License. See the LICENSE file for details.

Contributing

Contributions are welcome! Please feel free to submit a pull request or open an issue on GitHub.

Acknowledgements

This package uses the AWS SDK for JavaScript (v3) and is inspired by the design principles of NestJS.

Support

If you encounter any issues or have any questions, feel free to open an issue on GitHub or contact the maintainers.


By following this README, users should be able to easily install, configure, and use your NestJS AWS S3 library in their projects, with the added ability to directly interact with the AWS S3 client.

About

A NestJS module for interacting with AWS S3. This module simplifies the integration of AWS S3 within a NestJS application by providing injectable services and configuration options.

Topics

Resources

License

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published