"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const v4_1 = __importDefault(require("uuid/v4"));
const typeorm_1 = require("typeorm");
const entities_1 = require("../../../entities");
const fs = __importStar(require("fs"));
const promises_all_1 = __importDefault(require("promises-all"));
const mkdirp = __importStar(require("mkdirp"));
const { resolve } = require('path');
const storeFS = ({ stream, filename }) => {
    const uploadDir = process.env.UPLOAD_DIR;
    mkdirp.sync(process.env.UPLOAD_DIR);
    const id = v4_1.default();
    const ext = filename.split('.').pop();
    const path = ext ? resolve(uploadDir, `${id}.${ext}`) : resolve(uploadDir, id);
    return new Promise((resolve, reject) => stream
        .on('error', error => {
        if (stream.truncated)
            // Delete the truncated file
            fs.unlinkSync(path);
        reject(error);
    })
        .pipe(fs.createWriteStream(path))
        .on('error', error => reject(error))
        .on('finish', () => resolve({ id, path })));
};
const storeDB = async (file) => {
    const repository = typeorm_1.getRepository(entities_1.File);
    return await repository.save(file);
};
const processUpload = async (upload) => {
    const { stream, filename, mimetype, encoding } = await upload;
    var { id, path } = await storeFS({ stream, filename });
    path = path
        .split('\\')
        .pop()
        .split('/')
        .pop();
    return await storeDB({ id, filename, mimetype, encoding, path });
};
async function singleUpload(_, { file }) {
    return await processUpload(file);
}
exports.singleUpload = singleUpload;
async function multipleUpload(_, { files }) {
    const { resolve, reject } = await promises_all_1.default.all(files.map(processUpload));
    if (reject.length)
        reject.forEach(({ name, message }) => 
        // eslint-disable-next-line no-console
        console.error(`${name}: ${message}`));
    return resolve;
}
exports.multipleUpload = multipleUpload;
//# sourceMappingURL=upload.js.map