const express = require('express'); const path = require('path'); const Module = require('../../base/Module'); const RepositorySystem = require('../../systems/RepositorySystem'); const RoutingSystem = require('../../systems/RoutingSystem'); const uuidv4 = require('uuid/v4'); const formidable = require('formidable'); const fs = require('fs'); let FileScheme = { fields: [ { key: "filename", type: "text" }, { key: "userId", type: "integer" }, { key: "filetype", type: "text" } ] }; class FileModule extends Module { constructor(){ super('/files', [2,0,3,4,0], 'Files'); this.repository = RepositorySystem.create('Files', FileScheme); this.setRepo(this.repository); this.FileSystemPath = process.cwd(); this.path = this.FileSystemPath + '/localfiles'; this.router = express.Router(); this.init(); } init() { let routes = [ { type: 'custom', method: 'post', endpoint: '/files', customFn: (req,res) => { this.acceptFile(req) .then((data) => { res.send(data); }) .catch((e) => { res.send(e); }); } }, { type:'custom', method: 'get', endpoint:'/files/:id', customFn: (req,res) =>{ this.getFile(req.params) .then((results)=>{ res.download(results[0],results[1]); }) .catch((e)=>{ res.send(e) }) } } ]; RoutingSystem.loadRoutes(routes, this.router); } setRepo(repo) { this._repository = repo; } _getFolder(type){ switch(type){ case 'sql': return 'SQL'; case 'doc' || 'docx': return 'Word'; case 'xlsx' || 'xlsm' || 'xlsb': return 'Excel'; case 'jpg' || 'png': return 'Images'; case 'txt': return 'txt'; case 'pdf': return 'PDF'; } } acceptFile(req, path = this.path){ return new Promise((resolve,reject)=>{ try{ var form = new formidable.IncomingForm({uploadDir:path}); form.parse(req,(err,fields,files)=>{ if(err){ reject(err) } Object.keys(files).map((key,index) =>{ let type = files[key]['name'].split(".")[1] let FileName = form.openedFiles[0].name let newPath = path +'/'+ this._getFolder(type) +'/'+ FileName; fs.rename(files[key]['path'],newPath, (err) => { if (err) reject(err); let data = { "filename":FileName, "userId":null, "filetype":type, } this.repository.insert(data) .then((data)=>{ console.log('h?') resolve(FileName); }) .catch((e)=>{ reject(e) }) }); }); }); } catch(e){ reject(e); } }); } getFile(filename){ return new Promise((resolve,reject)=>{ this.repository.get('filename',filename) .then((data)=>{ let path = this.path + '/' + data[0].filetype.toUpperCase() +'/'+data[0].filename; let results = [ path,data[0].filename]; resolve(results); }) }) .catch((e)=> reject(e)) } } module.exports = FileModule;