♻️ ooconnector: routing refactor (#525)

This commit is contained in:
Eric Doughty-Papassideris
2024-09-15 01:41:48 +02:00
parent 5cf1fa581e
commit 87d0de92d8
7 changed files with 54 additions and 61 deletions
@@ -1,16 +1,13 @@
import path from 'path';
import express from 'express';
import { Routes } from '@interfaces/routes.interface';
import { NODE_ENV } from '@config';
import cors from 'cors';
import { renderFile } from 'eta';
import path from 'path';
import errorMiddleware from './middlewares/error.middleware';
import { SERVER_PORT } from '@config';
import logger from './lib/logger';
import cookieParser from 'cookie-parser';
import apiService from './services/api.service';
import onlyofficeService from './services/onlyoffice.service';
import { makeURLTo, mountRoutes } from './routes';
import { NODE_ENV, SERVER_BIND, SERVER_PORT } from '@config';
import logger from './lib/logger';
import errorMiddleware from './middlewares/error.middleware';
import { mountRoutes } from './routes';
class App {
public app: express.Application;
@@ -28,8 +25,9 @@ class App {
}
public listen = () => {
this.app.listen(parseInt(SERVER_PORT, 10), '0.0.0.0', () => {
logger.info(`🚀 App listening on port ${SERVER_PORT}`);
const binding_host = SERVER_BIND || '0.0.0.0';
this.app.listen(parseInt(SERVER_PORT, 10), binding_host, () => {
logger.info(`🚀 App listening at http://${binding_host}:${SERVER_PORT}`);
});
};
@@ -42,29 +40,6 @@ class App {
});
mountRoutes(this.app);
this.app.get('/health', (_req, res) => {
Promise.all([onlyofficeService.getLatestLicence(), apiService.hasToken(), onlyofficeService.getForgottenList()]).then(
([onlyOfficeLicense, twakeDriveToken, forgottenKeys]) =>
res.status(onlyOfficeLicense && twakeDriveToken ? 200 : 500).send({
uptime: process.uptime(),
onlyOfficeLicense,
twakeDriveToken,
forgottenKeys,
}),
err => res.status(500).send(err),
);
});
this.app.use(
makeURLTo.assets(),
(req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'X-Requested-With');
next();
},
express.static(path.join(__dirname, '../assets')),
);
};
private initMiddlewares = () => {
@@ -5,7 +5,7 @@ import jwt from 'jsonwebtoken';
import driveService from '@/services/drive.service';
import { DriveFileType } from '@/interfaces/drive.interface';
import fileService from '@/services/file.service';
import { OfficeToken } from '@/interfaces/routes.interface';
import { OfficeToken } from '@/interfaces/office-token.interface';
import logger from '@/lib/logger';
import { makeURLTo } from '@/routes';
@@ -0,0 +1,21 @@
import { NextFunction, Request, Response } from 'express';
import onlyofficeService from '@/services/onlyoffice.service';
import apiService from '@/services/api.service';
/**
* Health response for devops operational purposes. Should not be exposed.
*/
export const HealthStatusController = {
async get(req: Request<{}, {}, {}, {}>, res: Response, next: NextFunction): Promise<void> {
Promise.all([onlyofficeService.getLatestLicence(), apiService.hasToken(), onlyofficeService.getForgottenList()]).then(
([onlyOfficeLicense, twakeDriveToken, forgottenKeys]) =>
res.status(onlyOfficeLicense && twakeDriveToken ? 200 : 500).send({
uptimeS: Math.floor(process.uptime()),
onlyOfficeLicense,
twakeDriveToken,
forgottenCount: forgottenKeys?.length ?? 0,
}),
err => res.status(500).send(err),
);
},
};
@@ -1,5 +1,5 @@
import { CREDENTIALS_SECRET } from '@/config';
import { OfficeToken } from '@/interfaces/routes.interface';
import { OfficeToken } from '@/interfaces/office-token.interface';
import driveService from '@/services/drive.service';
import fileService from '@/services/file.service';
import logger from '@/lib/logger';
@@ -21,6 +21,6 @@ export interface IDriveService {
get: (params: DriveRequestParams) => Promise<DriveFileType>;
createVersion: (params: { company_id: string; drive_file_id: string; file_id: string }) => Promise<DriveFileType['item']['last_version_cache']>;
beginEditingSession: (company_id: string, drive_file_id: string) => Promise<string>;
endEditing: (company_id: string, editing_session_key: string, file_source_url: string) => Promise<void>;
endEditing: (company_id: string, editing_session_key: string, url: string) => Promise<void>;
getByEditingSessionKey: (params: { company_id: string; editing_session_key: string; user_token?: string }) => Promise<DriveFileType['item']>;
}
@@ -1,10 +1,3 @@
import { Router } from 'express';
export interface Routes {
path?: string;
router: Router;
}
export interface OfficeToken {
user_id: string;
company_id: string;
@@ -1,26 +1,41 @@
import { Application, Router } from 'express';
import * as path from 'path';
import { static as expressStatic, Application, Router } from 'express';
import * as Utils from '@/utils';
import { SERVER_ORIGIN, SERVER_PREFIX } from '@config';
import { HealthStatusController } from '@/controllers/health-status.controller';
import { TwakeDriveBackendCallbackRoutes } from './backend-callbacks.route';
import { BrowserEditorRoutes } from './browser-editor.route';
import { OnlyOfficeRoutes } from './onlyoffice.route';
import { SERVER_ORIGIN, SERVER_PREFIX, SERVER_TDRIVE_API_PREFIX } from '@config';
function mountAssetsRoutes(router: Router) {
router.use(
'/assets',
(req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'X-Requested-With');
next();
},
expressStatic(path.join(__dirname, '../../assets')),
);
}
export function mountRoutes(app: Application) {
// Technical routes for ops. Should not be exposed.
app.get('/health', HealthStatusController.get);
// These routes are forwarded through the Twake Drive front, back and here
const proxiedRouter = Router();
BrowserEditorRoutes.mount(proxiedRouter);
OnlyOfficeRoutes.mount(proxiedRouter);
console.log('Mounting at ' + SERVER_PREFIX);
app.use(SERVER_PREFIX, proxiedRouter);
mountAssetsRoutes(proxiedRouter);
app.use(SERVER_PREFIX /* usually "plugins/onlyoffice" */, proxiedRouter);
// These endpoints should only be accessible to the Twake Drive backend
const apiRouter = Router();
console.log('Mounting at ' + SERVER_TDRIVE_API_PREFIX);
TwakeDriveBackendCallbackRoutes.mount(apiRouter);
app.use(SERVER_TDRIVE_API_PREFIX, apiRouter);
app.use('/tdriveApi/1', apiRouter);
}
export const makeURLTo = {
@@ -30,14 +45,3 @@ export const makeURLTo = {
return Utils.joinURL([SERVER_ORIGIN ?? '', SERVER_PREFIX, 'editor'], params);
},
};
// export function makeURLToEditor2() {
// const initResponse = await editorService.init(company_id, file_name, file_id, user, preview, drive_file_id || file_id);
// res.render('index', {
// ...initResponse,
// docId: preview ? file_id : editing_session_key,
// server: Utils.joinURL([SERVER_ORIGIN, SERVER_PREFIX]),
// token: inPageToken,
// });
// }