2020-02-14 21:06:16 +01:00
|
|
|
import * as express from 'express';
|
2020-02-14 23:22:20 +01:00
|
|
|
import { checkSchema, validationResult } from "express-validator";
|
2020-02-14 21:06:16 +01:00
|
|
|
import {ExportJob, ExportJobsList} from "../interfaces"
|
|
|
|
|
import {PROCESSING_TIME_EXPORT} from "../config";
|
2020-02-14 23:22:20 +01:00
|
|
|
import {exportJobSchema} from "./schema";
|
2020-02-14 21:06:16 +01:00
|
|
|
|
|
|
|
|
class ExportController {
|
|
|
|
|
public path = '/export';
|
|
|
|
|
public router = express.Router();
|
|
|
|
|
|
|
|
|
|
private exportJobs: ExportJob[] = [];
|
|
|
|
|
|
|
|
|
|
constructor() {
|
|
|
|
|
this.initializeRoutes();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public initializeRoutes() {
|
|
|
|
|
this.router.get(this.path, this.getAllExportJobs);
|
2020-02-14 23:22:20 +01:00
|
|
|
this.router.post(this.path, checkSchema(exportJobSchema), this.addExportJob);
|
2020-02-14 21:06:16 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
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) => {
|
2020-02-14 23:22:20 +01:00
|
|
|
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);
|
2020-02-14 21:06:16 +01:00
|
|
|
|
2020-02-14 23:22:20 +01:00
|
|
|
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);
|
2020-02-18 11:07:30 +01:00
|
|
|
response.send(fullExportJob);
|
2020-02-14 23:22:20 +01:00
|
|
|
}
|
2020-02-14 21:06:16 +01:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export default ExportController;
|