Features
Docs
CLI
Benchmarks
Examples

© 2024 MoroJs

Enterprise Application Example

A complete enterprise-grade application with modular architecture. Copy, run, and customize.

Complete Working Example

1// src/server.ts - Enterprise Application with Functional Modules
2import { createApp } from '@morojs/moro';
3import UsersModule from './modules/users';
4import OrdersModule from './modules/orders';
5import TodosModule from './modules/todos';
6import HealthModule from './modules/health';
7
8async function createEnterpriseApp() {
9  // Use the functional createApp approach
10  const app = createApp({
11    cors: true,
12    compression: true,
13    helmet: true
14  });
15
16  // Simulated database (in real app, use MySQLAdapter)
17  const mockDatabase = {
18    users: [
19      { id: 1, name: 'John Doe', email: 'john@example.com', role: 'admin' },
20      { id: 2, name: 'Jane Smith', email: 'jane@example.com', role: 'user' }
21    ],
22    orders: [
23      { id: 1, userId: 1, product: 'Laptop', amount: 999.99, status: 'completed' },
24      { id: 2, userId: 2, product: 'Mouse', amount: 29.99, status: 'pending' }
25    ],
26    todos: [
27      { id: 1, title: 'Learn MoroJS', description: 'Explore the functional module architecture', completed: false, priority: 'high' }
28    ]
29  };
30
31  // Register database
32  app.database(mockDatabase);
33
34  // Add enterprise middleware
35  app.use((req: any, res: any, next: () => void) => {
36    console.log(`[${new Date().toISOString()}] ${req.method} ${req.path}`);
37    next();
38  });
39
40  // Load enterprise modules using the functional module system
41  await app.loadModule(HealthModule);
42  await app.loadModule(UsersModule);
43  await app.loadModule(OrdersModule);
44  await app.loadModule(TodosModule);
45
46  // Root endpoint
47  app.get('/', (req, res) => {
48    return {
49      message: 'Enterprise API with Functional Modules',
50      timestamp: new Date().toISOString(),
51      modules: ['health', 'users', 'orders', 'todos'],
52      architecture: 'functional-event-driven'
53    };
54  });
55
56  // Health check endpoint
57  app.get('/health', (req, res) => {
58    return {
59      status: 'ok',
60      timestamp: new Date().toISOString(),
61      uptime: process.uptime(),
62      architecture: 'Functional Modules Active'
63    };
64  });
65
66  return app;
67}
68
69async function bootstrap() {
70  try {
71    const app = await createEnterpriseApp();
72    const port = parseInt(process.env.PORT || '3002');
73
74    app.listen(port, () => {
75      console.log('🏢 Enterprise Application Started');
76      console.log(`HTTP API: http://localhost:${port}`);
77      console.log(`WebSocket: ws://localhost:${port}`);
78      console.log('Available APIs:');
79      console.log(`  Root: http://localhost:${port}/`);
80      console.log(`  Health: http://localhost:${port}/health`);
81      console.log(`  Users:  http://localhost:${port}/api/v1.0.0/users/`);
82      console.log(`  Orders: http://localhost:${port}/api/v1.0.0/orders/`);
83      console.log(`  Todos:  http://localhost:${port}/api/v1.0.0/todos/`);
84    });
85
86    // Graceful shutdown
87    process.on('SIGTERM', () => {
88      console.log('🏢 Enterprise app shutting down gracefully...');
89      process.exit(0);
90    });
91
92  } catch (error) {
93    console.error('❌ Failed to start enterprise application:', error);
94    process.exit(1);
95  }
96}
97
98bootstrap();

What This Does

  • Creates an enterprise application with functional module architecture
  • Loads multiple modules (users, orders, todos, health)
  • Sets up in-memory database with mock data
  • Configures enterprise middleware (CORS, compression, security headers)
  • Implements graceful shutdown handling

Project Structure

Functional Architecture

typescript

1enterprise-app/
2├── src/
3│   ├── modules/
4│   │   ├── users/
5│   │   │   ├── index.ts        # Module definition
6│   │   │   ├── routes.ts       # Route handlers
7│   │   │   ├── sockets.ts      # WebSocket handlers
8│   │   │   ├── actions.ts      # Business logic
9│   │   │   └── types.ts        # Type definitions
10│   │   ├── orders/
11│   │   │   ├── index.ts
12│   │   │   ├── routes.ts
13│   │   │   ├── actions.ts
14│   │   │   └── types.ts
15│   │   ├── todos/
16│   │   │   ├── index.ts
17│   │   │   ├── routes.ts
18│   │   │   ├── actions.ts
19│   │   │   └── types.ts
20│   │   └── health/
21│   │       └── index.ts
22│   └── server.ts               # Main application
23├── package.json
24├── tsconfig.json
25└── README.md
26
27// Key Features Demonstrated:
28✅ Functional modular architecture
29✅ Event-driven communication
30✅ In-memory data storage (easily replaceable)
31✅ Comprehensive validation with Zod
32✅ WebSocket support per module
33✅ Versioned API endpoints (/api/v1.0.0/)
34✅ Middleware system
35✅ Type-safe request handling
36✅ Clean separation of concerns
37✅ Easy module loading/unloading
38✅ Graceful shutdown handling
39✅ Development-friendly logging

Module Example

Functional Users Module Implementation

typescript

