đź“– 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-SupportWe 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.
- Installation
- Usage
- Available Methods
- getClient(): S3Client
- createBucket(bucketName: string): Promise
- uploadObject(bucketName: string, key: string, body: string): Promise
- getObject(bucketName: string, key: string): Promise<string | undefined>
- deleteOneObject(bucketName: string, key: string): Promise
- deleteAllObjects(bucketName: string): Promise
- deleteBucket(bucketName: string): Promise
- createPresignedUrlWithClient(params: { bucket: string; key: string }): Promise
- copyObject(sourceBucket: string, sourceKey: string, destinationBucket: string, destinationKey: string): Promise
- listBuckets(): Promise<{ owner: { name: string }; buckets: { name: string }[] }>
- License
- Contributing
- Acknowledgements
- Support
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
You can configure the S3 module using either synchronous or asynchronous 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 {}
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 {}
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.
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);
}
}
Given below are the available methods provided by the S3Client
and S3Service
classes.
Returns the configured S3Client instance for direct interaction with AWS S3.
const s3Client: S3Client = this.s3Service.getClient();
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!');
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);
Deletes an object from the specified S3 bucket.
await this.s3Service.deleteOneObject('my-new-bucket', 'my-object-key');
Deletes all objects from the specified S3 bucket.
await this.s3Service.deleteAllObjects('my-new-bucket');
Deletes the specified S3 bucket.
await this.s3Service.deleteBucket('my-new-bucket');
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');
Lists all buckets in AWS S3.
const { owner, buckets } = await this.s3Service.listBuckets();
console.log('Owner:', owner);
console.log('Buckets:', buckets);
This project is licensed under the MIT License. See the LICENSE file for details.
Contributions are welcome! Please feel free to submit a pull request or open an issue on GitHub.
This package uses the AWS SDK for JavaScript (v3) and is inspired by the design principles of NestJS.
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.