### Quick Start: Setting up OneBun Application with Queue Handlers Source: https://github.com/remryahirev/onebun/blob/master/docs/api/queue.md Illustrates the basic structure of a OneBun application, including module and controller setup for discovering queue handlers and an example of publishing messages. ```typescript import { Module, Controller, BaseController, OneBunApplication, Subscribe, Cron, Interval, Message, CronExpression, OnQueueReady, QueueService, } from '@onebun/core'; // Controller with queue handlers (must be in controllers array) @Controller('/events') class EventProcessor extends BaseController { constructor(private queueService: QueueService) { super(); } @OnQueueReady() onReady() { this.logger.info('Queue connected and ready'); } // Subscribe to messages @Subscribe('orders.created') async handleOrderCreated(message: Message<{ orderId: number }>) { this.logger.info('New order:', { orderId: message.data.orderId }); } // Scheduled job: every hour @Cron(CronExpression.EVERY_HOUR, { pattern: 'cleanup.expired' }) getCleanupData() { return { timestamp: Date.now() }; } // Interval job: every 30 seconds @Interval(30000, { pattern: 'metrics.collect' }) getMetricsData() { return { cpu: process.cpuUsage() }; } // Publish messages programmatically async createOrder(data: { userId: string }) { await this.queueService.publish('orders.created', { orderId: Date.now(), userId: data.userId, }); } } // Module: register in controllers so queue handlers are discovered @Module({ controllers: [EventProcessor], }) class AppModule {} // Application const app = new OneBunApplication(AppModule, { port: 3000 }); await app.start(); ``` -------------------------------- ### Running the Application Source: https://github.com/remryahirev/onebun/blob/master/docs/examples/basic-app.md Commands to install dependencies and start the OneBun application in development or production mode. ```bash # Install dependencies bun install # Start in development mode bun run dev # Or start once bun run start ``` -------------------------------- ### Basic Controller Setup with Documentation Decorators Source: https://github.com/remryahirev/onebun/blob/master/packages/docs/README.md Demonstrates using @ApiTags and @ApiOperation from @onebun/docs along with @Controller, @Get, @Post, and @ApiResponse from @onebun/core to document API endpoints. ```typescript import { Controller, Get, Post, Body, BaseController, ApiResponse, type } from '@onebun/core'; import { ApiTags, ApiOperation } from '@onebun/docs'; const createUserSchema = type({ name: 'string', email: 'string.email', }); // @ApiTags ABOVE @Controller @ApiTags('Users') @Controller('/users') export class UserController extends BaseController { // @ApiOperation ABOVE @Get, @ApiResponse BELOW @Get @ApiOperation({ summary: 'Get all users', description: 'Returns a list of all users' }) @Get('/') @ApiResponse(200, { description: 'List of users returned successfully' }) async getUsers(): Promise { return this.success({ users: [] }); } @ApiOperation({ summary: 'Create user', description: 'Creates a new user' }) @Post('/') @ApiResponse(201, { schema: createUserSchema, description: 'User created successfully' }) @ApiResponse(400, { description: 'Invalid input data' }) async createUser(@Body(createUserSchema) userData: typeof createUserSchema.infer): Promise { return this.success({ id: '1', ...userData }); } } ``` -------------------------------- ### Bootstrap OneBun Application Source: https://github.com/remryahirev/onebun/blob/master/docs/api/core.md Example of how to instantiate and start a OneBun application with configuration, including accessing typed configuration values and logging. ```typescript import { OneBunApplication } from '@onebun/core'; import { AppModule } from './app.module'; import { envSchema } from './config'; const app = new OneBunApplication(AppModule, { basePath: '/api/v1', envSchema, metrics: { enabled: true, path: '/metrics', prefix: 'myapp_', }, tracing: { enabled: true, serviceName: 'my-service', samplingRate: 1.0, }, }); app .start() .then(() => { // Access configuration - fully typed with module augmentation const port = app.getConfigValue('server.port'); // number (auto-inferred) const config = app.getConfig(); const host = config.get('server.host'); // string (auto-inferred) const logger = app.getLogger({ className: 'AppBootstrap' }); logger.info('Application started', { port, host }); }) .catch((error: unknown) => { const logger = app.getLogger({ className: 'AppBootstrap' }); logger.error('Failed to start:', error instanceof Error ? error : new Error(String(error))); }); // Application will automatically handle shutdown signals (SIGTERM, SIGINT) ``` -------------------------------- ### Quick Setup with Security Middleware Source: https://github.com/remryahirev/onebun/blob/master/docs/api/security.md Initialize a OneBun application with CORS, rate limiting, and security headers enabled via ApplicationOptions. Ensure the application is started after configuration. ```typescript import { OneBunApplication } from '@onebun/core'; import { AppModule } from './app.module'; const app = new OneBunApplication(AppModule, { cors: { origin: 'https://my-frontend.example.com', credentials: true }, rateLimit: { windowMs: 60_000, max: 100 }, security: true, // use all defaults }); await app.start(); ``` -------------------------------- ### OneBun Application Usage Example Source: https://github.com/remryahirev/onebun/blob/master/docs/api/core.md Demonstrates how to initialize and start a OneBun application with multiple services, including configuration for ports, route prefixes, environment overrides, metrics, and tracing. Shows how to access service URLs and child applications. ```typescript import { OneBunApplication } from '@onebun/core'; import { UsersModule } from './users/users.module'; import { OrdersModule } from './orders/orders.module'; import { envSchema } from './config'; const app = new OneBunApplication({ services: { users: { module: UsersModule, port: 3001, routePrefix: true, }, orders: { module: OrdersModule, port: 3002, routePrefix: true, envOverrides: { DB_NAME: { value: 'orders_db' }, }, }, }, envSchema, metrics: { enabled: true }, tracing: { enabled: true }, }); await app.start(); console.log('Running:', app.getRunningServices()); console.log('Users URL:', app.getServiceUrl('users')); // Access child application const usersApp = app.getApplication('users'); ``` -------------------------------- ### Quick Start: Basic OneBun Application Source: https://github.com/remryahirev/onebun/blob/master/packages/core/README.md Set up a minimal OneBun application with a controller and module, then start the server. ```typescript import { OneBunApplication, Controller, Get, Module } from '@onebun/core'; @Controller('/api') class AppController { @Get('/hello') async hello() { return { message: 'Hello, OneBun!' }; } } @Module({ controllers: [AppController], }) class AppModule {} const app = new OneBunApplication(AppModule); await app.start(); ``` -------------------------------- ### Logger Configuration via Environment Variables Source: https://github.com/remryahirev/onebun/blob/master/docs/api/logger.md Shows how to configure logger settings like log level and format using environment variables. This example demonstrates setting them for a `bun run start` command. ```bash # Example: Set log level to info and format to JSON LOG_LEVEL=info LOG_FORMAT=json bun run start ``` -------------------------------- ### Installation Source: https://github.com/remryahirev/onebun/blob/master/docs/api/docs.md Install the @onebun/docs package to automatically enable documentation generation. ```APIDOC ## Installation Install the `@onebun/docs` package to automatically enable documentation generation. ```bash bun add @onebun/docs ``` That's it. When `@onebun/docs` is installed, documentation is **automatically enabled** on application startup. No imports or configuration required in your application code. ``` -------------------------------- ### Install @onebun/trace Source: https://github.com/remryahirev/onebun/blob/master/packages/trace/README.md Install the tracing module using bun. ```bash bun add @onebun/trace ``` -------------------------------- ### OneBun Application Setup Source: https://github.com/remryahirev/onebun/blob/master/README.md This TypeScript example demonstrates setting up a basic OneBun application with a module, controller, service, and defining a request body schema using ArkType. It configures the application with port, Prometheus metrics, and OpenTelemetry tracing. ```typescript import { BaseController, Controller, Get, Module, OneBunApplication, Service, BaseService, Post, Body, type, } from '@onebun/core'; const CreateUser = type({ name: 'string', email: 'string.email' }); type CreateUserBody = typeof CreateUser.infer; @Service() class UserService extends BaseService { getAll() { return [{ id: 1, name: 'Alice' }]; } } @Controller('/users') class UserController extends BaseController { constructor(private users: UserService) { super(); } @Get('/') async list() { return this.users.getAll(); } @Post('/') async create(@Body(CreateUser) body: CreateUserBody) { return this.success(body, 201); // this.success() only when custom status needed } } @Module({ controllers: [UserController], providers: [UserService] }) class AppModule {} const app = new OneBunApplication(AppModule, { port: 3000, metrics: { enabled: true }, // Prometheus at /metrics tracing: { enabled: true }, // OpenTelemetry spans }); await app.start(); ``` -------------------------------- ### AppGateway Example Source: https://github.com/remryahirev/onebun/blob/master/docs/api/websocket.md A minimal example demonstrating how to set up a WebSocket Gateway with connection and message handling. ```APIDOC ## AppGateway Example ### Description A minimal example demonstrating how to set up a WebSocket Gateway with connection and message handling. ### Gateway Setup ```typescript import { WebSocketGateway, BaseWebSocketGateway, OnConnect, OnMessage, Client, MessageData } from '@onebun/core'; import type { WsClientData } from '@onebun/core'; @WebSocketGateway({ path: '/ws' }) export class AppGateway extends BaseWebSocketGateway { @OnConnect() handleConnect(@Client() client: WsClientData) { return { event: 'welcome', data: { id: client.id } }; } @OnMessage('ping') handlePing() { return { event: 'pong', data: {} }; } } ``` ### Module Registration ```typescript import { Module } from '@onebun/core'; import { AppGateway } from './gateway'; @Module({ controllers: [AppGateway], providers: [], }) export class AppModule {} ``` ### Application Initialization ```typescript import { OneBunApplication } from '@onebun/core'; import { AppModule } from './app.module'; const app = new OneBunApplication(AppModule, { port: 3000, websocket: { // Optional: storage, socketio, maxPayload }, }); await app.start(); // Native WebSocket: ws://localhost:3000/ws ``` ``` -------------------------------- ### Install @onebun/metrics Source: https://github.com/remryahirev/onebun/blob/master/packages/metrics/README.md Install the metrics module using bun. ```bash bun add @onebun/metrics ``` -------------------------------- ### UserController Example Source: https://github.com/remryahirev/onebun/blob/master/packages/docs/README.md Demonstrates how to use @onebun/docs decorators (@ApiTags, @ApiOperation) along with @onebun/core decorators (@Controller, @Get, @Post, @Body, @ApiResponse) to document API endpoints. ```APIDOC ## GET /users ### Description Retrieves a list of all users. ### Method GET ### Endpoint /users ### Parameters #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **users** (array) - List of users returned successfully #### Response Example ```json { "users": [] } ``` ``` ```APIDOC ## POST /users ### Description Creates a new user. ### Method POST ### Endpoint /users ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **name** (string) - Required - User's name - **email** (string) - Required - User's email address (must be a valid email format) ### Request Example ```json { "name": "John Doe", "email": "john.doe@example.com" } ``` ### Response #### Success Response (201) - **id** (string) - The unique identifier of the created user - **name** (string) - The name of the created user - **email** (string) - The email of the created user #### Response Example ```json { "id": "1", "name": "John Doe", "email": "john.doe@example.com" } ``` #### Error Response (400) - Description: Invalid input data ``` -------------------------------- ### Run CRUD API Example Source: https://github.com/remryahirev/onebun/blob/master/examples/README.md Navigate to the crud-api example directory and run the application using Bun. ```bash cd examples/crud-api bun run src/index.ts ``` -------------------------------- ### Install @onebun/logger Source: https://github.com/remryahirev/onebun/blob/master/packages/logger/README.md Install the logger package using bun. ```bash bun add @onebun/logger ``` -------------------------------- ### Install @onebun/requests Source: https://github.com/remryahirev/onebun/blob/master/packages/requests/README.md Install the package using Bun. ```bash bun add @onebun/requests ``` -------------------------------- ### User Controller Example Source: https://github.com/remryahirev/onebun/blob/master/docs/api/controllers.md Demonstrates extending BaseController to define routes for user management using decorators like @Controller, @Get, @Post, and @Param. ```typescript import { Controller, BaseController, Get, Post, Body, Param, HttpException } from '@onebun/core'; import { UserService } from './user.service'; @Controller('/users') export class UserController extends BaseController { constructor(private userService: UserService) { super(); // Always call super() } @Get('/') async findAll() { return this.userService.findAll(); // → { success: true, result: [...] } } @Get('/:id') async findOne(@Param('id') id: string) { const user = await this.userService.findById(id); if (!user) throw new HttpException(404, 'User not found'); return user; // → { success: true, result: { ... } } } @Post('/') async create(@Body() body: unknown) { const user = await this.userService.create(body); return user; // → { success: true, result: { ... } } } } ``` -------------------------------- ### Install @onebun/docs Source: https://github.com/remryahirev/onebun/blob/master/docs/api/docs.md Install the @onebun/docs package using bun. This package automatically enables documentation features upon installation. ```bash bun add @onebun/docs ``` -------------------------------- ### Install @onebun/cache Source: https://github.com/remryahirev/onebun/blob/master/packages/cache/README.md Install the cache module using bun. Ensure you have Bun v1.2.9+ and @onebun/envs installed. ```bash bun add @onebun/cache # Dependencies: # - @onebun/envs (for configuration management) # - Bun v1.2.9+ (for native RedisClient support) ``` -------------------------------- ### Start Development Server Source: https://github.com/remryahirev/onebun/blob/master/CONTRIBUTING.md Start the development server with watch mode enabled for automatic reloads. ```bash bun run dev ``` -------------------------------- ### Install Dependencies Source: https://github.com/remryahirev/onebun/blob/master/examples/README.md Install project dependencies from the repository root using Bun. ```bash bun install ``` -------------------------------- ### Install @onebun/nats Source: https://github.com/remryahirev/onebun/blob/master/packages/nats/README.md Install the NATS integration package using bun. ```bash bun add @onebun/nats ``` -------------------------------- ### Install @onebun/envs Package Source: https://github.com/remryahirev/onebun/blob/master/packages/envs/README.md Install the package using Bun package manager. ```bash bun add @onebun/envs ``` -------------------------------- ### Minimal Working Example Source: https://github.com/remryahirev/onebun/blob/master/docs/index.md A complete, runnable example demonstrating the structure of a OneBun application, including environment configuration, service and controller layers, module definition, and application entry point. ```typescript import { BaseController, BaseService, Controller, Env, Get, Module, OneBunApplication, Post, Body, Service, type InferConfigType, } from '@onebun/core'; // ============================================================================ // 1. Environment Schema (src/config.ts) // ============================================================================ const envSchema = { server: { port: Env.number({ default: 3000 }), host: Env.string({ default: '0.0.0.0' }), }, }; type AppConfig = InferConfigType; declare module '@onebun/core' { interface OneBunAppConfig extends AppConfig {} } // ============================================================================ // 2. Service Layer (src/counter.service.ts) // ============================================================================ @Service() class CounterService extends BaseService { private value = 0; getValue(): number { this.logger.debug('Getting counter value', { value: this.value }); return this.value; } increment(amount = 1): number { this.value += amount; return this.value; } } // ============================================================================ // 3. Controller Layer (src/counter.controller.ts) // ============================================================================ @Controller('/api/counter') class CounterController extends BaseController { constructor(private counterService: CounterService) { super(); } @Get('/') async getValue() { const value = this.counterService.getValue(); return { value }; } @Post('/increment') async increment(@Body() body?: { amount?: number }) { const newValue = this.counterService.increment(body?.amount); return { value: newValue }; } } // ============================================================================ // 4. Module Definition (src/app.module.ts) // ============================================================================ @Module({ controllers: [CounterController], providers: [CounterService], }) class AppModule {} // ============================================================================ // 5. Application Entry Point (src/index.ts) // ============================================================================ const app = new OneBunApplication(AppModule, { envSchema, metrics: { enabled: true }, tracing: { enabled: true }, }); app .start() .then(() => { const logger = app.getLogger({ className: 'AppBootstrap' }); logger.info('Application started'); }) .catch((error: unknown) => { const logger = app.getLogger({ className: 'AppBootstrap' }); logger.error('Failed to start:', error instanceof Error ? error : new Error(String(error))); }); ``` -------------------------------- ### Start WebSocket Server Source: https://github.com/remryahirev/onebun/blob/master/docs/examples/websocket-chat.md Command to start the WebSocket server using Bun. Ensure the server is running before connecting clients. ```bash bun run src/index.ts ``` -------------------------------- ### Install competitor dependencies for Simple HTTP Source: https://github.com/remryahirev/onebun/blob/master/benchmarks/README.md Installs dependencies for Hono, Elysia, and NestJS (Fastify adapter) for simple HTTP benchmarks using Bun. ```bash # Simple HTTP competitors cd benchmarks/simple/competitors/hono-bun && bun install cd ../elysia && bun install cd ../nestjs-fastify && bun install && bun run build ``` -------------------------------- ### Install @onebun/drizzle Source: https://github.com/remryahirev/onebun/blob/master/packages/drizzle/README.md Install the Drizzle ORM module and its dependencies using Bun. ```bash bun add @onebun/drizzle drizzle-orm drizzle-kit ``` -------------------------------- ### Install Dependencies with Bun Source: https://github.com/remryahirev/onebun/blob/master/CONTRIBUTING.md Install project dependencies using the Bun package manager. ```bash bun install ``` -------------------------------- ### EventProcessor Controller Example Source: https://github.com/remryahirev/onebun/blob/master/docs/api/queue.md An example controller demonstrating how to set up queue handlers (@Subscribe, @OnQueueReady), scheduled jobs (@Cron, @Interval), and programmatic message publishing using QueueService. ```APIDOC ## EventProcessor Controller Example ### Description This controller shows how to define various queue-related functionalities within a OneBun application. It includes handlers for incoming messages, scheduled tasks, and the ability to publish messages to the queue. ### Controller ```typescript @Controller('/events') class EventProcessor extends BaseController { constructor(private queueService: QueueService) { super(); } @OnQueueReady() onReady() { this.logger.info('Queue connected and ready'); } @Subscribe('orders.created') async handleOrderCreated(message: Message<{ orderId: number }>) { this.logger.info('New order:', { orderId: message.data.orderId }); } @Cron(CronExpression.EVERY_HOUR, { pattern: 'cleanup.expired' }) getCleanupData() { return { timestamp: Date.now() }; } @Interval(30000, { pattern: 'metrics.collect' }) getMetricsData() { return { cpu: process.cpuUsage() }; } async createOrder(data: { userId: string }) { await this.queueService.publish('orders.created', { orderId: Date.now(), userId: data.userId, }); } } ``` ### Module Registration Queue handlers are discovered when controllers are registered in a module's `controllers` array. ```typescript @Module({ controllers: [EventProcessor], }) class AppModule {} ``` ``` -------------------------------- ### System Metrics Output Example Source: https://github.com/remryahirev/onebun/blob/master/docs/api/metrics.md Example of Prometheus-formatted output for system and process metrics. ```text # Process CPU process_cpu_seconds_total process_cpu_user_seconds_total process_cpu_system_seconds_total # Memory process_memory_bytes{type="rss"} process_memory_bytes{type="heapTotal"} process_memory_bytes{type="heapUsed"} process_memory_bytes{type="external"} # Event loop lag nodejs_eventloop_lag_seconds # Active handles and requests nodejs_active_handles_total nodejs_active_requests_total ``` -------------------------------- ### Application Initialization and Start Source: https://github.com/remryahirev/onebun/blob/master/docs/api/docs.md Initializes and starts the OneBun application with the defined UserModule and configuration. It specifies the port and documentation settings. ```typescript // ---- Application ---- import { OneBunApplication } from '@onebun/core'; const app = new OneBunApplication(UserModule, { port: 3000, docs: { title: 'User Management API', version: '1.0.0', description: 'API for managing users', }, }); await app.start(); // Swagger UI: http://localhost:3000/docs // OpenAPI JSON: http://localhost:3000/openapi.json // API endpoint: http://localhost:3000/api/users ``` -------------------------------- ### Install Dependencies and Run Benchmarks Source: https://github.com/remryahirev/onebun/blob/master/BENCHMARKS.md Installs project dependencies and runs various benchmark suites. Requires bombardier and Docker for PostgreSQL benchmarks. ```bash # Install dependencies bun install cd benchmarks/simple/competitors/hono-bun && bun install cd ../elysia && bun install cd ../nestjs-fastify && bun install && bun run build cd ../../../../realistic/nestjs-fastify && bun install && bun run build cd ../nestjs-typeorm && bun install && bun run build cd ../../realistic-pg/nestjs-fastify && bun install && bun run build cd ../nestjs-typeorm && bun install && bun run build # Run all benchmarks (requires bombardier; Docker for PostgreSQL) ./benchmarks/run-all.sh # Or individual suites ./benchmarks/simple/run.sh ./benchmarks/realistic/run.sh ./benchmarks/realistic-pg/run.sh # requires Docker ./benchmarks/startup.sh # Parse results into JSON bun run benchmarks/parse-results.ts ``` -------------------------------- ### Install competitor dependencies for Realistic SQLite Source: https://github.com/remryahirev/onebun/blob/master/benchmarks/README.md Installs dependencies for NestJS (Fastify adapter) for realistic SQLite benchmarks using Bun. ```bash # Realistic SQLite competitors cd benchmarks/realistic/nestjs-fastify && bun install && bun run build cd ../nestjs-typeorm && bun install && bun run build ``` -------------------------------- ### Install competitor dependencies for Realistic PostgreSQL Source: https://github.com/remryahirev/onebun/blob/master/benchmarks/README.md Installs dependencies for NestJS (Fastify adapter and TypeORM) for realistic PostgreSQL benchmarks using Bun. ```bash # Realistic PostgreSQL competitors cd benchmarks/realistic-pg/nestjs-fastify && bun install && bun run build cd ../nestjs-typeorm && bun install && bun run build ``` -------------------------------- ### Run the Application Source: https://github.com/remryahirev/onebun/blob/master/docs/getting-started.md Commands to start the application in development mode with hot reload or to start it once. These scripts are defined in the package.json file. ```bash # Start in development mode with hot reload bun run dev # Or start once bun run dev:once ``` -------------------------------- ### Development and Production Deployment Examples Source: https://github.com/remryahirev/onebun/blob/master/docs/examples/multi-service.md Demonstrates how to run services in development (all in one process) and production (specific services using environment variables). ```bash # Development: run all services in one process bun run src/index.ts ``` ```bash # Production: run only users service ONEBUN_SERVICES=users bun run src/index.ts ``` ```bash # Production: run only orders service ONEBUN_SERVICES=orders bun run src/index.ts ``` ```bash # Run all except orders ONEBUN_EXCLUDE_SERVICES=orders bun run src/index.ts ``` ```bash # Multiple services ONEBUN_SERVICES=users,orders bun run src/index.ts ``` -------------------------------- ### Expected GET /api/hello/World Response Source: https://github.com/remryahirev/onebun/blob/master/docs/getting-started.md Example JSON response for a GET request to the /api/hello/World endpoint. ```json { "success": true, "result": { "greeting": "Hello, World! You are visitor #1" } } ``` -------------------------------- ### Expected GET /api/hello Response Source: https://github.com/remryahirev/onebun/blob/master/docs/getting-started.md Example JSON response for a GET request to the /api/hello endpoint. ```json { "success": true, "result": { "message": "Hello from OneBun!" } } ``` -------------------------------- ### Manual OneBun Project Setup Source: https://github.com/remryahirev/onebun/blob/master/docs/getting-started.md Manually set up a new OneBun project by initializing a directory and adding the core package. ```bash mkdir my-onebun-app cd my-onebun-app bun init -y bun add @onebun/core ``` -------------------------------- ### Get Root Response Source: https://github.com/remryahirev/onebun/blob/master/docs/examples/basic-app.md Example of a basic API call to the root endpoint. ```curl curl http://localhost:3000/ ``` -------------------------------- ### Example .env File Format Source: https://github.com/remryahirev/onebun/blob/master/docs/api/envs.md Illustrates the standard format for `.env` files, showing how to define various configuration variables including database credentials, Redis settings, and feature flags. ```bash # .env file PORT=3000 HOST=0.0.0.0 # Database DATABASE_URL=postgres://user:pass@localhost:5432/mydb DB_MAX_CONNECTIONS=20 DB_SSL=true # Redis REDIS_HOST=localhost REDIS_PORT=6379 REDIS_PASSWORD=secret123 # Features ALLOWED_ORIGINS=http://localhost:3000,https://example.com # App APP_NAME=my-awesome-app DEBUG=false ``` -------------------------------- ### Module Definition Example Source: https://github.com/remryahirev/onebun/blob/master/docs/api/decorators.md An example demonstrating how to import modules, register controllers and services, and export services from a module. This is a standard way to structure application components. ```typescript import { Module } from '@onebun/core'; import { CacheModule } from '@onebun/cache'; import { UserController } from './user.controller'; import { UserService } from './user.service'; @Module({ imports: [CacheModule], controllers: [UserController], providers: [UserService], exports: [UserService], }) export class UserModule {} ``` -------------------------------- ### Example: Creating a Profile with File and Form Fields Source: https://github.com/remryahirev/onebun/blob/master/docs/api/decorators.md This example combines uploading a file with @UploadedFile and extracting form fields like 'name' and 'email' using @FormField. ```typescript @Post('/profile') async createProfile( @UploadedFile('avatar', { mimeTypes: [MimeType.ANY_IMAGE] }) avatar: OneBunFile, @FormField('name', { required: true }) name: string, @FormField('email') email: string, ) { await avatar.writeTo(`./uploads/${avatar.name}`); return { name, email, avatar: avatar.name }; } ``` -------------------------------- ### CacheInterceptor Setup Source: https://github.com/remryahirev/onebun/blob/master/docs/api/interceptors.md Integrate the CacheInterceptor for HTTP GET responses. Requires importing CacheModule and CacheService for dependency injection. ```typescript import { CacheInterceptor } from '@onebun/cache'; import { CacheModule } from '@onebun/cache'; @Module({ imports: [CacheModule], controllers: [DataController], }) class DataModule {} @UseInterceptors(CacheInterceptor) @Controller('/api/data') class DataController extends BaseController { @Get('/') getData() { return { items: [1, 2, 3] }; } } ``` -------------------------------- ### Create Entry Point Source: https://github.com/remryahirev/onebun/blob/master/docs/getting-started.md Sets up the OneBun application instance with the root module, configuration options, and metrics/tracing. Includes error handling for application startup. ```typescript import { OneBunApplication } from '@onebun/core'; import { AppModule } from './app.module'; import { envSchema } from './config'; const app = new OneBunApplication(AppModule, { // port and host can be omitted - they'll use PORT/HOST env vars or defaults (3000/'0.0.0.0') // port: 3000, // host: '0.0.0.0', development: true, envSchema, envOptions: { loadDotEnv: true, }, metrics: { enabled: true, path: '/metrics', collectHttpMetrics: true, collectSystemMetrics: true, }, tracing: { enabled: true, serviceName: 'my-onebun-app', traceHttpRequests: true, }, }); app .start() .then(() => { const logger = app.getLogger({ className: 'AppBootstrap' }); logger.info('Application started successfully'); }) .catch((error: unknown) => { const logger = app.getLogger({ className: 'AppBootstrap' }); logger.error( 'Failed to start application:', error instanceof Error ? error : new Error(String(error)), ); process.exit(1); }); ``` -------------------------------- ### Starting a OneBun Application Source: https://github.com/remryahirev/onebun/blob/master/packages/core/README.md Creates and starts a OneBun application with specified port, host, and development mode. The application automatically handles logging and internal Effect.js calls. ```typescript import { OneBunApplication } from '@onebun/core'; import { AppModule } from './app.module'; const app = new OneBunApplication(AppModule, { port: 3000, host: '0.0.0.0', development: true }); // Start the application (no Effect.js calls needed) app.start() .then(() => console.log('Application started')) .catch(error => console.error('Failed to start application:', error)); ``` -------------------------------- ### HTTP Endpoint Decorator Example Source: https://github.com/remryahirev/onebun/blob/master/docs/index.md Defines an HTTP endpoint for a controller method. Supports various HTTP methods like GET, POST, etc. ```typescript @Get('/:id') ``` -------------------------------- ### Programmatic SSE Endpoint Creation Source: https://github.com/remryahirev/onebun/blob/master/docs/api/controllers.md Demonstrates creating an SSE endpoint programmatically using the `sse()` method instead of the `@Sse()` decorator. This example yields 'start', 'progress', and 'complete' events. ```typescript @Controller('/events') export class EventsController extends BaseController { /** * Using sse() method instead of @Sse() decorator */ @Get('/manual') events(): Response { return this.sse(async function* () { yield { event: 'start', data: { timestamp: Date.now() } }; for (let i = 0; i < 5; i++) { await Bun.sleep(1000); yield { event: 'progress', data: { percent: (i + 1) * 20 } }; } yield { event: 'complete', data: { success: true } }; }()); } ``` -------------------------------- ### Configure Static Files Under a Path Prefix Source: https://github.com/remryahirev/onebun/blob/master/docs/api/core.md Example of configuring static file serving to be accessible only under a specific URL path prefix. Files in './public' will be served when requests start with '/assets'. ```typescript const app = new OneBunApplication(AppModule, { static: { root: './public', pathPrefix: '/assets', }, }); // Only GET /assets/* are served from ./public; e.g. /assets/logo.png -> public/logo.png ``` -------------------------------- ### Effect.js Integration with LoggerService Source: https://github.com/remryahirev/onebun/blob/master/packages/logger/README.md Shows how to integrate the LoggerService from @onebun/logger with Effect.js for managing logging within Effectful programs. This example demonstrates starting operations, handling successful completion, and catching/logging errors. ```typescript import { Effect, pipe } from 'effect'; import { LoggerService } from '@onebun/logger'; const program = pipe( LoggerService, Effect.flatMap((logger) => pipe( logger.info('Starting operation'), Effect.flatMap(() => performOperation()), Effect.tap(() => logger.info('Operation completed')), Effect.catchAll((error) => pipe( logger.error('Operation failed', error), Effect.flatMap(() => Effect.fail(error)) ) ) ) ) ); ``` -------------------------------- ### Minimal App Bootstrap Source: https://github.com/remryahirev/onebun/blob/master/docs/api/core.md Demonstrates the minimal setup required to bootstrap a OneBun application using the OneBunApplication class. ```APIDOC ## Minimal App Bootstrap ### Description This example shows the most basic way to initialize and start a OneBun application. ### Method `new OneBunApplication(moduleClass, options).start()` ### Parameters #### Constructor Parameters - `moduleClass` (*new (...args: unknown[]) => object*) - The main application module class. - `options` (*Partial*) - Optional configuration for the application. #### `start()` Method Parameters None ### Request Example ```typescript import { OneBunApplication } from '@onebun/core'; import { AppModule } from './app.module'; import { envSchema } from './config'; const app = new OneBunApplication(AppModule, { envSchema }); app .start() .then(() => { const logger = app.getLogger({ className: 'AppBootstrap' }); logger.info('Application started'); }) .catch((error: unknown) => { const logger = app.getLogger({ className: 'AppBootstrap' }); logger.error('Failed to start:', error instanceof Error ? error : new Error(String(error))); }); ``` ### Response #### Success Response The `start()` method returns a Promise that resolves when the HTTP server has successfully started. #### Response Example (Promise resolves with no specific value on success) ``` -------------------------------- ### Configure OneBun Application for WebSocket Chat Source: https://github.com/remryahirev/onebun/blob/master/docs/examples/websocket-chat.md This snippet shows the server-side setup for a OneBun application, enabling WebSocket support and starting the server. It includes importing necessary modules and configuring the WebSocket options. ```typescript // src/index.ts import { OneBunApplication } from '@onebun/core'; import { ChatModule } from './chat.module'; import { envSchema } from './config'; const app = new OneBunApplication(ChatModule, { envSchema, websocket: {}, }); await app.start(); const logger = app.getLogger(); logger.info(`Chat server running on ${app.getHttpUrl()}`); logger.info(`Native WebSocket: ws://localhost:${app.getPort()}/chat`); ``` -------------------------------- ### Initialize and Start OneBun Application Source: https://github.com/remryahirev/onebun/blob/master/docs/api/envs.md This snippet shows how to initialize the OneBun application with the defined environment schema and options, then start the application and log its startup information, including configuration details. ```typescript // index.ts import { OneBunApplication } from '@onebun/core'; import { AppModule } from './app.module'; import { envSchema } from './config'; const app = new OneBunApplication(AppModule, { envSchema, envOptions: { envFilePath: '.env', strict: process.env.NODE_ENV === 'production', }, }); app.start().then(() => { const logger = app.getLogger(); const config = app.getConfig(); logger.info('Application started', { port: config.get('server.port'), config: config.getSafeConfig(), // Sensitive values masked }); }); ``` -------------------------------- ### SSE Endpoint using sse() Method Source: https://github.com/remryahirev/onebun/blob/master/docs/api/controllers.md Demonstrates creating an SSE response programmatically using the `sse()` method within a controller. This example shows how to yield events for start, progress, and completion stages of a task. ```APIDOC ## GET /events/manual ### Description Manually creates a Server-Sent Events stream using the `sse()` method. This endpoint yields events indicating the start, progress (in 20% increments), and completion of a process. ### Method GET ### Endpoint /events/manual ### Parameters None ### Request Example None ### Response #### Success Response (200) - **event** (string) - The type of the SSE event (e.g., 'start', 'progress', 'complete'). - **data** (object) - The payload of the SSE event, containing relevant information like timestamp, percent, or success status. #### Response Example ``` event: start data: {"timestamp":1678886400000} ``` ``` event: progress data: {"percent":20} ``` ``` event: complete data: {"success":true} ``` ``` -------------------------------- ### Route Decorators for Controllers Source: https://github.com/remryahirev/onebun/blob/master/packages/core/README.md Define various HTTP routes (GET, POST, PUT, DELETE, etc.) within a controller using decorators. This example shows how to define handlers for different HTTP methods and parameter types. ```typescript import { Controller, Get, Post, Put, Delete, Patch, Options, Head, All } from '@onebun/core'; @Controller('/users') export class UsersController { @Get() getAllUsers() { // Handle GET /users } @Get('/:id') getUserById(@Param('id') id: string) { // Handle GET /users/:id } @Post() createUser(@Body() userData: any) { // Handle POST /users } @Put('/:id') updateUser(@Param('id') id: string, @Body() userData: any) { // Handle PUT /users/:id } @Delete('/:id') deleteUser(@Param('id') id: string) { // Handle DELETE /users/:id } } ``` -------------------------------- ### NestJS vs OneBun HTTP Testing Source: https://github.com/remryahirev/onebun/blob/master/docs/migration-nestjs.md Compares the setup for creating a testing module and making HTTP requests in NestJS using `Test.createTestingModule` and `supertest`, versus OneBun's `TestingModule.create` which starts a real HTTP server. ```typescript // NestJS const module = await Test.createTestingModule({ controllers: [UserController], providers: [UserService], }).compile(); const app = module.createNestApplication(); await app.init(); const response = await request(app.getHttpServer()).get('/users'); ``` ```typescript // OneBun const module = await TestingModule .create({ controllers: [UserController], providers: [UserService] }) .overrideProvider(UserService).useValue(mockService) .compile(); // starts real server on random port const response = await module.inject('GET', '/users'); await module.close(); // always close in afterEach ``` -------------------------------- ### Basic Setup with CacheModule Source: https://github.com/remryahirev/onebun/blob/master/docs/api/cache.md Demonstrates how to import CacheModule in the root module for global availability of CacheService. It shows configuration for in-memory cache with a default TTL. ```APIDOC ## Basic Setup with CacheModule ### Description This example shows how to set up the `CacheModule` in your root application module. When imported globally, the `CacheService` becomes available throughout your application without needing to import it in every submodule. ### Method `CacheModule.forRoot(options)` ### Parameters #### Request Body - **options** (object) - Required - Configuration options for the cache module. - **type** (CacheType) - Required - Specifies the cache type, either `CacheType.MEMORY` or `CacheType.REDIS`. - **cacheOptions** (object) - Optional - Options specific to the cache implementation. - **defaultTtl** (number) - Optional - Default time-to-live for cache entries in milliseconds. Defaults to 0 (no expiry). ### Request Example ```typescript import { Module } from '@onebun/core'; import { CacheModule, CacheType } from '@onebun/cache'; @Module({ imports: [ CacheModule.forRoot({ type: CacheType.MEMORY, cacheOptions: { defaultTtl: 300000, }, }), ], // ... other module configurations }) export class AppModule {} ``` ### Response `CacheService` is registered and available for injection in controllers and providers. ``` -------------------------------- ### Testing Users Service Endpoints Source: https://github.com/remryahirev/onebun/blob/master/docs/examples/multi-service.md Provides example `curl` commands to test the Users service endpoints. These commands demonstrate how to retrieve users, get a specific user by ID, and create a new user. Ensure the Users service is running on port 3001. ```bash # Users Service (port 3001) curl http://localhost:3001/users/users curl http://localhost:3001/users/users/1 curl -X POST http://localhost:3001/users/users \ -H "Content-Type: application/json" \ -d '{"name": "Charlie", "email": "charlie@example.com"}' ``` -------------------------------- ### Create and Run a New OneBun App Source: https://github.com/remryahirev/onebun/blob/master/docs/getting-started.md Use the OneBun CLI to quickly scaffold a new project and start the development server. ```bash bun create @onebun my-onebun-app cd my-onebun-app bun run dev ``` -------------------------------- ### Basic Service Example Source: https://github.com/remryahirev/onebun/blob/master/docs/api/services.md Demonstrates how to create a simple service by extending BaseService and decorating it with @Service(). Services automatically receive logger and config. ```APIDOC ## Creating a Service: Basic Service ### Basic Service ```typescript import { Service, BaseService } from '@onebun/core'; @Service() export class CounterService extends BaseService { private count = 0; increment(): number { this.count++; this.logger.debug('Counter incremented', { count: this.count }); return this.count; } decrement(): number { this.count--; return this.count; } getValue(): number { return this.count; } } ``` ``` -------------------------------- ### Main Application Entry Point (src/index.ts) Source: https://github.com/remryahirev/onebun/blob/master/docs/examples/basic-app.md Initializes and starts the OneBun application, configuring port, host, environment loading, metrics, and tracing. ```typescript import { OneBunApplication } from '@onebun/core'; import { AppModule } from './app.module'; import { envSchema } from './config'; const app = new OneBunApplication(AppModule, { port: 3000, host: '0.0.0.0', development: true, envSchema, envOptions: { loadDotEnv: true, }, metrics: { enabled: true, path: '/metrics', }, tracing: { enabled: true, serviceName: 'basic-app', }, }); app.start() .then(() => { const logger = app.getLogger({ className: 'Bootstrap' }); logger.info('Basic app started successfully!'); logger.info(`Server: http://localhost:3000`); logger.info(`Metrics: http://localhost:3000/metrics`); }) .catch((error) => { console.error('Failed to start:', error); process.exit(1); }); ``` -------------------------------- ### Run Startup time benchmark Source: https://github.com/remryahirev/onebun/blob/master/benchmarks/README.md Measures the cold start time for different frameworks using custom bash timing and Bun HTTP polling. ```bash ./benchmarks/startup.sh ``` -------------------------------- ### Quick Start: Define and Load Configuration Source: https://github.com/remryahirev/onebun/blob/master/packages/envs/README.md Define a configuration schema with types, defaults, and validators, then load it asynchronously. Sensitive data is automatically masked in logs. ```typescript import { TypedEnv, Env } from '@onebun/envs'; // Define your configuration schema const schema = { app: { port: Env.number({ default: 3000, validate: Env.port() }), host: Env.string({ default: 'localhost' }), env: Env.string({ default: 'development', validate: Env.oneOf(['development', 'production', 'test']) }) }, database: { url: Env.string({ required: true, validate: Env.url() }), password: Env.string({ sensitive: true, required: true }) } }; // Create typed configuration const config = await TypedEnv.createAsync(schema); // Access values with full type safety const port = config.get('app.port'); // number const dbUrl = config.get('database.url'); // string // Get safe config for logging (sensitive data masked) console.log(config.getSafeConfig()); // Output: { app: { port: 3000, host: 'localhost', env: 'development' }, database: { url: 'postgres://...', password: '***' } } ``` -------------------------------- ### Complete User Controller Example Source: https://github.com/remryahirev/onebun/blob/master/docs/api/controllers.md Demonstrates a full controller implementation for managing users, including CRUD operations, parameter handling, middleware usage, and error handling. ```typescript import { Controller, BaseController, Get, Post, Put, Delete, Param, Body, Query, Header, UseMiddleware, HttpStatusCode, HttpException, } from '@onebun/core'; import { UserService } from './user.service'; import { AuthMiddleware } from './middleware/auth'; import { createUserSchema, type CreateUserBody, updateUserSchema, type UpdateUserBody, } from './user.schema'; @Controller('/api/users') export class UserController extends BaseController { constructor(private userService: UserService) { super(); } @Get('/') async findAll( @Query('page') page: string = '1', @Query('limit') limit: string = '10', ) { this.logger.info('Listing users', { page, limit }); const users = await this.userService.findAll({ page: parseInt(page, 10), limit: parseInt(limit, 10), }); return { users: users.items, total: users.total, page: users.page, limit: users.limit, }; } @Get('/search') async search( @Query('q') query: string, @Query('field') field: string = 'name', ) { if (!query) { throw new HttpException(HttpStatusCode.BAD_REQUEST, 'Query parameter "q" is required'); } return this.userService.search(query, field); } @Get('/:id') async findOne(@Param('id') id: string) { const user = await this.userService.findById(id); if (!user) throw new HttpException(HttpStatusCode.NOT_FOUND, 'User not found'); return user; } @Post('/') @UseMiddleware(AuthMiddleware) async create( @Body(createUserSchema) body: CreateUserBody, @Header('X-Request-ID') requestId?: string, ) { this.logger.info('Creating user', { email: body.email, requestId }); const user = await this.userService.create(body); return this.success(user, HttpStatusCode.CREATED); } @Put('/:id') @UseMiddleware(AuthMiddleware) async update( @Param('id') id: string, @Body(updateUserSchema) body: UpdateUserBody, ) { const user = await this.userService.update(id, body); if (!user) throw new HttpException(HttpStatusCode.NOT_FOUND, 'User not found'); return user; } @Delete('/:id') @UseMiddleware(AuthMiddleware) async remove(@Param('id') id: string) { const deleted = await this.userService.delete(id); if (!deleted) throw new HttpException(HttpStatusCode.NOT_FOUND, 'User not found'); return { deleted: true }; } } ```