All files / varjoliitokauppa/lib minio.ts

90% Statements 9/10
100% Branches 14/14
100% Functions 2/2
90% Lines 9/10

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41    2x               2x       2x 2x 2x 1x   1x                     1x               2x    
import { Client } from 'minio'
 
export const minioClient = new Client({
  endPoint: process.env.MINIO_ENDPOINT || 'localhost',
  port: parseInt(process.env.MINIO_PORT || '9000'),
  useSSL: process.env.MINIO_USE_SSL === 'true',
  accessKey: process.env.MINIO_ACCESS_KEY || 'minioadmin',
  secretKey: process.env.MINIO_SECRET_KEY || 'minioadmin',
})
 
export const bucketName = process.env.MINIO_BUCKET_NAME || 'varjoliitokauppa-images'
 
// Initialize bucket if it doesn't exist
export async function initBucket() {
  try {
    const exists = await minioClient.bucketExists(bucketName)
    if (!exists) {
      await minioClient.makeBucket(bucketName, 'us-east-1')
      // Set bucket policy to public read
      const policy = {
        Version: '2012-10-17',
        Statement: [
          {
            Effect: 'Allow',
            Principal: { AWS: ['*'] },
            Action: ['s3:GetObject'],
            Resource: [`arn:aws:s3:::${bucketName}/*`],
          },
        ],
      }
      await minioClient.setBucketPolicy(bucketName, JSON.stringify(policy))
    }
  } catch (error) {
    console.error('Error initializing MinIO bucket:', error)
  }
}
 
export function getPublicUrl(fileName: string): string {
  return `${process.env.MINIO_PUBLIC_URL || 'http://localhost:9000'}/${bucketName}/${fileName}`
}