made s3 uploader and apis

This commit is contained in:
2025-11-12 19:59:54 +05:30
parent c0e58fe1ce
commit 8e19bb566d
12 changed files with 3083 additions and 385 deletions

View File

@@ -0,0 +1,75 @@
import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';
import ApiError from './ApiError';
import * as crypto from 'crypto';
import config from '@/config/config';
const AWS_REGION = config.aws.region;
const S3_BUCKET_NAME = config.aws.bucketName;
const s3Client = new S3Client({
region: AWS_REGION,
});
interface UploadFileParams {
fileData: string; // base64 encoded file
fileName: string;
folder?: string; // Optional folder path in S3
contentType?: string;
}
/**
* Upload file to S3 and return the S3 URL
*/
export async function uploadFileToS3(params: UploadFileParams): Promise<string> {
try {
const { fileData, fileName, folder = 'documents', contentType = 'application/pdf' } = params;
// Generate unique file name
const fileExtension = fileName.split('.').pop() || 'pdf';
const uniqueFileName = `${crypto.randomUUID()}-${Date.now()}.${fileExtension}`;
const s3Key = folder ? `${folder}/${uniqueFileName}` : uniqueFileName;
// Decode base64 file data
const fileBuffer = Buffer.from(fileData, 'base64');
// Upload to S3
const command = new PutObjectCommand({
Bucket: S3_BUCKET_NAME,
Key: s3Key,
Body: fileBuffer,
ContentType: contentType,
// Make file publicly readable (adjust based on your needs)
// ACL: 'public-read', // Uncomment if you want public access
});
await s3Client.send(command);
// Return S3 URL
const s3Url = `https://${S3_BUCKET_NAME}.s3.${AWS_REGION}.amazonaws.com/${s3Key}`;
return s3Url;
} catch (error) {
console.error('S3 upload error:', error);
throw new ApiError(500, 'Failed to upload file to S3');
}
}
/**
* Upload multiple files to S3
*/
export async function uploadFilesToS3(
files: Array<{ fileData: string; fileName: string; contentType?: string }>,
folder?: string
): Promise<string[]> {
const uploadPromises = files.map((file) =>
uploadFileToS3({
fileData: file.fileData,
fileName: file.fileName,
folder,
contentType: file.contentType,
})
);
return Promise.all(uploadPromises);
}

View File

@@ -34,11 +34,12 @@ export const hostCompanyDetailsSchema = z.object({
currencyXid: z.number().min(1, "Currency is required"),
});
// Validation for documents
// Validation for documents with file data (base64)
export const hostDocumentsSchema = z.array(
z.object({
documentTypeXid: z.number(),
documentName: z.string(),
filePath: z.string(),
fileData: z.string().min(1, "File data is required"), // base64 encoded file
contentType: z.string().optional(), // e.g., "application/pdf", "image/png"
})
);