MinIO - is a cloud-native object store built to run on any infrastructure - public, private or edge clouds. Primary use cases include data lakes, databases, AI/ML, SaaS applications and fast backup & recovery. MinIO is dual licensed under GNU AGPL v3 and commercial license. To learn more, visit www.min.io.
Download package nestjs-minio-s3.
Set docker environment variables:
MINIO_ROOT_USER="minioadmin"
MINIO_ROOT_PASSWORD="minioadmin"
- Add Minio container in Docker Compose:
services:
db:
container_name: db
image: postgres:latest
ports:
- '5432:5432'
env_file:
- .docker.env
volumes:
- postgres:/data/postgres
minio:
image: minio/minio:latest
container_name: minio
ports:
- '9000:9000'
- '9001:9001'
env_file:
- .docker.env
command: server /data --console-address ":9001"
volumes:
- minio:/data
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:9000/minio/health/live"]
interval: 30s
timeout: 20s
retries: 3
volumes:
postgres:
driver: local
minio:
driver: local
- Add global environment variables:
MINIO_ENDPOINT="http://localhost:9000"
MINIO_USER="minioadmin"
MINIO_PASSWORD="minioadmin"
MINIO_REGION="us-east-1"
- Include
MinioModulein AppModule:
MinioModule.forRootAsync({
imports: [EnvModule],
inject: [EnvService],
useFactory: (envService: EnvService) => ({
endpoint: envService.get('MINIO_ENDPOINT')!,
accessKey: envService.get('MINIO_USER')!,
secretKey: envService.get('MINIO_PASSWORD')!,
region: envService.get('MINIO_REGION') || 'us-east-1',
buckets: [{ name: 'avatars', policy: 'public' }],
}),
}),
- Add
MinioServiceto constructor:
constructor(
private readonly minioService: MinioService,
) {}
- Use
MinioServicein your methods:
async uploadAvatar(userId: number, file: Express.Multer.File) {
return await this.dataSource.transaction(async (manager) => {
const user = await manager.findOne(UserEntity, {
where: { id: userId },
select: ['id', 'avatarUrl'],
});
if (!user) {
throw new NotFoundException('User not found');
}
const oldAvatarUrl = user.avatarUrl as string;
const key = `${userId}-${Date.now()}.${file.originalname.split('.').pop()}`;
const newAvatarUrl = await this.minioService.upload(
this.AVATARS_BUCKET,
key,
file.buffer,
file.mimetype,
);
await manager.update(UserEntity, userId, { avatarUrl: newAvatarUrl });
if (oldAvatarUrl) {
try {
const oldKey = this.minioService.getKeyFromUrl(
oldAvatarUrl,
this.AVATARS_BUCKET,
);
if (oldKey) {
await this.minioService.delete(this.AVATARS_BUCKET, oldKey);
}
} catch (e: unknown) {
console.error('Error deleting old avatar ', e);
}
}
return newAvatarUrl;
});
}
- After completing the request, view the changes at the address http://localhost:9001 with authorization data: username:
minioadmin, password:minioadmin