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// Chainable API style - Recommended
2app.get('/path').handler(handlerFn);
3
4app.post('/path')
5  .body(schema)
6  .handler(handlerFn);
7
8app.put('/path')
9  .params(paramsSchema)
10  .body(bodySchema)
11  .handler(handlerFn);
12
13app.delete('/path')
14  .params(schema)
15  .handler(handlerFn);
16
17app.patch('/path').handler(handlerFn);
18app.head('/path').handler(handlerFn);
19app.options('/path').handler(handlerFn);
20
21// Schema-based routing style - For complex configurations
22app.route({
23  method: 'POST',
24  path: '/users',
25  validation: {
26    params: UserParamsSchema,
27    query: QuerySchema,
28    headers: HeadersSchema,
29    body: CreateUserSchema
30  },
31  handler: ({ params, query, headers, body }) => {
32    // Your logic here
33    return { success: true };
34  }
35});

Complete Route Configuration Examples

typescript

1import { Moro, z } from '@morojs/moro';
2
3const app = new Moro();
4
5// Chainable API - Full configuration
6app.post('/users')
7  .params(UserParamsSchema)
8  .query(QuerySchema)
9  .headers(HeadersSchema)
10  .body(CreateUserSchema)
11  .auth({ roles: ['admin'] })
12  .rateLimit({ requests: 10, window: 60000 })
13  .describe('Create a new user')
14  .tag('users', 'write')
15  .handler(({ params, query, headers, body, context }) => {
16    // Your logic here
17    return { success: true };
18  });
19
20// Schema-based routing - Alternative for complex configs
21app.route({
22  method: 'POST',
23  path: '/users-alt',
24  validation: {
25    params: UserParamsSchema,
26    query: QuerySchema,
27    headers: HeadersSchema,
28    body: CreateUserSchema
29  },
30  auth: { roles: ['admin'] },
31  rateLimit: { requests: 10, window: 60000 },
32  description: 'Create a new user',
33  tags: ['users', 'write'],
34  handler: ({ params, query, headers, body, context }) => {
35    // Your logic here
36    return { success: true };
37  }
38});

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').handler(getUsersHandler);
9  group.post('/users').handler(createUserHandler);
10});
11
12// Start server (Node.js only)
13await app.listen(() => {
14  console.log('Server running');
15});
16
17// Export for serverless platforms
18export default app;
19
20// Get configuration
21const config = app.getConfig();
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