import * as express from 'express'; import { checkSchema, validationResult } from "express-validator"; import {ExportJob, ExportJobsList} from "../interfaces" import {PROCESSING_TIME_EXPORT} from "../config"; import {exportJobSchema} from "./schema"; 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, checkSchema(exportJobSchema), 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 validationResultArray = validationResult(request).array(); if (validationResultArray.length > 0){ response.status(400).send(validationResultArray); }else { 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(fullExportJob); } } } export default ExportController;