import { Server } from 'hyper-express'; import { Environment } from '../types/Environment.ts'; import { Route } from '../Route/Route'; import { createDocument, ZodOpenApiObject } from 'zod-openapi'; import * as fs from 'node:fs'; import * as path from 'node:path'; import { WorkerManager, WorkerManagerParams } from '../Workers/WorkerManager'; import { swaggerTemplate } from '../Swagger/SwaggerTemplate.ts'; import { z, ZodObject } from 'zod'; // DIRTY HACK FOR FILE LOGGING if (!(File.prototype as any).toJSON) { (File.prototype as any).toJSON = function () { return { name: this.name, size: this.size, type: this.type, lastModified: this.lastModified, }; }; } export interface BackendConfigInfo { readonly title: string; readonly version: string; readonly description: string; readonly fileName: string; } export interface BackendConfigSettings { readonly maxBodyLength?: number; readonly swaggerPath: string; readonly customHeaders?: string[]; readonly workers?: WorkerManagerParams; readonly staticFolder?: string; } export interface BackendConfig { // swagger info readonly info: BackendConfigInfo; // server settings readonly settings: BackendConfigSettings; // environment variables. Need only to check launch readonly environment: Environment; // routes array readonly routes: Route< ZodObject, ZodObject, ZodObject, ZodObject, ZodObject >[]; } /** * Backend representation * @param {BackendConfig} config backend settings */ export class Backend { static new(config: BackendConfig) { return new Backend(config); } private server: Server; private workerManager: WorkerManager | undefined; private constructor(private config: BackendConfig) { this.server = new Server({ max_body_length: config?.settings?.maxBodyLength || 50 * 1024 * 1024, }); this.workerManager = config.settings.workers ? WorkerManager.new(config.settings.workers) : undefined; } /** * Runs backend * @param {number} port */ run(port: number): Promise { const environmentItems = Object.entries(this.config.environment); for (let item of environmentItems) { if (item[1].required && !item[1].value) { throw new Error(`${item[0]} required.`); } } const allowedHeaders = [ 'Origin', 'X-Requested-With', 'Content-Type', 'Accept', 'Authorization', ] .concat( this.config.settings.customHeaders ? this.config.settings.customHeaders : [], ) .join(', '); this.server.use((req, res, next) => { res.header('Access-Control-Allow-Origin', '*'); res.header( 'Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS', ); // Allowed methods res.header('Access-Control-Allow-Headers', allowedHeaders); if (req.method === 'OPTIONS') { return res.status(200).send(); } next(); }); this.server.get('/health', (_, response) => { return response.send('ok'); }); if (this.config.settings.staticFolder) { const staticFolder = this.config.settings.staticFolder; let dir: string[] = []; try { dir = fs .readdirSync(staticFolder, { recursive: true, }) .filter((f) => typeof f === 'string'); } catch { console.log({ time: new Date().toISOString(), message: 'No static directory. Pls create it', }); } this.server.get('*.[js|css|png|jpeg|jpg|html|svg]', (req, res) => { const filePath = dir.find((path) => req.url.endsWith(path)); if (!filePath) { res.status(404).send(); } else { res.status(200).file(path.resolve(staticFolder, filePath)); } }); this.server.get('/', (_req, res) => { if (dir.includes('index.html')) { return res.status(200).file(path.resolve(staticFolder, 'index.html')); } else { res.status(404); } }); } for (let route of this.config.routes) { switch (route.info.method) { case 'get': this.server.get(route.info.route, route.handler(this.workerManager)); break; case 'post': this.server.post(route.info.route, route.handler(this.workerManager)); break; case 'patch': this.server.patch( route.info.route, route.handler(this.workerManager), ); break; case 'put': this.server.put(route.info.route, route.handler(this.workerManager)); break; case 'delete': this.server.delete( route.info.route, route.handler(this.workerManager), ); break; } } const apiSpec = this.generateSwaggerSpec(); const jsonSpec = JSON.stringify(apiSpec, null, 2); fs.writeFileSync( path.resolve( this.config.settings.swaggerPath, `./${this.config.info.fileName}.json`, ), jsonSpec, ); console.log({ time: new Date().toISOString(), message: 'Swagger spec created!', }); this.server.get('/docs/openapi', (_, response) => { response.json(apiSpec); }); this.server.get('/docs/openapi/ui', (_, response) => { response.html(swaggerTemplate); }); console.log({ time: new Date().toISOString(), message: 'Swagger routes added', }); return this.server.listen(port, () => { console.log({ time: new Date().toISOString(), message: 'Service started!', }); console.log({ time: new Date().toISOString(), message: 'Environment', data: environmentItems.reduce((acc, [name, item]) => { return { ...acc, [name]: item.sensitive ? '******' : `${item.value instanceof Object ? JSON.stringify(item.value, null, 2) : item.value}`, }; }, {}), }); }); } private generateSwaggerSpec() { const zodOpenApiObject: ZodOpenApiObject = this.config.routes.reduce( (swagger, route) => { // [route.info.method]: { // summary: route.info.summary, // tags: route.info.tags, // parameters: headerParams.concat(queryParams).concat(pathParams), swagger.paths![route.info.route] = { [route.info.method]: { summary: route.info.summary, tags: route.info.tags, requestParams: { header: route.info.headers || z.object({}), query: route.info.query || z.object({}), path: route.info.path || z.object({}), }, responses: { [route.info.result.status]: { description: route.info.result.content.description, content: { 'application/json': { schema: route.info.result.content, }, }, }, 400: { description: 'Bad Request', content: { 'application/json': { schema: { type: 'object', properties: { cause: { description: 'cause of error', type: 'string', }, message: { description: 'error message', type: 'string', }, }, }, }, }, }, 500: { description: 'Internal Server Error', content: { 'application/json': { schema: { type: 'object', properties: { cause: { description: 'cause of error', type: 'string', }, message: { description: 'error message', type: 'string', }, }, }, }, }, }, }, requestBody: route.info.body ? { content: route.info.body?.contentType === 'application/json' ? { 'application/json': { schema: route.info.body.payload, }, } : { 'multipart/form-data': { schema: route.info.body.payload, }, }, } : undefined, }, }; return swagger; }, { openapi: '3.1.0', info: { title: this.config.info.title, description: this.config.info.description, version: this.config.info.version, }, paths: { '/health': { get: { summary: 'health check', tags: ['System'], responses: { 200: { description: 'Ok', content: { 'plain/text': { schema: { type: 'string', description: 'ok', }, }, }, }, }, }, }, }, }, ); return createDocument(zodOpenApiObject, { cycles: 'ref', }); } }