1// modules/users/index.ts - Functional Module Architecture
2import { defineModule } from '@morojs/moro';
3import { config } from './config';
4import { routes } from './routes';
5import { userSockets as sockets } from './sockets';
6
7export default defineModule({
8  name: 'users',
9  version: '1.0.0',
10  config,
11  routes,
12  sockets,
13});
14
15// Re-export types and actions for direct usage
16export * from './types';
17export * from './actions';
18
19// modules/users/config.ts - Module configuration
20export const config = {
21  prefix: '/api/v1.0.0/users',
22};
23
24// modules/users/routes.ts - Route definitions
25import { z, validate } from '@morojs/moro';
26import * as actions from './actions';
27
28export function routes(app: any) {
29  // GET /api/v1.0.0/users/ - List all users
30  app.get('/', (req: any, res: any) => {
31    const users = actions.getAllUsers(req.database);
32    return {
33      success: true,
34      data: users,
35      total: users.length
36    };
37  });
38
39  // GET /api/v1.0.0/users/:id - Get user by ID
40  app.get('/:id', 
41    validate({
42      params: z.object({
43        id: z.coerce.number()
44      })
45    }, (req: any, res: any) => {
46      const user = actions.getUserById(req.database, req.params.id);
47      if (!user) {
48        res.status(404);
49        return { error: 'User not found' };
50      }
51      return { success: true, data: user };
52    })
53  );
54
55  // POST /api/v1.0.0/users/ - Create new user
56  app.post('/',
57    validate({
58      body: z.object({
59        name: z.string().min(2).max(50),
60        email: z.string().email(),
61        role: z.enum(['admin', 'user']).default('user')
62      })
63    }, (req: any, res: any) => {
64      try {
65        const newUser = actions.createUser(req.database, req.body);
66        return { 
67          success: true, 
68          data: newUser,
69          message: 'User created successfully'
70        };
71      } catch (error: any) {
72        res.status(400);
73        return { error: error.message };
74      }
75    })
76  );
77
78  // PUT /api/v1.0.0/users/:id - Update user
79  app.put('/:id',
80    validate({
81      params: z.object({
82        id: z.coerce.number()
83      }),
84      body: z.object({
85        name: z.string().min(2).max(50).optional(),
86        email: z.string().email().optional(),
87        role: z.enum(['admin', 'user']).optional()
88      })
89    }, (req: any, res: any) => {
90      try {
91        const updatedUser = actions.updateUser(req.database, req.params.id, req.body);
92        if (!updatedUser) {
93          res.status(404);
94          return { error: 'User not found' };
95        }
96        return { 
97          success: true, 
98          data: updatedUser,
99          message: 'User updated successfully'
100        };
101      } catch (error: any) {
102        res.status(400);
103        return { error: error.message };
104      }
105    })
106  );
107}
108
109// modules/users/actions.ts - Business logic
110export function getAllUsers(database: any) {
111  return database.users || [];
112}
113
114export function getUserById(database: any, id: number) {
115  return database.users?.find((user: any) => user.id === id);
116}
117
118export function createUser(database: any, userData: any) {
119  // Check if email already exists
120  const existingUser = database.users?.find((u: any) => u.email === userData.email);
121  if (existingUser) {
122    throw new Error('User with this email already exists');
123  }
124
125  const newUser = {
126    id: Math.max(...database.users.map((u: any) => u.id), 0) + 1,
127    ...userData,
128    createdAt: new Date().toISOString(),
129    updatedAt: new Date().toISOString()
130  };
131
132  database.users.push(newUser);
133  return newUser;
134}
135
136export function updateUser(database: any, id: number, updateData: any) {
137  const userIndex = database.users?.findIndex((u: any) => u.id === id);
138  if (userIndex === -1) {
139    return null;
140  }
141
142  database.users[userIndex] = {
143    ...database.users[userIndex],
144    ...updateData,
145    updatedAt: new Date().toISOString()
146  };
147
148  return database.users[userIndex];
149}

Try It Yourself

Clone the repository and run the enterprise example:

1# Clone the repository
2git clone https://github.com/Moro-JS/examples.git
3cd examples/enterprise-app
4
5# Install dependencies
6npm install
7
8# Start development server (no database setup required)
9npm run dev
10
11# The application will be available at:
12# - API: http://localhost:3002
13# - Health Check: http://localhost:3002/health
14# - Users API: http://localhost:3002/api/v1.0.0/users/
15# - Orders API: http://localhost:3002/api/v1.0.0/orders/
16# - Todos API: http://localhost:3002/api/v1.0.0/todos/
17
18# Available scripts:
19npm run dev          # Start development server
20npm run build        # Build for production  
21npm run start        # Start production server
22
23# Note: This example uses functional modules with in-memory storage
24# No database setup required for basic functionality
25# Real enterprise apps would use database adapters (MySQL, PostgreSQL, etc.)

Key API Endpoints

GET http://localhost:3002/
GET http://localhost:3002/health
GET http://localhost:3002/api/v1.0.0/users/
POST http://localhost:3002/api/v1.0.0/users/
GET http://localhost:3002/api/v1.0.0/orders/
GET http://localhost:3002/api/v1.0.0/todos/

What You'll Learn

  • Enterprise-grade application architecture
  • Module-based code organization
  • Authentication and authorization patterns
  • Database design and optimization
  • Event-driven communication
  • Comprehensive testing strategies
  • Production deployment patterns

Next Steps