Core API Reference

Complete reference for the MoroJS core API. Learn about application creation, configuration, and fundamental methods.

createApp()

Creates a new MoroJS application instance with optional configuration.

Basic Usage (Actual Implementation)

typescript

1import { createApp } from '@morojs/moro';
2
3// Create app with default settings
4const app = createApp();
5
6// Create app with basic configuration (actual API)
7const app = createApp({
8  cors: true,        // Enable CORS
9  compression: true, // Enable gzip compression  
10  helmet: true       // Enable security headers
11});
12
13// Simple route definition
14app.get('/', (req, res) => {
15  return { message: 'Hello from MoroJS!' };
16});
17
18// Start the server
19app.listen(3000, () => {
20  console.log('Server running on http://localhost:3000');
21});

Available Configuration Options

Basic Features
  • cors: true: Enable CORS
  • compression: true: Enable gzip
  • helmet: true: Enable security headers
Per-Route Features
  • .rateLimit(): Rate limiting
  • .cache(): Response caching
  • .body(): Body validation
  • .query(): Query validation

HTTP Methods

HTTP Method Definitions

typescript

1// GET request
2app.get('/path', handler);
3app.get('/path', { middleware: [], handler });
4
5// POST request
6app.post('/path', handler);
7app.post('/path', { body: schema, handler });
8
9// PUT request
10app.put('/path', handler);
11app.put('/path', { params: schema, body: schema, handler });
12
13// DELETE request
14app.delete('/path', handler);
15app.delete('/path', { params: schema, handler });
16
17// PATCH request
18app.patch('/path', handler);
19
20// HEAD request
21app.head('/path', handler);
22
23// OPTIONS request (usually automatic for CORS)
24app.options('/path', handler);
25
26// Multiple methods
27app.route('/path', ['GET', 'POST'], handler);

Route Configuration Object

typescript

1app.post('/users', {
2  // Request validation
3  params: UserParamsSchema,     // Route parameters
4  query: QuerySchema,           // Query string parameters
5  headers: HeadersSchema,       // Request headers
6  body: CreateUserSchema,       // Request body
7  
8  // Response definition
9  response: {
10    200: UserResponseSchema,
11    400: ErrorResponseSchema,
12    404: ErrorResponseSchema
13  },
14  
15  // Middleware
16  middleware: [authMiddleware, rateLimitMiddleware],
17  
18  // Main handler
19  handler: ({ params, query, headers, body, context }) => {
20    // Your logic here
21    return { success: true };
22  },
23  
24  // Error handlers
25  onValidationError: (errors) => ({ status: 400, body: { errors } }),
26  onError: (error) => ({ status: 500, body: { error: error.message } })
27});

Application Methods

Core Application Methods

typescript

1const app = createApp();
2
3// Global middleware
4app.use(middlewareFunction);
5
6// Route groups
7app.group('/api/v1', (group) => {
8  group.get('/users', getUsersHandler);
9  group.post('/users', createUserHandler);
10});
11
12// Start server (Node.js only)
13app.listen(port);
14app.listen(port, host);
15app.listen(port, host, callback);
16
17// Export for serverless platforms
18export default app;
19
20// Get server instance (Node.js only)
21const server = app.getServer();
22
23// Graceful shutdown
24await app.close();

Configuration Methods

typescript

1// Set global configuration
2app.configure({
3  cors: { origin: '*' },
4  rateLimit: { max: 1000, window: '1h' }
5});
6
7// Get current configuration
8const config = app.getConfig();
9
10// Set environment variables
11app.env({
12  DATABASE_URL: 'postgresql://...',
13  JWT_SECRET: 'your-secret-key'
14});
15
16// Access environment
17const dbUrl = app.env('DATABASE_URL');

Context and Utilities

Request Context

typescript

1// Available in all handlers and middleware
2interface RequestContext {
3  // HTTP primitives
4  request: Request;
5  response: Response;
6  
7  // Parsed data
8  params: Record<string, string>;
9  query: Record<string, string>;
10  headers: Record<string, string>;
11  body: any;
12  
13  // Middleware context
14  context: any;
15  
16  // Utilities
17  ip: string;
18  userAgent: string;
19  
20  // Methods
21  json(data: any): Response;
22  text(data: string): Response;
23  redirect(url: string, status?: number): Response;
24  status(code: number): ResponseBuilder;
25}

Utility Functions

typescript

1import { 
2  getCache, 
3  getRateLimiter, 
4  getLogger,
5  getWebSocketManager,
6  getEventBus 
7} from '@morojs/moro';
8
9// Cache utilities
10const cache = getCache();
11await cache.set('key', value, { ttl: '1h' });
12
13// Rate limiting utilities
14const rateLimiter = getRateLimiter();
15await rateLimiter.check('user:123', { max: 10, window: '1m' });
16
17// Logging utilities
18const logger = getLogger();
19logger.info('Message', { extra: 'data' });
20
21// WebSocket utilities
22const wsManager = getWebSocketManager();
23wsManager.broadcast({ type: 'notification', data: {} });
24
25// Event bus utilities
26const eventBus = getEventBus();
27eventBus.emit('user.created', { userId: '123' });

Next Steps