svtslv / nestjs-s3

S3 module for Nest
79 stars 6 forks source link

How to registerasync in other modules ? #12

Open wisekaa03 opened 2 years ago

wisekaa03 commented 2 years ago
    S3Module.forRootAsync({
      useFactory: async (configService: ConfigService) => ({
        config: {
          endPoint: configService.get('AWS_HOST'),
          accessKey: configService.get('AWS_ACCESS_KEY'),
          secretKey: configService.get('AWS_SECRET_KEY'),
          region: configService.get('AWS_REGION'),
        },
      }),
      inject: [ConfigService],
    }),

    MulterModule.registerAsync({
      imports: [S3Module],
      useFactory: async (configService: ConfigService, s3: AWS_S3) => {
        return {
          storage: multerS3({
            s3,
            ...mediaBucketConfig,
          }),
        };
      },
      inject: [
        ConfigService,
        {
          provide: getS3ConnectionToken(S3_MODULE_CONNECTION),
          useExisting: AWS_S3,
        },
      ],
    }),

Error: resove dependencies :)

Dryymoon commented 11 months ago

Something like that:

Main difference:

inject: [getS3ConnectionToken('')]

Full working example:

// your-cool.module.ts

import { S3Module, S3, getS3ConnectionToken } from 'nestjs-s3';
import { MulterModule } from '@nestjs/platform-express';
import { customAlphabet } from 'nanoid';
import { nolookalikes } from 'nanoid-dictionary';
import multerS3 from 'multer-s3';
import mime from 'mime-types';
const nanoId = customAlphabet(nolookalikes, 37);
const S3_BUCKET_NAME = 'your-s3-bucket';

// ...

@Module({
  imports: [
    MulterModule.registerAsync({
      imports: [S3Module],
      inject: [getS3ConnectionToken('')],
      useFactory: (s3Client: S3) => ({
        storage: multerS3({
          s3: s3Client,
          bucket: S3_BUCKET_NAME,
          acl: 'public-read',
          metadata: function (req, file, cb) {
            /*
          file: {
            fieldname: 'file',
            originalname: '123.jpg',
            encoding: '7bit',
            mimetype: 'image/jpeg'
          },
          */
            cb(null, {
              fileName: file.originalname,
              uploadedAt: new Date().toJSON(),
            });
          },
          key: function (req, file, cb) {
            const ext = mime.extension(file.mimetype);
            const fileName = `uploaded-tmp-files/${nanoId()}.${ext}`;
            cb(null, fileName);
          },
          contentType: function (req, file, cb) {
            cb(null, file.mimetype);
          },
          cacheControl: `max-age=${60 * 60}`, // 1 Hour
        }),
      }),
    }),
  ],
  controllers: [/* ... */],
  providers: [/* ... */],
})
export class YourCoolModule {}