import * as express from 'express'; import {ExportJob, ExportJobsList} from "../interfaces" import {PROCESSING_TIME_EXPORT} from "../config"; class ExportController { public path = '/export'; public router = express.Router(); private exportJobs: ExportJob[] = []; constructor() { this.initializeRoutes(); } public initializeRoutes() { this.router.get(this.path, this.getAllExportJobs); this.router.post(this.path, this.addExportJob); } getAllExportJobs = (request: express.Request, response: express.Response) => { const result: ExportJobsList = { pending: [], finished: [] }; this.exportJobs.forEach((exportJob:ExportJob) => { if (exportJob.state === "pending"){ result.pending.push(exportJob); }else if (exportJob.state === "finished"){ result.finished.push(exportJob); } }); response.send(result); }; addExportJob = (request: express.Request, response: express.Response) => { const receivedExportJob = request.body; const fullExportJob:ExportJob = { bookId: receivedExportJob.bookId, type: receivedExportJob.type, state: "pending", created_at: new Date(), updated_at: new Date() }; this.exportJobs.push(fullExportJob); const jobIndexToUpdate:number = this.exportJobs.length-1; const timeout:number = PROCESSING_TIME_EXPORT[fullExportJob.type]*1000; setTimeout((jobIndex:number) => { this.exportJobs[jobIndex].state = "finished"; this.exportJobs[jobIndex].updated_at = new Date(); }, timeout, jobIndexToUpdate); response.send(); } } export default ExportController;