API Reference

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)
1import { createApp } from '@morojs/moro';
2
3// Create app with default settings
4const app = await createApp();
5
6// Create app with basic configuration (actual API)
7const app = await 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
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
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((req) => {
16    // Access via req.params, req.query, req.headers, req.body, req.context
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
1const app = await 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
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
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
1import {
2  getApp,
3  createCacheAdapter,
4  createFrameworkLogger,
5  middleware
6} from '@morojs/moro';
7
8// Reach the app instance created by createApp() from anywhere
9const app = getApp();
10
11// Cache — construct an adapter; ttl is seconds
12const cache = createCacheAdapter('memory');
13await cache.set('key', value, 3600);
14
15// Rate limiting is middleware, not a service you call
16app.use(middleware.rateLimit({ windowMs: 60_000, max: 100 }));
17
18// Logging — logger(message, context, metadata)
19const logger = createFrameworkLogger('MyModule');
20logger.info('Message', 'Startup', { extra: 'data' });
21
22// WebSockets — register namespaced handlers on the app
23app.websocket('/notifications', {
24  subscribe: (socket, data) => socket.join(data.channel)
25});
26
27// Event bus — listeners receive { context, data }
28app.events.on('user.created', ({ data }) => console.log(data.userId));
29await app.events.emit('user.created', { userId: '123' });

Next Steps