npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@open-nebel/nest-s3

v0.2.1

Published

NestJS module for AWS S3 adapted for AWS SDK v3

Downloads

24

Readme

COVER IMAGE OF PACKAGE

@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.