add validation schema and use it to validate requests

This commit is contained in:
Bilal Catic
2020-02-14 23:22:20 +01:00
parent a0c3672d2a
commit 483483a1c4
3 changed files with 116 additions and 40 deletions

View File

@@ -1,6 +1,8 @@
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';
@@ -14,7 +16,7 @@ class ExportController {
public initializeRoutes() {
this.router.get(this.path, this.getAllExportJobs);
this.router.post(this.path, this.addExportJob);
this.router.post(this.path, checkSchema(exportJobSchema), this.addExportJob);
}
getAllExportJobs = (request: express.Request, response: express.Response) => {
@@ -35,24 +37,28 @@ class ExportController {
};
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 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();
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();
}
}
}