Types API Reference
Complete TypeScript type definitions for MoroJS. Build type-safe applications with full IntelliSense support and compile-time validation.
Core Types
Essential TypeScript interfaces and types for building MoroJS applications.
Application Types
typescript
1import type {
2 Moro,
3 MoroConfig,
4 MoroOptions,
5 RuntimeAdapter
6} from '@morojs/moro';
7
8// Main application interface
9interface Moro {
10 // HTTP methods
11 get<T = any>(path: string, handler: RouteHandler<T>): void;
12 get<T = any>(path: string, config: RouteConfig<T>): void;
13 post<T = any>(path: string, handler: RouteHandler<T>): void;
14 post<T = any>(path: string, config: RouteConfig<T>): void;
15 put<T = any>(path: string, handler: RouteHandler<T>): void;
16 put<T = any>(path: string, config: RouteConfig<T>): void;
17 delete<T = any>(path: string, handler: RouteHandler<T>): void;
18 delete<T = any>(path: string, config: RouteConfig<T>): void;
19 patch<T = any>(path: string, handler: RouteHandler<T>): void;
20 patch<T = any>(path: string, config: RouteConfig<T>): void;
21 head<T = any>(path: string, handler: RouteHandler<T>): void;
22 options<T = any>(path: string, handler: RouteHandler<T>): void;
23
24 // Application methods
25 use(...middleware: MiddlewareFunction[]): void;
26 group(prefix: string, callback: (group: Moro) => void): void;
27 listen(port: number, host?: string, callback?: () => void): void;
28 close(): Promise<void>;
29
30 // Configuration
31 configure(config: Partial<MoroConfig>): void;
32 getConfig(): MoroConfig;
33 getConfig<K extends keyof MoroConfig>(key: K): MoroConfig[K];
34
35 // Environment
36 env(): Record<string, string>;
37 env<T = Record<string, string>>(): T;
38 env(key: string): string | undefined;
39 env(schema: EnvSchema): void;
40}
41
42// Configuration interface
43interface MoroConfig {
44 server?: ServerConfig;
45 security?: SecurityConfig;
46 database?: DatabaseConfig;
47 logging?: LoggingConfig;
48 features?: FeaturesConfig;
49}
50
51// Runtime adapter interface
52interface RuntimeAdapter {
53 name: 'node' | 'edge' | 'lambda' | 'worker';
54 createHandler(app: Moro): any;
55 transformRequest(request: any): Request;
56 transformResponse(response: Response): any;
57}
Request/Response Types
Handler and Context Types
typescript
1// Route handler function type
2type RouteHandler<T = any> = (context: RequestContext) => T | Promise<T>;
3
4// Request context interface
5interface RequestContext {
6 // HTTP primitives
7 request: Request;
8 response: Response;
9
10 // Parsed request data
11 params: Record<string, string>;
12 query: Record<string, string | string[]>;
13 headers: Record<string, string>;
14 body: any;
15
16 // Request metadata
17 ip: string;
18 userAgent: string;
19 method: HttpMethod;
20 url: string;
21 path: string;
22
23 // Shared context for middleware communication
24 context: Record<string, any>;
25
26 // Response builders
27 json(data: any, status?: number): Response;
28 text(data: string, status?: number): Response;
29 html(data: string, status?: number): Response;
30 status(code: number): ResponseBuilder;
31 redirect(url: string, status?: number): Response;
32
33 // Context utilities
34 set(key: string, value: any): void;
35 get(key: string): any;
36 has(key: string): boolean;
37 delete(key: string): void;
38}
39
40// Response builder interface
41interface ResponseBuilder {
42 json(data: any): Response;
43 text(data: string): Response;
44 html(data: string): Response;
45 send(data: any): Response;
46 end(): Response;
47 header(name: string, value: string): ResponseBuilder;
48 headers(headers: Record<string, string>): ResponseBuilder;
49 cookie(name: string, value: string, options?: CookieOptions): ResponseBuilder;
50}
51
52// HTTP method type
53type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' | 'OPTIONS';
54
55// Cookie options
56interface CookieOptions {
57 domain?: string;
58 expires?: Date;
59 httpOnly?: boolean;
60 maxAge?: number;
61 path?: string;
62 secure?: boolean;
63 signed?: boolean;
64 sameSite?: boolean | 'lax' | 'strict' | 'none';
65}
Route Configuration Types
Route Configuration Interface
typescript
1// Route configuration object
2interface RouteConfig<T = any> {
3 // Validation schemas (Zod schemas)
4 params?: ZodSchema;
5 query?: ZodSchema;
6 headers?: ZodSchema;
7 body?: ZodSchema;
8
9 // Response schema definitions
10 response?: {
11 [statusCode: number]: ZodSchema;
12 };
13
14 // Middleware
15 middleware?: MiddlewareFunction[];
16
17 // Main handler
18 handler: RouteHandler<T>;
19
20 // Error handlers
21 onValidationError?: (errors: ValidationError[]) => Response | Promise<Response>;
22 onError?: (error: Error, context: RequestContext) => Response | Promise<Response>;
23
24 // Route metadata
25 tags?: string[];
26 summary?: string;
27 description?: string;
28 deprecated?: boolean;
29
30 // Rate limiting (route-specific)
31 rateLimit?: {
32 max: number;
33 window: string;
34 keyGenerator?: (context: RequestContext) => string;
35 };
36
37 // Caching
38 cache?: {
39 ttl: string;
40 key?: (context: RequestContext) => string;
41 vary?: string[];
42 };
43}
44
45// Validation error type
46interface ValidationError {
47 field: string;
48 message: string;
49 code: string;
50 value?: any;
51}
52
53// Zod schema type (re-exported from Zod)
54type ZodSchema = z.ZodSchema<any>;
Middleware Types
Middleware Function Types
typescript
1// Middleware function type
2type MiddlewareFunction = (
3 context: RequestContext,
4 next: NextFunction
5) => void | Promise<void>;
6
7// Next function type
8type NextFunction = () => void | Promise<void>;
9
10// Middleware factory type (for configurable middleware)
11type MiddlewareFactory<T = any> = (options?: T) => MiddlewareFunction;
12
13// Built-in middleware options
14interface CorsOptions {
15 origin?: string | string[] | ((origin: string) => boolean);
16 methods?: string[];
17 allowedHeaders?: string[];
18 exposedHeaders?: string[];
19 credentials?: boolean;
20 maxAge?: number;
21 preflightContinue?: boolean;
22 optionsSuccessStatus?: number;
23}
24
25interface RateLimitOptions {
26 max: number;
27 window: string;
28 keyGenerator?: (context: RequestContext) => string;
29 skip?: (context: RequestContext) => boolean;
30 onLimitReached?: (context: RequestContext) => Response | Promise<Response>;
31 store?: RateLimitStore;
32}
33
34interface HelmetOptions {
35 contentSecurityPolicy?: {
36 directives?: Record<string, string[]>;
37 reportOnly?: boolean;
38 };
39 crossOriginEmbedderPolicy?: boolean;
40 crossOriginOpenerPolicy?: boolean;
41 crossOriginResourcePolicy?: { policy: 'same-site' | 'same-origin' | 'cross-origin' };
42 dnsPrefetchControl?: boolean;
43 frameguard?: { action: 'deny' | 'sameorigin' };
44 hidePoweredBy?: boolean;
45 hsts?: {
46 maxAge?: number;
47 includeSubDomains?: boolean;
48 preload?: boolean;
49 };
50 ieNoOpen?: boolean;
51 noSniff?: boolean;
52 originAgentCluster?: boolean;
53 permittedCrossDomainPolicies?: boolean;
54 referrerPolicy?: string;
55 xssFilter?: boolean;
56}
57
58// Rate limit store interface
59interface RateLimitStore {
60 get(key: string): Promise<number | null>;
61 set(key: string, value: number, ttl: number): Promise<void>;
62 increment(key: string, ttl: number): Promise<number>;
63 reset(key: string): Promise<void>;
64}
Configuration Types
Configuration Interfaces
typescript
1// Server configuration
2interface ServerConfig {
3 port?: number;
4 host?: string;
5 environment?: 'development' | 'staging' | 'production';
6 gracefulShutdown?: {
7 timeout?: number;
8 signals?: string[];
9 };
10 keepAlive?: boolean;
11 bodyLimit?: string;
12}
13
14// Security configuration
15interface SecurityConfig {
16 cors?: CorsOptions;
17 helmet?: HelmetOptions;
18 rateLimit?: {
19 global?: RateLimitOptions;
20 api?: RateLimitOptions;
21 };
22 csrf?: {
23 enabled?: boolean;
24 secret?: string;
25 cookie?: CookieOptions;
26 };
27}
28
29// Database configuration
30interface DatabaseConfig {
31 default?: {
32 type?: 'postgresql' | 'mysql' | 'sqlite' | 'mongodb';
33 url?: string;
34 pool?: {
35 min?: number;
36 max?: number;
37 acquireTimeoutMillis?: number;
38 idleTimeoutMillis?: number;
39 createTimeoutMillis?: number;
40 };
41 migrations?: {
42 directory?: string;
43 autoRun?: boolean;
44 table?: string;
45 };
46 ssl?: boolean | {
47 rejectUnauthorized?: boolean;
48 ca?: string;
49 key?: string;
50 cert?: string;
51 };
52 };
53 cache?: {
54 type?: 'redis' | 'memory' | 'file';
55 url?: string;
56 ttl?: string;
57 prefix?: string;
58 maxSize?: number;
59 };
60}
61
62// Logging configuration
63interface LoggingConfig {
64 level?: 'debug' | 'info' | 'warn' | 'error';
65 format?: 'json' | 'pretty';
66 destinations?: Array<{
67 type: 'console' | 'file' | 'http';
68 path?: string;
69 url?: string;
70 level?: string;
71 }>;
72 requestLogging?: {
73 enabled?: boolean;
74 skipHealthChecks?: boolean;
75 skipPaths?: string[];
76 format?: string;
77 };
78}
79
80// Features configuration
81interface FeaturesConfig {
82 websockets?: boolean | {
83 enabled?: boolean;
84 path?: string;
85 cors?: CorsOptions;
86 };
87 fileUploads?: {
88 enabled?: boolean;
89 maxSize?: string;
90 allowedTypes?: string[];
91 destination?: string;
92 };
93 apiDocs?: {
94 enabled?: boolean;
95 path?: string;
96 title?: string;
97 version?: string;
98 description?: string;
99 };
100 clustering?: {
101 enabled?: boolean;
102 workers?: number;
103 };
104}
105
106// Environment schema
107interface EnvSchema {
108 [key: string]: {
109 required?: boolean;
110 type?: 'string' | 'number' | 'boolean';
111 default?: any;
112 enum?: string[];
113 minLength?: number;
114 maxLength?: number;
115 min?: number;
116 max?: number;
117 };
118}
Utility Types
Helper Types and Utilities
typescript
1// Generic utility types
2type Optional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
3type Required<T, K extends keyof T> = T & Required<Pick<T, K>>;
4
5// Route parameter extraction
6type ExtractParams<T extends string> = T extends `${infer Start}:${infer Param}/${infer Rest}`
7 ? { [K in Param]: string } & ExtractParams<Rest>
8 : T extends `${infer Start}:${infer Param}`
9 ? { [K in Param]: string }
10 : {};
11
12// Type-safe route handler with parameter inference
13type TypedRouteHandler<TPath extends string, TBody = any, TResponse = any> = (
14 context: RequestContext & {
15 params: ExtractParams<TPath>;
16 body: TBody;
17 }
18) => TResponse | Promise<TResponse>;
19
20// WebSocket types
21interface WebSocketConnection {
22 id: string;
23 send(data: any): void;
24 close(code?: number, reason?: string): void;
25 ping(data?: Buffer): void;
26 pong(data?: Buffer): void;
27 on(event: 'message' | 'close' | 'error' | 'ping' | 'pong', handler: Function): void;
28 off(event: string, handler: Function): void;
29}
30
31interface WebSocketManager {
32 connections: Map<string, WebSocketConnection>;
33 broadcast(data: any, filter?: (connection: WebSocketConnection) => boolean): void;
34 getConnection(id: string): WebSocketConnection | undefined;
35 closeConnection(id: string): void;
36 closeAll(): void;
37}
38
39// Event system types
40interface EventBus {
41 emit(event: string, data?: any): void;
42 on(event: string, handler: (data: any) => void): void;
43 off(event: string, handler: (data: any) => void): void;
44 once(event: string, handler: (data: any) => void): void;
45 removeAllListeners(event?: string): void;
46}
47
48// Cache types
49interface CacheStore {
50 get<T = any>(key: string): Promise<T | null>;
51 set<T = any>(key: string, value: T, options?: { ttl?: string | number }): Promise<void>;
52 delete(key: string): Promise<boolean>;
53 clear(): Promise<void>;
54 has(key: string): Promise<boolean>;
55 keys(pattern?: string): Promise<string[]>;
56}
57
58// Logger types
59interface Logger {
60 debug(message: string, meta?: any): void;
61 info(message: string, meta?: any): void;
62 warn(message: string, meta?: any): void;
63 error(message: string, meta?: any): void;
64 child(meta: any): Logger;
65}
Type Safety Benefits
MoroJS provides comprehensive TypeScript support:
- • Full IntelliSense and autocomplete support
- • Compile-time type checking for routes and handlers
- • Automatic parameter type inference from route paths
- • Schema-based request/response validation
- • Type-safe configuration and environment variables