Skip to content

Instantly share code, notes, and snippets.

@krishnasaga
Last active April 1, 2023 19:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krishnasaga/47d2473b044f61ebc5dc777f22ebfa8e to your computer and use it in GitHub Desktop.
Save krishnasaga/47d2473b044f61ebc5dc777f22ebfa8e to your computer and use it in GitHub Desktop.
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
import { OpenAPI } from 'openapi-types';
import axios from 'axios';
import { createValidatorMiddleware } from 'openapi-enforcer-middleware';
@Injectable()
export class OpenApiValidationMiddleware implements NestMiddleware {
private specifications: OpenAPI.Document[] = [];
constructor() {
// Define the HTTP locations of the OpenAPI specifications
const specLocations = [
'http://example.com/api1/openapi.json',
'http://example.com/api2/openapi.json',
'http://example.com/api3/openapi.json',
];
// Fetch and combine the specification files
Promise.all(specLocations.map((location) => axios.get(location)))
.then((responses) => {
this.specifications = responses.map((response) => response.data);
})
.catch((error) => {
console.error('Failed to fetch the OpenAPI specifications:', error);
});
}
async use(req: Request, res: Response, next: NextFunction) {
// Wait until the specifications are loaded
while (this.specifications.length === 0) {
await new Promise((resolve) => setTimeout(resolve, 100));
}
// Combine the specifications into one document
const document: OpenAPI.Document = {
openapi: '3.0.0',
info: {
title: 'Combined OpenAPI Specification',
version: '1.0.0',
},
paths: {},
};
this.specifications.forEach((spec) => {
if (spec.paths) {
Object.assign(document.paths, spec.paths);
}
});
// Create the validator middleware using the combined document
const validatorMiddleware = createValidatorMiddleware(document);
// Use the validator middleware
validatorMiddleware(req, res, next);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment