diff --git a/src/app.ts b/src/app.ts index c40d83e..a81956c 100644 --- a/src/app.ts +++ b/src/app.ts @@ -5,6 +5,8 @@ import express, { NextFunction, Request, Response } from 'express'; import * as api from './api'; import { allApplications } from './constants'; import AppError from './utils/appError'; +import { findJsonFilesRecursively } from './utils/autoDeploy'; +import { appsDirectory } from './utils/config'; import globalErrorHandler from './utils/errorHandler'; const app = express(); @@ -42,6 +44,15 @@ app.all('*', (req: Request, res: Response, next: NextFunction) => { next(new AppError(`Can't find ${req.originalUrl} on this server!`, 404)); }); +const appsDir = appsDirectory(); +findJsonFilesRecursively(appsDir) + .then(() => { + console.log('Previously deployed apllications deployed successfully'); + }) + .catch(error => { + console.error('Error while re-deploying applications', error); + }); + app.use(globalErrorHandler); export default app; diff --git a/src/utils/autoDeploy.ts b/src/utils/autoDeploy.ts new file mode 100644 index 0000000..75539ec --- /dev/null +++ b/src/utils/autoDeploy.ts @@ -0,0 +1,56 @@ +import { spawn } from 'child_process'; +import * as fs from 'fs'; +import * as path from 'path'; +import { + allApplications, + childProcessResponse, + cps, + currentFile, + protocol +} from '../constants'; +import { isIAllApps } from './utils'; + +export const findJsonFilesRecursively = async ( + appsDir: string +): Promise => { + const files = fs.readdirSync(appsDir, { withFileTypes: true }); + for (const file of files) { + if (file.isDirectory()) { + await findJsonFilesRecursively(path.join(appsDir, file.name)); + } else if (file.name === 'metacall.json') { + const filePath = path.join(appsDir, file.name); + const desiredPath = path.join(__dirname, '../worker/index.js'); + const id = path.basename(appsDir); + + currentFile.id = id; + (currentFile.type = 'application/x-zip-compressed'), + (currentFile.path = appsDir); + + const proc = spawn('metacall', [desiredPath, filePath], { + stdio: ['pipe', 'pipe', 'pipe', 'ipc'] + }); + + proc.send({ + type: protocol.l, + currentFile + }); + + proc.stdout?.on('data', (data: Buffer) => { + console.log(data.toString().green); + }); + proc.stderr?.on('data', (data: Buffer) => { + console.log(data.toString().red); + }); + + proc.on('message', (data: childProcessResponse) => { + if (data.type === protocol.g) { + if (isIAllApps(data.data)) { + const appName = Object.keys(data.data)[0]; + cps[appName] = proc; + allApplications[appName] = data.data[appName]; + } + } + }); + } + } +};