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,9 @@
import * as express from 'express';
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';
@@ -10,12 +13,12 @@ class ImportController {
constructor() {
this.initializeRoutes();
}
};
public initializeRoutes() {
this.router.get(this.path, this.getAllImportJobs);
this.router.post(this.path, this.addImportJob);
}
this.router.post(this.path, checkSchema(importJobSchema), this.addImportJob);
};
getAllImportJobs = (request: express.Request, response: express.Response) => {
const result: ImportJobsList = {
@@ -35,26 +38,32 @@ class ImportController {
};
addImportJob = (request: express.Request, response: express.Response) => {
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);
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);
response.send();
}
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();
}
};
}
export default ImportController;