import { ExpressHttpApp, createExpressApp, FastifyHttpApp, createFastifyApp } from '../src/infra/http/http-app'; import { SecurityPlugin } from '../src/infra/http/plugins/security-plugin'; import { HealthCheckPlugin } from '../src/infra/http/plugins/plugins/health-check-plugin'; import { MetricsPlugin } from '../src/infra/http/plugins/plugins/metrics-plugin'; /** * HTTP App Frameworks Example * * This example demonstrates how to use the new HttpApp architecture * with different HTTP frameworks (Express and Fastify). */ async function expressExample() { console.log('šŸš€ Express HTTP App Example'); console.log('===========================\n'); // Create Express application const app = createExpressApp(); // Configure the app app .setTrustProxy(true) .setStatic('public') .setViewEngine('ejs') .configure((app) => { // Custom configuration console.log('Configuring Express app...'); }); // Add plugins app .usePlugin(new SecurityPlugin({ enabled: true, exposeEndpoints: true })) .usePlugin(new HealthCheckPlugin({ path: '/health' })) .usePlugin(new MetricsPlugin({ exposeEndpoint: true, metricsPath: '/metrics' })); // Add routes app.addRoute({ method: 'GET', path: '/', handler: async (req, res) => { return { message: 'Hello from Express!', framework: 'Express.js' }; } }); // Start the server try { await app.start(3000); console.log('āœ… Express server started successfully'); // Stop after 5 seconds for demo setTimeout(async () => { await app.stop(); console.log('āœ… Express server stopped'); }, 5000); } catch (error) { console.error('āŒ Failed to start Express server:', error); } } async function fastifyExample() { console.log('⚔ Fastify HTTP App Example'); console.log('===========================\n'); // Create Fastify application const app = createFastifyApp(); // Configure the app app .setConfig({ trustProxy: true, logger: true }) .configure((app) => { // Custom configuration console.log('Configuring Fastify app...'); }); // Add plugins app .usePlugin(new SecurityPlugin({ enabled: true, exposeEndpoints: true })) .usePlugin(new HealthCheckPlugin({ path: '/health' })) .usePlugin(new MetricsPlugin({ exposeEndpoint: true, metricsPath: '/metrics' })); // Add routes with schema validation app.addRouteWithSchema({ method: 'GET', url: '/', schema: { response: { 200: { type: 'object', properties: { message: { type: 'string' }, framework: { type: 'string' } } } } }, handler: async (request, reply) => { return { message: 'Hello from Fastify!', framework: 'Fastify' }; } }); // Start the server try { await app.start(3001); console.log('āœ… Fastify server started successfully'); // Stop after 5 seconds for demo setTimeout(async () => { await app.stop(); console.log('āœ… Fastify server stopped'); }, 5000); } catch (error) { console.error('āŒ Failed to start Fastify server:', error); } } async function comparisonExample() { console.log('šŸ”„ Framework Comparison Example'); console.log('================================\n'); // Create both applications const expressApp = createExpressApp(); const fastifyApp = createFastifyApp(); // Add the same plugins to both const securityPlugin = new SecurityPlugin({ enabled: true, exposeEndpoints: true, endpointsPath: '/security' }); const healthPlugin = new HealthCheckPlugin({ path: '/health' }); expressApp.usePlugin(securityPlugin).usePlugin(healthPlugin); fastifyApp.usePlugin(securityPlugin).usePlugin(healthPlugin); // Add the same route to both const testRoute = { method: 'GET', path: '/test', handler: async (req: any, res: any) => { return { message: 'Test route', timestamp: new Date().toISOString(), framework: expressApp.isApplicationStarted() ? 'Express' : 'Fastify' }; } }; expressApp.addRoute(testRoute); fastifyApp.addRoute(testRoute); console.log('šŸ“Š Framework Comparison:'); console.log('Express App:'); console.log(` - Plugins: ${expressApp.listPlugins().length}`); console.log(` - Routes: ${expressApp.getRouteRegistry().getRoutes().length}`); console.log(` - Container services: ${Object.keys(expressApp.getContainer().services).length}`); console.log('\nFastify App:'); console.log(` - Plugins: ${fastifyApp.listPlugins().length}`); console.log(` - Routes: ${fastifyApp.getRouteRegistry().getRoutes().length}`); console.log(` - Container services: ${Object.keys(fastifyApp.getContainer().services).length}`); } async function advancedFeaturesExample() { console.log('šŸŽÆ Advanced Features Example'); console.log('=============================\n'); // Express with advanced features const expressApp = createExpressApp(); expressApp .setTrustProxy(true) .setStatic('public', { index: ['index.html', 'index.htm'] }) .setViewEngine('pug') .addErrorHandler((err: any, req: any, res: any, next: any) => { console.error('Express Error:', err); res.status(500).json({ error: 'Internal Server Error' }); }) .useExpressMiddleware((req, res, next) => { console.log(`Express: ${req.method} ${req.path}`); next(); }); // Fastify with advanced features const fastifyApp = createFastifyApp(); fastifyApp .setConfig({ trustProxy: true, logger: { level: 'info', transport: { target: 'pino-pretty' } } }) .addHook('onRequest', async (request, reply) => { console.log(`Fastify: ${request.method} ${request.url}`); }) .addHook('onError', async (request, reply, error) => { console.error('Fastify Error:', error); reply.code(500).send({ error: 'Internal Server Error' }); }) .decorate('customHelper', () => { return 'This is a custom Fastify helper'; }); console.log('āœ… Advanced features configured for both frameworks'); } async function pluginSystemExample() { console.log('šŸ”Œ Plugin System Example'); console.log('=========================\n'); const app = createExpressApp(); // Register multiple plugins app .usePlugin(new SecurityPlugin({ enabled: true, exposeEndpoints: true, headers: { enabled: true, headers: { contentSecurityPolicy: "default-src 'self'", frameOptions: 'DENY' } } })) .usePlugin(new HealthCheckPlugin({ path: '/health', checks: [ { name: 'database', check: async () => ({ status: 'healthy', message: 'Database connection OK' }) }, { name: 'redis', check: async () => ({ status: 'healthy', message: 'Redis connection OK' }) } ] })) .usePlugin(new MetricsPlugin({ exposeEndpoint: true, metricsPath: '/metrics', includeSystemMetrics: true })); console.log('šŸ“‹ Installed Plugins:'); app.listPlugins().forEach(plugin => { console.log(` - ${plugin.name} v${plugin.version}: ${plugin.description}`); }); console.log('\nšŸ”§ Plugin Management:'); console.log(` - Total plugins: ${app.listPlugins().length}`); console.log(` - Installed plugins: ${app.getInstalledPlugins().length}`); console.log(` - Security plugin loaded: ${app.isPluginLoaded('security')}`); console.log(` - Health plugin loaded: ${app.isPluginLoaded('health-check')}`); console.log(` - Metrics plugin loaded: ${app.isPluginLoaded('metrics')}`); } // Export factory functions for different frameworks export function createExpressApplication(): ExpressHttpApp { return createExpressApp(); } export function createFastifyApplication(): FastifyHttpApp { return createFastifyApp(); } export function createApplicationWithSecurity(): ExpressHttpApp { const app = createExpressApp(); app.usePlugin(new SecurityPlugin({ enabled: true, exposeEndpoints: true, headers: { enabled: true, headers: { contentSecurityPolicy: "default-src 'self'", frameOptions: 'DENY', contentTypeOptions: true } }, csrf: { enabled: true, secret: process.env.CSRF_SECRET || 'change-in-production' } })); return app; } export function createApplicationWithMonitoring(): ExpressHttpApp { const app = createExpressApp(); app .usePlugin(new HealthCheckPlugin({ path: '/health', responseFormat: 'json' })) .usePlugin(new MetricsPlugin({ exposeEndpoint: true, metricsPath: '/metrics', metricsFormat: 'prometheus' })); return app; } // Run all examples async function runAllExamples() { try { await expressExample(); await new Promise(resolve => setTimeout(resolve, 1000)); await fastifyExample(); await new Promise(resolve => setTimeout(resolve, 1000)); await comparisonExample(); await new Promise(resolve => setTimeout(resolve, 1000)); await advancedFeaturesExample(); await new Promise(resolve => setTimeout(resolve, 1000)); await pluginSystemExample(); console.log('\nšŸŽ‰ All examples completed successfully!'); } catch (error) { console.error('āŒ Error running examples:', error); } } // Run the examples if this file is executed directly if (require.main === module) { runAllExamples(); } export default runAllExamples;