### Start Documentation Site Source: https://github.com/carnojs/carno.js/blob/master/README.md Installs dependencies and starts the Docusaurus development server for the Carno.js documentation site. ```bash cd docs/carno npm install npm run start ``` -------------------------------- ### Quick Start: Basic Carno Application Source: https://github.com/carnojs/carno.js/blob/master/packages/core/README.md A minimal example demonstrating service and controller registration, dependency injection, and starting the server. ```typescript import { Carno, Controller, Get, Service, Param } from '@carno.js/core'; @Service() class GreetService { greet(name: string) { return `Hello, ${name}!`; } } @Controller('/greet') class GreetController { constructor(private greetService: GreetService) {} @Get('/:name') greet(@Param('name') name: string) { return { message: this.greetService.greet(name) }; } } const app = new Carno(); app.services([GreetService]); app.controllers([GreetController]); app.listen(3000); ``` -------------------------------- ### Quick Start: Basic WebSocket Chat Gateway Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/websocket/overview.md A minimal example demonstrating a chat gateway with connection, message subscription, and disconnection handling. ```typescript import { Carno } from '@carno.js/core'; import { WebSocketPlugin, Gateway, OnOpen, OnClose, SubscribeMessage, CarnoSocket, } from '@carno.js/websocket'; @Gateway('/chat') class ChatGateway { @OnOpen() onOpen(socket: CarnoSocket) { socket.join('general'); socket.emit('welcome', { id: socket.id }); } @SubscribeMessage('send') onSend(socket: CarnoSocket, payload: { message: string }) { socket.to('general').emit('message', { from: socket.id, text: payload.message, }); } @OnClose() onClose(socket: CarnoSocket, code: number, reason: string) { console.log(`${socket.id} disconnected (${code})`); } } const app = new Carno(); app.use(WebSocketPlugin.create([ChatGateway])); app.listen(3000); // Clients connect to: ws://localhost:3000/chat ``` -------------------------------- ### Install @carno.js/static Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/static/overview.md Install the static file serving plugin using Bun. ```bash bun add @carno.js/static ``` -------------------------------- ### Install Carno.js Core Source: https://github.com/carnojs/carno.js/blob/master/packages/core/README.md Install the core package using Bun. ```bash bun add @carno.js/core ``` -------------------------------- ### Install Valibot Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/core/validation.md Install Valibot using bun. This is a prerequisite for using the ValibotAdapter. ```bash bun add valibot ``` -------------------------------- ### Start Development Server Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/README.md Starts the Docusaurus development server for local previewing. ```bash npm run start ``` -------------------------------- ### PostConstruct Hook Example Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/core/lifecycle.md Shows how to use the PostConstruct decorator to perform setup operations on a service instance after its dependencies have been injected by the DI container. ```typescript import { PostConstruct, Service } from '@carno.js/core'; @Service() export class SearchIndex { @PostConstruct() prepare() { // local setup after dependencies exist } } ``` -------------------------------- ### Install @carno.js/websocket Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/websocket/overview.md Install the WebSocket plugin for Carno.js using Bun. ```bash bun install @carno.js/websocket ``` ```bash bun install "@carno.js/websocket" ``` -------------------------------- ### Install Carno.js Queue (Windows) Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/queue/overview.md Install the Carno.js Queue module using bun on Windows. ```bash bun install "@carno.js/queue" ``` -------------------------------- ### Install Carno CLI (Windows) Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/orm/migrations.md Install the Carno CLI as a development dependency on Windows using Bun. ```bash bun install -d "@carno.js/cli" ``` -------------------------------- ### Install Dependencies Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/README.md Installs the necessary project dependencies using npm. ```bash npm install ``` -------------------------------- ### Install OHA Benchmark Tool Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/benchmark.md Install the OHA HTTP load generator tool. This is a prerequisite for running local benchmarks. ```bash # macOS brew install oha # Cargo cargo install oha ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/carnojs/carno.js/blob/master/README.md Installs all necessary dependencies for the Carno.js project locally. ```bash bun install ``` -------------------------------- ### Create Simple Carno.js Server for Benchmarking Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/benchmark.md A basic Carno.js server setup for benchmarking purposes. It defines a single controller with a GET route that returns 'ok'. ```typescript // server.ts import { Carno, Controller, Get } from '@carno.js/core'; @Controller() class BenchmarkController { @Get('/') health() { return 'ok'; } } const app = new Carno({ providers: [BenchmarkController] }); app.listen(3000); ``` -------------------------------- ### Install Carno.js CLI with Bun Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/cli.md Install the Carno.js CLI as a development dependency using Bun. Recommended for Bun users. ```bash bun add -d @carno.js/cli ``` ```bash bun add -d "@carno.js/cli" ``` -------------------------------- ### Install Carno.js Core (Windows) Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/installation.md Install the core Carno.js package using Bun on Windows. Note the use of quotes around the package name. ```bash bun install "@carno.js/core" ``` -------------------------------- ### Install Carno CLI (macOS/Linux) Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/orm/migrations.md Install the Carno CLI as a development dependency on macOS or Linux using Bun. ```bash bun install -d @carno.js/cli ``` -------------------------------- ### Service Lifecycle Hook for Application Initialization Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/core/overview.md Implement the `OnApplicationInit` interface to define asynchronous methods that run once after the application has initialized but before it starts serving traffic. This is suitable for setup tasks like database connections. ```typescript import { OnApplicationInit, Service } from '@carno.js/core'; @Service() class DatabaseService { @OnApplicationInit() async connect() { // connect before serving traffic } } ``` -------------------------------- ### Install Carno.js Core (macOS/Linux) Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/installation.md Install the core Carno.js package using Bun on macOS or Linux. ```bash bun install @carno.js/core ``` -------------------------------- ### Initialize and Start Carno Application Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/core/overview.md Instantiate the Carno application, register services and controllers, and start the HTTP server on a specified port. ```typescript import { Carno } from '@carno.js/core'; import { UserController } from './user.controller'; import { UserService } from './user.service'; const app = new Carno() .services([UserService]) .controllers([UserController]); app.listen(3000); ``` -------------------------------- ### Install @carno.js/logger on Windows Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/core/logging.md Install the logger package using bun. This command is specifically for Windows environments. ```bash bun add "@carno.js/logger" ``` -------------------------------- ### Install @carno.js/logger Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/core/logging.md Install the logger package using bun. This command is for macOS and Linux environments. ```bash bun add @carno.js/logger ``` -------------------------------- ### Install Carno.js Scheduler on Windows Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/schedule/overview.md Install the Carno.js scheduler module using bun. This command is specifically for Windows systems. ```bash bun install "@carno.js/schedule" ``` -------------------------------- ### Install Carno.js CLI with npm Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/cli.md Install the Carno.js CLI as a development dependency using npm. Compatible with npm users. ```bash npm install -D @carno.js/cli ``` ```bash npm install -D "@carno.js/cli" ``` -------------------------------- ### Install Carno.js Core Package Source: https://github.com/carnojs/carno.js/blob/master/README.md Use this command to install the core package for Carno.js. On Windows, scoped package names may require quotes. ```bash bun install @carno.js/core ``` ```bash bun install "@carno.js/core" ``` -------------------------------- ### Relation Loading Example with refById and load Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/orm/ref.md This example demonstrates creating a `UserLibrary` with references using `refById` and then loading those relations in a subsequent query. It highlights using IDs for writes and `load` for reads when related data is needed. ```typescript const created = await UserLibrary.create({ user: refById(User, userId), course: refById(Course, courseId), }); const loaded = await UserLibrary.findOneOrFail( { id: created.id }, { load: ['user', 'course'] }, ); console.log(loaded.user.email); console.log(loaded.course.name); ``` -------------------------------- ### Install Carno.js ORM Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/orm/overview.md Install the Carno.js ORM package using Bun. This command is compatible with macOS, Linux, and Windows. ```bash bun install @carno.js/orm ``` ```bash bun install "@carno.js/orm" ``` -------------------------------- ### Register Controllers with Carno App Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/core/controllers.md Shows how to register controllers with the Carno application instance and start the server. ```typescript import { Carno } from '@carno.js/core'; const app = new Carno() .controllers([UserController]); app.listen(3000); ``` -------------------------------- ### Install Optional Modules (Windows) Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/installation.md Install additional Carno.js modules like ORM, Queue, and Schedule, along with the CLI as a dev dependency, on Windows. Note the use of quotes. ```bash bun install "@carno.js/orm" "@carno.js/queue" "@carno.js/schedule" bun install -d "@carno.js/cli" ``` -------------------------------- ### Defining a Controller Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/core/controllers.md Demonstrates how to define a controller with a base path and a GET route using decorators. ```APIDOC ## @Controller() ### Description Defines a class as a controller and optionally sets a base path for all its routes. ### Decorator `@Controller(path?: string)` ### Example ```typescript import { Controller, Get } from '@carno.js/core'; @Controller('/users') export class UserController { @Get() findAll() { return [{ id: 1, name: 'Alice' }]; } } ``` ``` -------------------------------- ### Repository Setup with Entity and Service Decorators Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/orm/derived-query-methods.md This code sets up a `User` entity and a `UserRepository` that extends `Repository`. This configuration enables the use of derived query methods. ```typescript import { Entity, PrimaryKey, Property, Repository } from '@carno.js/orm'; import { Service } from '@carno.js/core'; @Entity() export class User { @PrimaryKey() id: number; @Property() email: string; @Property() name: string; @Property() status: string; @Property() age: number; @Property() active: boolean; @Property() createdAt: Date; } @Service() export class UserRepository extends Repository { constructor() { super(User); } } ``` -------------------------------- ### Main Application Setup with WebSocketPlugin Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/websocket/overview.md Sets up the main Carno application, integrating the WebSocketPlugin with the ChatGateway and registering other services and controllers. It also specifies basic WebSocket plugin options. ```typescript // main.ts import { Carno } from '@carno.js/core'; import { WebSocketPlugin } from '@carno.js/websocket'; import { ChatGateway } from './chat.gateway'; import { NotificationsController } from './notifications.controller'; import { AuthService } from './auth.service'; const app = new Carno(); app.use(WebSocketPlugin.create([ChatGateway], { idleTimeout: 120, sendPings: true, })); app.services([AuthService]); app.controllers([NotificationsController]); app.listen(3000); // WS: ws://localhost:3000/chat // HTTP: POST http://localhost:3000/api/notifications/announce ``` -------------------------------- ### Basic Setup for Static Files Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/static/overview.md Register the StaticPlugin in your Carno.js application to serve files from a specified root directory under a given URL prefix. ```typescript import { Carno } from '@carno.js/core'; import { StaticPlugin } from '@carno.js/static'; const app = new Carno(); app.use(await StaticPlugin.create({ root: './public', prefix: '/assets' })); app.listen(3000); ``` -------------------------------- ### Install Optional Modules (macOS/Linux) Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/installation.md Install additional Carno.js modules like ORM, Queue, and Schedule, along with the CLI as a dev dependency, on macOS or Linux. ```bash bun install @carno.js/orm @carno.js/queue @carno.js/schedule bun install -d @carno.js/cli ``` -------------------------------- ### Create Basic Carno.js Application Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/installation.md A minimal example of a Carno.js application with a controller and a route. Ensure TypeScript configuration is set up correctly. ```typescript import { Carno, Controller, Get } from '@carno.js/core'; @Controller() class AppController { @Get() hello() { return 'Hello World'; } } const app = new Carno(); app.controllers([AppController]); await app.listen(3000); ``` -------------------------------- ### Setup Carno.js Application with Queue Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/queue/overview.md Register the CarnoQueue module in your Carno.js application, configuring the Redis connection. ```typescript import { Carno } from '@carno.js/core'; import { CarnoQueue } from '@carno.js/queue'; const app = new Carno() .use(CarnoQueue({ connection: { host: 'localhost', port: 6379 } })); await app.listen(3000); ``` -------------------------------- ### Configure Custom Seeder Directory Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/cli.md Example configuration in 'carno.config.ts' to specify a custom directory for seeders. ```typescript import { ConnectionSettings, BunPgDriver } from '@carno.js/orm'; const config: ConnectionSettings = { driver: BunPgDriver, migrationPath: './src/migrations', seederPath: './src/seeders', }; export default config; ``` -------------------------------- ### findPage Options Example Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/orm/pagination.md Illustrates advanced options available for `findPage()`, including `fields`, `load`, `loadStrategy`, and `cache`. Note that `limit` and `offset` are implicitly handled by `page` and `pageSize`. ```typescript await userRepository.findPage({ where: { role: 'admin' }, orderBy: { id: 'ASC' }, fields: ['id', 'email'], load: ['profile'], loadStrategy: 'select', cache: 30_000, page: 1, pageSize: 50, }); ``` -------------------------------- ### PreDestroy Hook Example Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/core/lifecycle.md Demonstrates the use of the PreDestroy decorator for performing cleanup tasks on singleton service instances during container destruction. ```typescript import { PreDestroy, Service } from '@carno.js/core'; @Service() export class MetricsBuffer { @PreDestroy() async flush() { // flush pending metrics } } ``` -------------------------------- ### Service Method with Pagination Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/orm/pagination.md Provides an example of a service method that utilizes `findPage` to list active users with pagination. It demonstrates how to pass the `page` number and set a `pageSize`. ```typescript async listActiveUsers(page = 1): Promise> { return this.userRepository.findPage({ where: { status: 'active' }, orderBy: { createdAt: 'DESC' }, page, pageSize: 50, }); } ``` -------------------------------- ### Configure Carno ORM Plugin Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/orm/overview.md Register the CarnoOrm plugin with the Carno application. This setup is typically done during application initialization. ```typescript import { Carno } from '@carno.js/core'; import { CarnoOrm } from '@carno.js/orm'; const app = new Carno() .use(CarnoOrm); await app.listen(3000); ``` -------------------------------- ### Examples of Calling Various Derived Query Methods Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/orm/derived-query-methods.md Illustrates calling different types of derived query methods, including single entity retrieval, multiple entities with conditions, and range-based queries. ```typescript const user = await userRepository.findByEmail('alice@example.com'); const active = await userRepository.findAllByStatusAndActive('active', true); const adults = await userRepository.findAllByAgeGreaterThanEqual(18); ``` -------------------------------- ### Define a User Service with Dependency Injection Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/core/overview.md Services and controllers are managed by the dependency injection container. This example shows a basic service definition. ```typescript import { Service } from '@carno.js/core'; @Service() export class UserService { constructor(private repository: UserRepository) {} } ``` -------------------------------- ### Tenant Middleware for HTTP Requests Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/orm/tenant-isolation.md Implement a middleware to automatically set the active tenant context for incoming HTTP requests. This example extracts the tenant ID from user claims or headers and wraps the request handling in `tenantContext.run()`. ```typescript import { Middleware, Context, NextFn } from '@carno.js/core'; import { tenantContext } from '@carno.js/orm'; @Middleware() export class TenantMiddleware { async handle(ctx: Context, next: NextFn) { // Tenant ID might come from a JWT claim, a subdomain, a header, etc. const tenantId = ctx.user?.organizationId ?? ctx.headers['x-tenant-id']; if (!tenantId) { return ctx.status(401); } // Wrap the rest of the request in the tenant context return tenantContext.run(tenantId, () => next()); } } ``` -------------------------------- ### Quick Start Controller Testing with `withTestApp` Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/testing/overview.md Use `withTestApp` for straightforward integration tests that require automatic cleanup. It ensures the test app is closed after execution, even if errors occur. ```typescript import { withTestApp, Controller, Get } from '@carno.js/core'; @Controller('/health') class HealthController { @Get() health() { return { status: 'ok' }; } } await withTestApp( async (harness) => { const response = await harness.get('/health'); expect(response.status).toBe(200); expect(await response.json()).toEqual({ status: 'ok' }); }, { controllers: [HealthController], listen: true } ); ``` -------------------------------- ### Define a User Controller Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/core/overview.md Controllers group route handlers under a base path. This example defines a controller for '/users' with a GET route to find a user by ID. ```typescript import { Controller, Get, Param } from '@carno.js/core'; @Controller('/users') export class UserController { constructor(private users: UserService) {} @Get('/:id') findOne(@Param('id') id: string) { return this.users.findById(id); } } ``` -------------------------------- ### Connection Settings for Carno ORM Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/orm/overview.md Define database connection settings in `carno.config.ts`. This example shows PostgreSQL settings, but MySQL is also supported. Ensure to specify the correct driver. ```typescript import { ConnectionSettings, BunPgDriver } from '@carno.js/orm'; const config: ConnectionSettings = { driver: BunPgDriver, // or BunMysqlDriver host: 'localhost', port: 5432, username: 'postgres', password: 'password', database: 'my_db', // Optional: migrationPath: './migrations', }; ``` -------------------------------- ### Hook Priority Example Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/core/lifecycle.md Illustrates how to use the optional priority argument with application lifecycle decorators to control the execution order of hooks. Higher priority values execute first. ```typescript @Service() export class ConfigService { @OnApplicationInit(100) loadConfig() { // runs first } } @Service() export class DatabaseService { @OnApplicationInit(50) connect() { // runs after ConfigService } } ``` -------------------------------- ### Create Custom Logger Configuration Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/core/logging.md Create a custom logger plugin using createCarnoLogger with specific configuration options. This example sets the log level to DEBUG, enables pretty printing for non-production environments, includes timestamps, and sets a prefix. ```typescript import { Carno } from '@carno.js/core'; import { createCarnoLogger, LogLevel } from '@carno.js/logger'; const LoggerModule = createCarnoLogger({ level: LogLevel.DEBUG, pretty: process.env.NODE_ENV !== 'production', timestamp: true, prefix: 'api', flushInterval: 10, }); const app = new Carno() .use(LoggerModule); ``` -------------------------------- ### Run Carno.js CLI Help Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/cli.md Execute the Carno.js CLI to display its help information. Use 'bunx' or 'npx' to run. ```bash bunx carno --help ``` -------------------------------- ### Serve Local Production Build Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/README.md Serves a local copy of the production build for testing. ```bash npm run serve ``` -------------------------------- ### Initialize Bun Project Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/installation.md Use these commands to create a new directory and initialize a Bun project for your Carno.js application. ```bash mkdir my-app cd my-app bun init ``` -------------------------------- ### Application Lifecycle Hooks Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/core/lifecycle.md Demonstrates the usage of OnApplicationInit, OnApplicationBoot, and OnApplicationShutdown decorators for managing service lifecycle events during application startup and shutdown. ```typescript import { OnApplicationBoot, OnApplicationInit, OnApplicationShutdown, Service, } from '@carno.js/core'; @Service() export class DatabaseService { @OnApplicationInit() async connect() { // connect before traffic is served } @OnApplicationBoot() reportReady() { console.log('Database service ready'); } @OnApplicationShutdown() async disconnect() { // close connection during shutdown } } ``` -------------------------------- ### Integrate ORM Module Example Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/installation.md An example of how to integrate the ORM module into your Carno.js application. This snippet shows basic usage; actual configuration may vary. ```typescript import { Carno } from '@carno.js/core'; import { CarnoOrm } from '@carno.js/orm'; // Configure ORM Module (example) // Usually you'd import a pre-configured module from another file const ormModule = new Carno(); // ... configure ormModule ... const app = new Carno(); app.use(CarnoOrm); // Use provided modules app.listen(3000); ``` -------------------------------- ### TypeScript Bulk UPDATE Example Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/orm/bulk-operations.md Example of using `Repository.bulkUpdate` in TypeScript to update multiple records. Rows can specify only the fields to be updated, with omitted fields retaining their original values. The operation is automatically wrapped in a transaction if the number of rows exceeds the `chunkSize`. ```typescript await repo.bulkUpdate([ { id: 1, name: 'Alice2', age: 31 }, { id: 2, name: 'Bob2' }, // age unchanged { id: 3, age: 33 }, // name unchanged ]); ``` -------------------------------- ### Configure Primary and Read Replicas Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/orm/read-replicas.md Define primary connection settings and a list of read replicas. Replicas inherit most settings from the primary, only requiring host overrides. ```typescript import { BunPgDriver, type ConnectionSettings } from '@carno.js/orm'; const config: ConnectionSettings = { host: 'db-primary.internal', port: 5432, username: 'app', password: process.env.DB_PASSWORD, database: 'my_app', driver: BunPgDriver, replicas: [ { host: 'db-replica-1.internal' }, { host: 'db-replica-2.internal' }, ], }; export default config; ``` -------------------------------- ### TypeScript Bulk DELETE Example Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/orm/bulk-operations.md Example of using `Repository.bulkDelete` in TypeScript to remove multiple records by their IDs. The function chunks the IDs and generates `DELETE WHERE pk IN (...)` statements for each chunk. Non-existent IDs are ignored, and the returned count reflects the actual number of deleted rows. ```typescript const deletedCount = await repo.bulkDelete([1, 2, 3, /* ... */]); ``` -------------------------------- ### Entity with Additional Property Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/orm/entities.md An example of an entity definition that includes an additional property with a default value. ```typescript import { Entity, PrimaryKey, Property, BaseEntity } from '@carno.js/orm'; @Entity() export class User extends BaseEntity { @PrimaryKey({ autoIncrement: true }) id: number; @Property() name: string; @Property({ unique: true }) email: string; @Property({ default: true }) isActive: boolean; } ``` -------------------------------- ### Initialize Database with SQL Statements Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/testing/overview.md Manually initialize the database schema using an array of SQL statements instead of relying on migrations. ```typescript await withDatabase( [ 'CREATE TABLE users (id SERIAL PRIMARY KEY, name TEXT, email TEXT)' ], async ({ orm, executeSql }) => { // Your test logic here await executeSql("INSERT INTO users (name) VALUES ('Jane')"); } ); ``` -------------------------------- ### Primitive Validation Example Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/orm/value-objects.md Demonstrates scattered validation logic for a primitive string, which is error-prone and hard to reuse. ```typescript if (!email.includes('@')) { throw new Error('Invalid email'); } ``` -------------------------------- ### Controller with DTO Validation Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/core/controllers.md Example of a controller endpoint that uses a DTO with @Schema() for automatic request body validation. ```typescript import { Body, Controller, Post } from "@carno/core"; @Controller("/users") export class UserController { constructor(private readonly users: UserService) {} @Post() create(@Body() body: CreateUserDto) { return this.users.create(body); } } ``` -------------------------------- ### List Application Routes Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/cli.md Use the 'carno routes' command to list all registered routes. You can specify an entry file if the config is insufficient. ```bash # Analyze carno.config.ts and list routes bunx carno routes ``` ```bash # Or point to your entry file if config is not enough bunx carno routes src/index.ts ``` -------------------------------- ### Count Records Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/orm/query-builder.md Retrieve the total number of records matching the query criteria. Use `executeCount()` to get the count. ```typescript const count = await User.createQueryBuilder() .where({ isActive: true }) .count() .executeCount(); ``` -------------------------------- ### Instantiate Value Objects Directly and via Factory Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/orm/value-objects.md Demonstrates creating instances of a Value Object using both direct instantiation and the static `from()` factory method. Shows how to retrieve the raw value and compare instances. ```typescript const direct = new Email('user@example.com'); const factory = Email.from('user@example.com'); console.log(direct.getValue()); // 'user@example.com' console.log(direct.equals(factory)); // true ``` -------------------------------- ### Run Project Tests Source: https://github.com/carnojs/carno.js/blob/master/README.md Executes the test suite for the Carno.js project using Bun. ```bash bun test ``` -------------------------------- ### Add Nullable Property to Entity Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/orm/migrations.md Example of adding a new nullable property to an entity. This can be part of a simple migration strategy for additions. ```typescript @Property({ nullable: true }) nickname?: string; ``` -------------------------------- ### String-Based Tenant IDs Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/orm/tenant-isolation.md Tenant IDs can be strings, such as organization slugs or UUIDs. This example shows how to use a string for the tenant discriminator. ```typescript @Entity() export class Document extends BaseEntity { @PrimaryKey() id: number; @Property() title: string; @Property({ columnName: 'org_id' }) @Tenant() orgId: string; // can be 'acme-corp', 'stellar-inc', etc. } ``` -------------------------------- ### Create and Save Using Static `create` Method Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/orm/active-record.md Use the static `create` method on the entity class for a concise way to instantiate, populate, and save a new record in a single step. ```typescript const user = await User.create({ name: 'Jane Doe', email: 'jane@example.com', isActive: true }); ``` -------------------------------- ### Run Carno.js Application Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/installation.md Execute your Carno.js application using the Bun runtime. ```bash bun run src/index.ts ``` -------------------------------- ### Configuring Compression Middleware Options Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/core/middleware.md Customize the behavior of CompressionMiddleware by providing a configuration object during instantiation. Options include response size threshold, supported encodings, compression levels, and content types eligible for compression. ```typescript new CompressionMiddleware({ threshold: 512, encodings: ['br', 'gzip'], gzipLevel: 6, brotliQuality: 4, compressibleTypes: [ 'text/', 'application/json', 'application/javascript', 'application/xml', 'image/svg+xml', ], }); ``` -------------------------------- ### Typical Carno.js Project Structure Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/installation.md Illustrates a standard directory and file structure for a Carno.js project, including the placement of controllers, services, entities, and the main entry point. ```plaintext my-app/ ├── src/ │ ├── modules/ │ │ └── user/ │ │ ├── user.controller.ts │ │ ├── user.service.ts │ │ ├── user.entity.ts │ │ └── index.ts # Exports UserModule │ ├── index.ts # Entry point ├── package.json ├── tsconfig.json └── ... ``` -------------------------------- ### Define a User Controller Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/core/controllers.md Defines a basic controller for user-related endpoints with a base path of '/users' and a GET method to find all users. ```typescript import { Controller, Get } from '@carno.js/core'; @Controller('/users') export class UserController { @Get() findAll() { return [{ id: 1, name: 'Alice' }]; } } ``` -------------------------------- ### Setup Carno.js Scheduler Module Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/schedule/overview.md Register the CarnoScheduler module within your Carno.js application. Ensure the application is listening for incoming requests. ```typescript import { Carno } from '@carno.js/core'; import { CarnoScheduler } from '@carno.js/schedule'; const app = new Carno() .use(CarnoScheduler); await app.listen(3000); ``` -------------------------------- ### Registering Services with Carno Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/core/dependency-injection.md Shows how to register multiple service classes using the `.services()` method. Carno automatically handles token and implementation for class providers. ```typescript import { Carno } from '@carno.js/core'; const app = new Carno() .services([ DatabaseService, UserService, ]); app.services([UserService]); app.services([ { token: UserService, useClass: UserService, }, ]); ``` -------------------------------- ### Identity Map Usage Example Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/orm/identity-map.md Demonstrates how two calls to findByIdOrFail for the same ID within the same identity map context return the same object instance. ```typescript const first = await users.findByIdOrFail(1); const second = await users.findByIdOrFail(1); console.log(first === second); // true, when both run in the same identity map context ``` -------------------------------- ### Enable Single Page Application (SPA) Support Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/static/overview.md Configure the StaticPlugin to serve `index.html` for any route that does not match a static file or API route, which is useful for SPAs. ```typescript app.use(await StaticPlugin.create({ root: './dist', spa: true })); ``` -------------------------------- ### Apply Middleware to a Controller Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/core/overview.md Middleware can wrap route handlers to implement cross-cutting concerns. This example applies an `AuthMiddleware` to all routes within the `AdminController`. ```typescript import { Middleware } from '@carno.js/core'; @Controller('/admin') @Middleware(AuthMiddleware) class AdminController {} ``` -------------------------------- ### Basic Database Testing with `withDatabase` Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/testing/overview.md Use `withDatabase` to ensure a clean database state for each test. It handles connection, schema creation, and cleanup automatically. ```typescript import { withDatabase } from '@carno.js/orm/testing'; import { User } from '../entities/User'; describe('UserRepository', () => { it('should create a user', async () => { await withDatabase(async ({ orm }) => { const user = await User.create({ name: 'John Doe', email: 'john@example.com' }); expect(user.id).toBeDefined(); }); }); }); ``` -------------------------------- ### Build Production Site Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/README.md Builds the static production version of the Docusaurus site. ```bash npm run build ``` -------------------------------- ### Implement Custom Validator Adapter Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/core/validation.md Implement the ValidatorAdapter interface to support custom validation libraries within Carno. This example shows the basic structure. ```typescript import type { ValidationResult, ValidatorAdapter, } from '@carno.js/core'; import { ValidationException, getSchema } from '@carno.js/core'; class MyValidatorAdapter implements ValidatorAdapter { readonly name = 'MyValidatorAdapter'; hasValidation(target: any): boolean { return getSchema(target) !== undefined; } validate(target: any, value: unknown): ValidationResult { const schema = getSchema(target); if (!schema) { return { success: true, data: value as T }; } // Run your validation library here. return { success: true, data: value as T }; } validateOrThrow(target: any, value: unknown): T { const result = this.validate(target, value); if (result.success) { return result.data!; } throw new ValidationException(result.errors ?? []); } } ``` -------------------------------- ### Controller Handler with DTO Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/core/validation.md This example shows a controller handler that accepts a `CreateUserDto`. The handler can assume the `body` parameter has already passed schema validation. ```typescript import { Body, Controller, Post, Schema } from '@carno.js/core'; import { z } from 'zod'; const CreateUserSchema = z.object({ email: z.string().email(), password: z.string().min(8), }); @Schema(CreateUserSchema) class CreateUserDto { email!: string; password!: string; } @Controller('/users') class UserController { @Post() create(@Body() body: CreateUserDto) { return { created: true, user: body }; } } ``` -------------------------------- ### Example of a Custom FindByEmail Method Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/orm/derived-query-methods.md This snippet shows a typical custom method in a repository that finds a user by their email. Derived query methods automate this pattern. ```typescript async findByEmail(email: string) { return this.findOne({ where: { email } }); } ``` -------------------------------- ### Broadcasting from Controllers with RoomManager Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/websocket/overview.md Use `RoomManager` within controllers to broadcast messages to WebSocket clients. This example shows broadcasting a notification event to a specified room. ```typescript import { Controller, Post, Body } from '@carno.js/core'; import { RoomManager } from '@carno.js/websocket'; @Controller('/api/notifications') class NotificationsController { constructor(private readonly rooms: RoomManager) {} @Post('/broadcast') send(@Body() body: { room: string; message: string }) { this.rooms.broadcast(body.room, 'notification', { text: body.message }); return { sent: true }; } } ``` -------------------------------- ### Use CronExpression Enum Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/schedule/overview.md Utilize the built-in CronExpression enum for predefined cron expressions to avoid writing raw cron strings. This example schedules a daily report. ```typescript import { CronExpression } from '@carno.js/schedule'; @Schedule(CronExpression.EVERY_DAY_AT_NOON) handleDailyReport() { ... } ``` -------------------------------- ### Basic findPage Usage Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/orm/pagination.md Demonstrates the basic usage of `findPage` with common options like `where`, `orderBy`, `page`, and `pageSize`. It also shows the structure of the returned `page` object. ```typescript const page = await userRepository.findPage({ where: { status: 'active' }, orderBy: { createdAt: 'DESC' }, page: 2, pageSize: 25, }); page.data; // User[] page.total; // total matching rows page.page; // 2 page.pageSize; // 25 page.totalPages; // Math.ceil(total / pageSize) ``` -------------------------------- ### Create Query Builder Instances Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/orm/query-builder.md Instantiate the Query Builder from an entity, repository, or the Orm service. Ensure the Orm is imported when creating from the service. ```typescript const qb = User.createQueryBuilder(); ``` ```typescript const qb = this.repository.createQueryBuilder(); ``` ```typescript import { Orm } from '@carno.js/orm'; const qb = orm.createQueryBuilder(User); ``` -------------------------------- ### Create a Custom Repository Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/orm/repository.md Create a custom repository by extending the generic Repository class and decorating it with @Service(). The constructor must call super() with the entity class. Custom methods can be added to encapsulate specific query logic. ```typescript import { Service } from '@carno.js/core'; import { Repository } from '@carno.js/orm'; import { User } from '../entities/user.entity'; @Service() export class UserRepository extends Repository { constructor() { super(User); } // Custom method to find users by role async findByRole(role: string): Promise { return this.find({ where: { role } }); } } ``` -------------------------------- ### Database Connection Settings for Migrations Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/orm/migrations.md Configure database connection settings for running migrations. Ensure environment variables are used for sensitive credentials in production environments. ```typescript const config: ConnectionSettings = { driver: BunPgDriver, host: process.env.DB_HOST, port: Number(process.env.DB_PORT ?? 5432), username: process.env.DB_USER, password: process.env.DB_PASSWORD, database: process.env.DB_NAME, migrationPath: './dist/migrations', }; ``` -------------------------------- ### Serve Multiple Static Directories Source: https://github.com/carnojs/carno.js/blob/master/docs/carno/docs/static/overview.md Use the StaticPlugin multiple times to serve static files from different directories under distinct URL prefixes. ```typescript app.use(await StaticPlugin.create({ root: './public', prefix: '/' })); app.use(await StaticPlugin.create({ root: './uploads', prefix: '/uploads' })); ```