import * as express from "express"; import { checkSchema, validationResult } from "express-validator"; import {ImportJobsList, ImportJob} from "../interfaces" import {PROCESSING_TIME_IMPORT_ANY} from "../config"; import {importJobSchema} from "./schema"; class ImportController { public path = '/import'; public router = express.Router(); private importJobs: ImportJob[] = []; constructor() { this.initializeRoutes(); }; public initializeRoutes() { this.router.get(this.path, this.getAllImportJobs); this.router.post(this.path, checkSchema(importJobSchema), this.addImportJob); }; getAllImportJobs = (request: express.Request, response: express.Response) => { const result: ImportJobsList = { pending: [], finished: [] }; this.importJobs.forEach((importJob:ImportJob) => { if (importJob.state === "pending"){ result.pending.push(importJob); }else if (importJob.state === "finished"){ result.finished.push(importJob); } }); response.send(result); }; addImportJob = (request: express.Request, response: express.Response) => { const validationResultArray = validationResult(request).array(); if (validationResultArray.length > 0){ response.status(400).send(validationResultArray); }else{ const receivedImportJob = request.body; const fullImportJob:ImportJob = { bookId: receivedImportJob.bookId, type: receivedImportJob.type, url: receivedImportJob.url, state: "pending", created_at: new Date(), updated_at: new Date() }; this.importJobs.push(fullImportJob); const jobIndexToUpdate:number = this.importJobs.length-1; const timeout:number = PROCESSING_TIME_IMPORT_ANY*1000; setTimeout((jobIndex:number) => { this.importJobs[jobIndex].state = "finished"; this.importJobs[jobIndex].updated_at = new Date(); }, timeout, jobIndexToUpdate); response.send(fullImportJob); } }; } export default ImportController;