Skip to content

Commit

Permalink
remove unnecessary middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
magicmatatjahu committed Dec 9, 2021
1 parent 91db24e commit baaa950
Show file tree
Hide file tree
Showing 3 changed files with 87 additions and 94 deletions.
3 changes: 2 additions & 1 deletion src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,13 @@ export class App {
this.port = process.env.PORT || 3000;
this.env = process.env.NODE_ENV || 'development';

// initialize core middlewares
this.initializeMiddlewares();
// initialize validation middlewares
this.initializeValidation();
// initialize all controllers
this.initializeControllers(controller);
// initialize error handlings
// initialize error handling
this.initializeErrorHandling();
}

Expand Down
91 changes: 85 additions & 6 deletions src/controllers/generate.controller.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { Request, Response, Router } from 'express';
import fs from 'fs';
import path from 'path';
import { NextFunction, Request, Response, Router } from 'express';
import Ajv from 'ajv';

import { Controller } from '../interfaces';

import { documentValidationMiddleware } from '../middlewares/document-validation.middleware';
import { generatorTemplateParametersValidationMiddleware } from "../middlewares/generator-template-parameters-validation.middleware";

import { ArchiverService } from '../services/archiver.service';
import { GeneratorService } from '../services/generator.service';
Expand All @@ -19,8 +21,15 @@ export class GenerateController implements Controller {

private archiverService = new ArchiverService();
private generatorService = new GeneratorService();
private ajv: Ajv;

private async generate(req: Request, res: Response) {
private async generate(req: Request, res: Response, next: NextFunction) {
try {
this.validateTemplateParameters(req);
} catch(err) {
return next(err);
}

const zip = this.archiverService.createZip(res);

let tmpDir: string;
Expand All @@ -43,25 +52,95 @@ export class GenerateController implements Controller {
return await this.archiverService.finalize(zip);
}
catch (err: unknown) {
throw new ProblemException({
return next(new ProblemException({
type: 'internal-server-error',
title: 'Internal server error',
status: 500,
detail: (err as Error).message,
});
}));
}
finally {
this.archiverService.removeTempDirectory(tmpDir);
}
}

private validateTemplateParameters(req: Request) {
const { template, parameters } = req.body;

const validate = this.getAjvValidator(template);
const valid = validate(parameters || {});
const errors = validate.errors && [...validate.errors];

if (valid === false) {
throw new ProblemException({
type: 'invalid-template-parameters',
title: 'Invalid Generator Template parameters',
status: 422,
validationErrors: errors as any,
});
}
}

/**
* Retrieve proper AJV's validator function, create or reuse it.
*/
public getAjvValidator(templateName: string) {
let validate = this.ajv.getSchema(templateName);
if (!validate) {
this.ajv.addSchema(this.serializeTemplateParameters(templateName), templateName);
validate = this.ajv.getSchema(templateName);
}
return validate;
}

/**
* Serialize template parameters. Read all parameters from template's package.json and create a proper JSON Schema for validating parameters.
*/
public serializeTemplateParameters(templateName: string): object {
const packageJSON = JSON.parse(fs.readFileSync(path.join(__dirname, `../../node_modules/${templateName}/package.json`), 'utf-8'));
if (!packageJSON) {
return;
}

const generator = packageJSON.generator;
if (!generator || !generator.parameters) {
return;
}

const parameters = generator.parameters || {};
const required: string[] = [];
for (let parameter in parameters) {
// at the moment all parameters have to be passed to the Generator instance as string
parameters[parameter].type = 'string';
if (parameters[parameter].required) {
required.push(parameter);
}
delete parameters[parameter].required;
}

return {
'$schema': 'http://json-schema.org/draft-07/schema#',
type: 'object',
properties: parameters,
required,
// don't allow non supported properties
additionalProperties: false,
}
}


public boot(): Router {
this.ajv = new Ajv({
inlineRefs: true,
allErrors: true,
schemaId: 'id',
logger: false,
});
const router = Router();

router.post(
`${this.basepath}`,
documentValidationMiddleware,
generatorTemplateParametersValidationMiddleware,
this.generate.bind(this)
);

Expand Down

This file was deleted.

0 comments on commit baaa950

Please sign in to comment.