All files / src/services resources_service.ts

88.88% Statements 24/27
78.57% Branches 11/14
100% Functions 7/7
88.88% Lines 24/27

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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68            7x     3x 3x 1x     3x   2x     2x 2x 2x         3x           3x 3x 3x   3x 2x   1x         3x         7x 3x   3x 3x 2x 2x             1x          
import { config } from '../config/config';
import multer from 'multer';
import path from 'path';
import { randomUUID } from 'crypto';
import fs from 'fs';
 
const createImagesStorage = () => {
 
    // Ensure the directory exists
    const imagesResourcesDir = config.resources.imagesDirectoryPath();
    if (!fs.existsSync(imagesResourcesDir)) {
        fs.mkdirSync(imagesResourcesDir, { recursive: true });
    }
 
    const imagesStorage = multer.diskStorage({
        destination: (req, file, cb) => {
            cb(null, `${imagesResourcesDir}/`);
        },
        filename: (req, file, cb) => {
            const ext = path.extname(file.originalname);
            const id = randomUUID();
            cb(null, id + ext);
        }
    });
 
    // TODO - consider to make a Promise
    const uploadImage = multer({
        storage: imagesStorage,
        limits: {
            fileSize: config.resources.imageMaxSize()
        },
        fileFilter: (req, file, cb) => {
            const allowedTypes = /jpeg|jpg|png|gif/;
            const extname = allowedTypes.test(path.extname(file.originalname).toLowerCase());
            const mimetype = allowedTypes.test(file.mimetype);
 
            if (extname && mimetype) {
                return cb(null, true);
            } else {
                return cb(new TypeError(`Invalid file type. Only images are allowed: ${allowedTypes}`));
            }
        }
    });
 
    return uploadImage;
};
 
// TODO - fix the type here
// @ts-ignore
const uploadImage = (req) : Promise<string> => {
    return new Promise<string>((resolve, reject) => {
        // @ts-ignore
        createImagesStorage().single('file')(req, {}, (error) => {
            if (error) {
                if (error instanceof multer.MulterError || error instanceof TypeError) {
                    return reject(error);
                } else Eif (!req.file) {
                    return reject(new TypeError('No file uploaded.'));
                } else {
                    return reject(new Error('Internal Server Error'));
                }
            }
            resolve(req.file.filename);
        });
    });
};
 
export { uploadImage };