File size: 1,359 Bytes
057576a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
42
43
44
45
46
47
48
49
const allowedFileTypes = {
  image: ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'],
  audio: ['audio/mpeg', 'audio/wav', 'audio/ogg', 'audio/mp4', 'audio/x-m4a'],
  document: ['application/pdf', 'text/plain', 'text/markdown']
};

const maxFileSizes = {
  image: 10 * 1024 * 1024, // 10MB
  audio: 25 * 1024 * 1024, // 25MB
  document: 50 * 1024 * 1024 // 50MB
};

const validateFile = (file) => {
  const { mimetype, size } = file;

  // Check file type
  let fileCategory = null;
  for (const [category, types] of Object.entries(allowedFileTypes)) {
    if (types.includes(mimetype)) {
      fileCategory = category;
      break;
    }
  }

  if (!fileCategory) {
    throw new Error(`File type ${mimetype} is not supported`);
  }

  // Check file size
  if (size > maxFileSizes[fileCategory]) {
    throw new Error(`File too large. Maximum size for ${fileCategory} is ${maxFileSizes[fileCategory] / 1024 / 1024}MB`);
  }

  return fileCategory;
};

const getFileType = (mimetype) => {
  if (mimetype.startsWith('image/')) return 'image';
  if (mimetype.startsWith('audio/')) return 'audio';
  if (mimetype.startsWith('text/') || mimetype === 'application/pdf') return 'document';
  return 'file';
};

module.exports = {
  validateFile,
  getFileType,
  allowedFileTypes,
  maxFileSizes
};