Load api versions dynamically

This commit is contained in:
ricardo 2022-04-14 14:39:12 -04:00
parent 44ec5c6cfe
commit 215fe9aad3
6 changed files with 58 additions and 104 deletions

View file

@ -88,7 +88,7 @@ export async function getUsersToSaveAndInvite(
export async function saveUsersWithRole(
users: string[],
role: Role,
role: Role | undefined,
tokenOwnerId: string,
): Promise<User[]> {
const savedUsers = await Db.transaction(async (transactionManager) => {
@ -96,7 +96,7 @@ export async function saveUsersWithRole(
users.map(async (email) => {
const newUser = Object.assign(new User(), {
email,
globalRole: role.id,
globalRole: role?.id,
});
const savedUser = await transactionManager.save<User>(newUser);
return savedUser;

View file

@ -1,5 +1,55 @@
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable no-restricted-syntax */
/* eslint-disable @typescript-eslint/naming-convention */
/* eslint-disable @typescript-eslint/no-unsafe-call */
/* eslint-disable import/no-cycle */
import { publicApiControllerV1 } from './v1';
import { publicApiControllerV2 } from './v2';
import express, { Router } from 'express';
import * as OpenApiValidator from 'express-openapi-validator';
import { HttpError } from 'express-openapi-validator/dist/framework/types';
import fs from 'fs/promises';
import path from 'path';
import { authenticationHandler, specFormats } from './helpers';
export const publicApi = [publicApiControllerV1, publicApiControllerV2];
function createApiRouter(
version: string,
openApiSpecPath: string,
hanldersDirectory: string,
): Router {
const apiController = express.Router();
apiController.use(`/${version}/spec`, express.static(openApiSpecPath));
apiController.use(`/${version}`, express.json());
apiController.use(
`/${version}`,
OpenApiValidator.middleware({
apiSpec: openApiSpecPath,
operationHandlers: hanldersDirectory,
validateRequests: true,
validateApiSpec: true,
formats: specFormats(),
validateSecurity: {
handlers: {
ApiKeyAuth: authenticationHandler,
},
},
}),
);
apiController.use(
(error: HttpError, req: express.Request, res: express.Response, next: express.NextFunction) => {
return res.status(error.status || 400).json({
message: error.message,
});
},
);
return apiController;
}
export const loadPublicApiVersions = async (): Promise<express.Router[]> => {
const data = await fs.readdir(__dirname);
const versions = data.filter((folderName) => folderName.startsWith('v'));
const apiRouters: express.Router[] = [];
for (const version of versions) {
const openApiPath = path.join(__dirname, version, 'openapi.yml');
apiRouters.push(createApiRouter(version, openApiPath, __dirname));
}
return apiRouters;
};

View file

@ -40,7 +40,7 @@ export = {
let savedUsers;
try {
savedUsers = await saveUsersWithRole(usersToSave, role!, tokenOwnerId);
savedUsers = await saveUsersWithRole(usersToSave, role, tokenOwnerId);
} catch (error) {
return res.status(500).json({
message: 'An error occurred during user creation',

View file

@ -1,48 +0,0 @@
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/naming-convention */
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
/* eslint-disable global-require */
/* eslint-disable import/no-dynamic-require */
/* eslint-disable import/no-cycle */
import * as OpenApiValidator from 'express-openapi-validator';
import path = require('path');
import express = require('express');
import { HttpError } from 'express-openapi-validator/dist/framework/types';
import { authenticationHandler, specFormats } from '../helpers';
export const publicApiControllerV1 = express.Router();
const openApiSpec = path.join(__dirname, 'openapi.yml');
publicApiControllerV1.use('/v1/spec', express.static(openApiSpec));
publicApiControllerV1.use('/v1', express.json());
publicApiControllerV1.use(
'/v1',
OpenApiValidator.middleware({
apiSpec: openApiSpec,
operationHandlers: path.join(__dirname, '..'),
validateRequests: true,
validateApiSpec: true,
formats: specFormats(),
validateSecurity: {
handlers: {
ApiKeyAuth: authenticationHandler,
},
},
}),
);
// error handler
publicApiControllerV1.use(
(error: HttpError, req: express.Request, res: express.Response, next: express.NextFunction) => {
return res.status(error.status || 400).json({
message: error.message,
});
},
);

View file

@ -1,48 +0,0 @@
/* eslint-disable @typescript-eslint/naming-convention */
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
/* eslint-disable global-require */
/* eslint-disable import/no-dynamic-require */
/* eslint-disable import/no-cycle */
import * as OpenApiValidator from 'express-openapi-validator';
import path = require('path');
import express = require('express');
import { HttpError } from 'express-openapi-validator/dist/framework/types';
import { authenticationHandler } from '../helpers';
export const publicApiControllerV2 = express.Router();
const openApiSpec = path.join(__dirname, 'openapi.yml');
publicApiControllerV2.use('/v2/spec', express.static(openApiSpec));
publicApiControllerV2.use('/v2', express.json());
publicApiControllerV2.use(
'/v2',
OpenApiValidator.middleware({
apiSpec: openApiSpec,
operationHandlers: path.join(__dirname, '..'),
validateRequests: true,
validateApiSpec: true,
validateSecurity: {
handlers: {
ApiKeyAuth: authenticationHandler,
},
},
}),
);
// error handler
publicApiControllerV2.use(
// eslint-disable-next-line @typescript-eslint/no-unused-vars
(error: HttpError, req: express.Request, res: express.Response, next: express.NextFunction) => {
return res.status(error.status || 400).json({
message: error.message,
// errors: error.errors,
});
},
);

View file

@ -169,7 +169,7 @@ import { SharedWorkflow } from './databases/entities/SharedWorkflow';
import { AUTH_COOKIE_NAME, RESPONSE_ERROR_MESSAGES } from './constants';
import { credentialsController } from './api/credentials.api';
import { getInstanceBaseUrl, isEmailSetUp } from './UserManagement/UserManagementHelper';
import { publicApi } from './PublicApi';
import { loadPublicApiVersions } from './PublicApi';
require('body-parser-xml')(bodyParser);
@ -580,7 +580,7 @@ class App {
return ResponseHelper.sendSuccessResponse(res, {}, true, 204);
});
this.app.use(`/${this.publicApiEndpoint}`, ...publicApi);
this.app.use(`/${this.publicApiEndpoint}`, ...(await loadPublicApiVersions()));
// Parse cookies for easier access
this.app.use(cookieParser());