import {C4CApiHandler, C4CApiRequest, Router, Simulator} from "../src"; import * as fs from 'fs'; import * as path from 'path'; const config = require('./server.config.json'); const FOLDER = path.join(__dirname, config.appPath); const simulator = new Simulator(config); interface FunctionApp { path: string, name: string, entrance: { main: C4CApiHandler, createApp: (req: C4CApiRequest, context: Record) => Router } } const readFolder = (folderPath: string): Promise => { return new Promise((resolve, reject) => { fs.readdir(folderPath, (err: NodeJS.ErrnoException | null, items: string[]) => { if (err) { reject(err); } else { resolve(items); } }); }); }; const fileLoader = (filePath: string): Promise => { return new Promise((resolve, reject) => { import(filePath).then((module) => { resolve(module); }).catch(() => { import(filePath.replace('.js', '.ts')).then((module) => { resolve(module); }).catch(reject); }); }); }; const getApps = (): Promise => { return new Promise((resolve, reject) => { const appListPromises = [] as Promise<(FunctionApp | boolean)>[]; readFolder(FOLDER).then((items) => { for (let appName of items) { const status = fs.lstatSync(`${FOLDER}/${appName}`); if (status.isDirectory()) { appListPromises.push(checkActiveApp(`${FOLDER}/${appName}`)); } } Promise.all(appListPromises).then((results) => { resolve(results.filter(result => !!result) as FunctionApp[]); }); }).catch(reject); }); }; const checkActiveApp = (appPath: string): Promise => { return readFolder(appPath).then((items: string[]) => { if (items.includes('package.json')) { const config = require(`${appPath}/package.json`); if (!config.skipDeployment) { return fileLoader(`${appPath}/${config.main}`).then((entrance) => { return { path: config.webservice?.path, name: config.name, entrance }; }); } else { return false; } } else { return false; } }); }; getApps().then((apps) => { console.log(apps); simulator.deploy(async (request: C4CApiRequest, context: Record) => { for (let app of apps) { if (request.path.startsWith(app.path)) { const newRequest = Object.assign(request); let newPath = request.path.replace(app.path, ''); if (!newPath.startsWith('/')) { newPath = '/' + newPath; } newRequest.path = newPath; const newApp = app.entrance.createApp( newRequest, context ); return newApp.serve(); } } }); });