Chapter 19: API Reference

This chapter is a comprehensive reference for every package, class, method, and interface in OriJS. Use it as a lookup when you need the exact signature of a method or the shape of an interface.

@orijs/core

The foundation package. Provides the application builder, DI container, routing, and lifecycle management.

Ori

Static factory for creating applications.

import { Ori } from '@orijs/core';

Ori.create(options?: ApplicationOptions): OriApplication

ApplicationOptions:

PropertyTypeDescription
containerContainerCustom DI container (default: new Container())
responseFactoryResponseFactoryCustom response factory
routingCoordinatorFactoryFunctionFactory for custom routing coordinator (testing)
eventCoordinatorFactoryFunctionFactory for custom event coordinator (testing)
workflowCoordinatorFactoryFunctionFactory for custom workflow coordinator (testing)
lifecycleManagerFactoryFunctionFactory for custom lifecycle manager (testing)
providerCoordinatorFactoryFunctionFactory for custom provider coordinator (testing)
socketRoutingCoordinatorFactoryFunctionFactory for custom socket routing coordinator (testing)

OriApplication

The main application class. All methods return this for fluent chaining unless otherwise noted.

Configuration Methods:

MethodSignatureDescription
config(provider: ConfigProvider | AsyncFactory): thisSets the config provider or async config factory
cors(config: CorsConfig): thisConfigures CORS
logger(options: AppLoggerOptions): thisConfigures the application logger

CorsConfig:

PropertyTypeDefaultDescription
originstring | string[]Allowed origins
methodsstring[]['GET','POST','PUT','PATCH','DELETE','OPTIONS']Allowed HTTP methods
allowedHeadersstring[]['Content-Type','Authorization','X-Firebase-AppCheck']Allowed request headers
exposedHeadersstring[][]Headers exposed to the browser
credentialsbooleantrueAllow credentials
maxAgenumber86400Preflight cache duration (seconds)

AppLoggerOptions:

PropertyTypeDescription
levelLevelNameLog level: 'debug' | 'info' | 'warn' | 'error' | 'fatal'
transportsTransport[]Array of log transports
traceFieldsTraceFieldDef[]Custom trace field definitions
clearConsolebooleanClear console before logging starts

Provider Methods:

MethodSignatureDescription
provider(service, deps?, options?): thisRegisters a provider with constructor dependencies
providerInstance(token, instance): thisRegisters a pre-instantiated value
providerWithTokens(service, deps, options?): thisRegisters with explicit token dependencies
use(extension: (app) => app): thisApplies an extension function

ProviderOptions:

PropertyTypeDefaultDescription
eagerbooleanfalseInstantiate at startup (not on first use)

Middleware Methods:

MethodSignatureDescription
guard(guard: GuardClass): thisAdds a global guard
intercept(interceptor: InterceptorClass): thisAdds a global interceptor

Controller Methods:

MethodSignatureDescription
controller(path, controller, deps?): thisRegisters an HTTP controller
socketRouter(router, deps?): thisRegisters a WebSocket socket router

Event Methods:

MethodSignatureDescription
event(definition): EventRegistrationRegisters an event definition
eventProvider(provider: EventProvider): thisSets custom event provider
getEventProvider(): EventProvider | nullReturns the event provider

EventRegistration (returned by .event()):

MethodSignatureDescription
consumer(consumerClass, deps?): OriApplicationRegisters consumer for this event

Workflow Methods:

MethodSignatureDescription
workflow(definition): WorkflowRegistrationRegisters a workflow definition
workflowProvider(provider: WorkflowProvider): thisSets custom workflow provider
getWorkflowProvider(): WorkflowProvider | nullReturns the workflow provider

WorkflowRegistration (returned by .workflow()):

MethodSignatureDescription
consumer(consumerClass, deps?): OriApplicationRegisters consumer for this workflow

Cache Methods:

MethodSignatureDescription
cache(provider?: CacheProvider): thisConfigures caching (default: InMemory)
getCacheService(): CacheService | nullReturns the cache service

WebSocket Methods:

MethodSignatureDescription
websocket(provider?, options?): OriApplication<TEmitter>Configures WebSocket support
onWebSocket(handlers: WebSocketHandlers): thisRegisters WebSocket lifecycle handlers
getWebSocketCoordinator(): SocketCoordinator | nullReturns the WebSocket coordinator
getWebSocketProvider(): WebSocketProvider | nullReturns the WebSocket provider
getSocketEmitter(): TEmitterReturns the socket emitter instance

WebSocket options (second parameter of .websocket()):

PropertyTypeDefaultDescription
pathstring'/ws'WebSocket upgrade path
emitterSocketEmitterConstructornullCustom emitter class
upgrade(request: Request) => TData | nullnullUpgrade handler (null rejects)

Lifecycle Methods:

MethodSignatureDescription
listen(port: number, callback?): Promise<BunServer>Starts the HTTP server
stop(): Promise<void>Stops the server gracefully
disableSignalHandling(): thisDisables SIGINT/SIGTERM handling (for tests)
setShutdownTimeout(timeoutMs: number): thisSets graceful shutdown timeout (default: 10s)

Inspection Methods:

MethodSignatureDescription
getRoutes(): CompiledRoute[]Returns all registered routes
getContainer(): ContainerReturns the DI container
contextAppContext (getter)Returns the application context

Container

Dependency injection container. Singletons by default.

MethodSignatureDescription
register(service, deps?): voidRegisters a service with dependencies
registerInstance(token, instance): voidRegisters a pre-created instance
registerWithTokenDeps(service, deps): voidRegisters with token dependencies
registerWithExternal(service, deps, external): voidRegisters with external package checks
resolve(token): TResolves a service synchronously
resolveAsync(token): Promise<T>Resolves with async constructor support
has(token): booleanChecks if a service is registered
validate(): voidValidates the dependency graph
clear(): voidClears all registrations and instances
clearInstances(): voidClears instances, keeps registrations
getRegisteredCount(): numberReturns count of registered services
getRegisteredNames(): string[]Returns names of registered services
setResolutionTimeout(timeoutMs): voidSets timeout warning threshold
setLogger(logger): voidSets logger for container warnings

createToken

Creates a typed injection token for named providers.

import { createToken } from '@orijs/core';

const HotCache = createToken<CacheService>('HotCache');
const ColdCache = createToken<CacheService>('ColdCache');

AppContext

Application-scoped context. Created once per application.

Properties:

PropertyTypeDescription
logLoggerApplication logger
configConfigProviderConfiguration provider
phaseLifecyclePhaseCurrent lifecycle phase
socketTSocketSocket emitter (throws if not configured)
workflowsWorkflowExecutorWorkflow executor (throws if not configured)
hasWebSocketbooleanWhether WebSocket is configured
hasWorkflowsbooleanWhether workflows are configured

LifecyclePhase: 'created' | 'bootstrapped' | 'starting' | 'ready' | 'stopping' | 'stopped'

Lifecycle Methods:

MethodSignatureDescription
onStartup(hook: () => Promise<void>): voidRegister startup hook
onReady(hook: () => Promise<void>): voidRegister ready hook
onShutdown(hook: () => Promise<void>): voidRegister shutdown hook
resolve(service): TResolve service from container
resolveAsync(service): Promise<T>Resolve with async support
getConfig(): TGet typed config

RouteBuilder

Fluent API for defining routes within a controller.

MethodSignatureDescription
guard(guard: GuardClass): thisAdds a guard
guards(guards: GuardClass[]): thisReplaces all guards
clearGuards(): thisRemoves all guards
intercept(interceptor: InterceptorClass): thisAdds an interceptor
interceptors(interceptors: InterceptorClass[]): thisReplaces all interceptors
clearInterceptors(): thisRemoves all interceptors
pipe(pipe: PipeClass, schema?): thisAdds a validation pipe
clear(): thisRemoves all guards and interceptors
param<TName>(name, validator): RouteBuilder<TState, TParams & Record<TName, string>>Declares a path parameter validator (accumulates TParams)
get(path, handler, schema?): thisRegisters a GET route
post(path, handler, schema?): thisRegisters a POST route
put(path, handler, schema?): thisRegisters a PUT route
patch(path, handler, schema?): thisRegisters a PATCH route
delete(path, handler, schema?): thisRegisters a DELETE route
head(path, handler, schema?): thisRegisters a HEAD route
options(path, handler, schema?): thisRegisters an OPTIONS route

RouteSchemaOptions:

PropertyTypeDescription
paramsSchemaSchema for URL path parameters
querySchemaSchema for query string parameters
bodySchemaSchema for request body

RequestContext

Request-scoped context passed to handlers, guards, and interceptors.

Properties:

PropertyTypeDescription
requestRequestThe raw Bun Request object
paramsTParamsTyped URL path parameters
queryRecord<string, string | string[]>Parsed query string (lazy)
stateTStateState set by guards (lazy)
correlationIdstringRequest ID (from header or generated)
logLoggerRequest-scoped logger (lazy)
eventsEventEmitterType-safe event emitter (lazy)
workflowsWorkflowExecutorWorkflow executor (lazy)
socketTSocketSocket emitter with correlation binding (lazy)
signalAbortSignalClient disconnect signal
appAppContextApplication context

Methods:

MethodSignatureDescription
set(key, value): voidSet a state variable
get(key): TState[K]Get a state variable
json(): Promise<T>Parse body as JSON
text(): Promise<string>Parse body as text
getValidatedParam(key): stringGet validated path parameter
getValidatedUUID(key): stringGet validated UUID parameter
setResponseHeader(name, value): voidInject a header into the HTTP response
getResponseHeaders(): [string, string][] | nullGet all response headers (internal)

ResponseFactory

Creates standardized HTTP responses.

MethodSignatureDescription
json(data, status): ResponseJSON response
toResponse(result): ResponseConvert any value to Response
notFound(): Response404 Not Found
forbidden(): Response403 Forbidden
methodNotAllowed(): Response405 Method Not Allowed
error(error, options?): Response500 Internal Server Error
validationError(errors, options?): Response422 Unprocessable Entity
stream(readable, contentType?, status?): ResponseStreaming response
sseStream(source, options?): ResponseServer-Sent Events stream

Interfaces

Guard:

interface Guard {
  canActivate(ctx: RequestContext): boolean | Promise<boolean>;
}

Interceptor:

interface Interceptor {
  intercept(ctx: RequestContext, next: () => Promise<Response>): Promise<Response>;
}

Pipe:

interface Pipe<TInput = unknown, TOutput = unknown> {
  transform(value: TInput, metadata?: PipeMetadata): TOutput | Promise<TOutput>;
}

OriController:

interface OriController<
  TState extends object = Record<string, unknown>,
  TParams extends Record<string, string> = Record<string, string>
> {
  configure(route: RouteBuilder<TState, TParams>): void;
}

ParamValidator:

interface ParamValidator {
  validate(value: string, key: string): string; // Returns validated value or throws
}

Built-in Param Validators: UuidParam, StringParam, NumberParam

HttpException

OriJS does not have a built-in HttpException class. Use domain error classes with an error mapping interceptor (see Chapter 17).


@orijs/validation

TypeBox-based validation with Standard Schema and custom validator support.

Type

Re-exported from @sinclair/typebox. Defines JSON Schema-compatible types.

Common methods:

MethodReturnsDescription
Type.Object(props)TObjectObject schema
Type.String(opts?)TStringString schema
Type.Number(opts?)TNumberNumber schema
Type.Integer(opts?)TIntegerInteger schema
Type.Boolean()TBooleanBoolean schema
Type.Array(items)TArrayArray schema
Type.Null()TNullNull schema
Type.Optional(schema)TOptionalOptional wrapper
Type.Union(schemas)TUnionUnion type
Type.Intersect(schemas)TIntersectIntersection type
Type.Literal(value)TLiteralLiteral value
Type.Enum(enumObj)TEnumEnum schema
Type.Record(key, value)TRecordRecord/map schema
Type.Tuple(items)TTupleTuple schema
Type.Any()TAnyAny type
Type.Unknown()TUnknownUnknown type
Type.Void()TVoidVoid type (for fire-and-forget events)
Type.Ref(schema)TRefReference to another schema

String format options: 'email', 'uuid', 'uri', 'date-time', 'date', 'time', 'ipv4', 'ipv6'

Params

Pre-built parameter validation schemas.

import { Params } from '@orijs/validation';

Params.uuid()        // UUID format string
Params.string(opts?) // String with optional min/max length
Params.number(opts?) // Numeric string (parsed to number)

Query

Pre-built query parameter schemas.

import { Query } from '@orijs/validation';

Query.pagination(opts?)  // { page, limit } with defaults
Query.search(opts?)      // { q } search string
Query.sort(opts?)        // { sortBy, sortOrder }

validate / validateSync

import { validate, validateSync } from '@orijs/validation';

// Async — supports TypeBox, Standard Schema, custom validators
const result = await validate(schema, data);
// result: { success: true, data: T } | { success: false, errors: ValidationError[] }

// Sync — TypeBox only
const result = validateSync(schema, data);

Json

Safe JSON parsing with prototype pollution protection.

import { Json } from '@orijs/validation';

Json.parse(text)       // Safe parse (strips __proto__, constructor)
Json.stringify(value)  // Standard stringify
Json.sanitize(data)    // Strip prototype pollution keys from object

@orijs/events

Type-safe event system with pluggable providers.

Event.define

Creates a type-safe event definition.

import { Event } from '@orijs/core';
import { Type } from '@orijs/validation';

const UserCreated = Event.define({
  name: 'user.created',
  data: Type.Object({ userId: Type.String(), email: Type.String() }),
  result: Type.Object({ welcomeEmailSent: Type.Boolean() }),
});

EventConfig:

PropertyTypeDescription
namestringUnique event name (dot notation: 'entity.action')
dataTSchemaTypeBox schema for input data
resultTSchemaTypeBox schema for result (use Type.Void() for fire-and-forget)

IEventConsumer

Interface for event consumer classes.

interface IEventConsumer<TData, TResult> {
  readonly onEvent: (ctx: EventContext<TData>) => Promise<TResult> | TResult;
  readonly onSuccess?: (ctx: EventContext<TData>, result: TResult) => Promise<void> | void;
  readonly onError?: (ctx: EventContext<TData>, error: Error) => Promise<void> | void;
}

EventContext

Context passed to event consumers.

PropertyTypeDescription
eventIdstringUnique event instance ID
dataTPayloadThe event payload data
logLoggerStructured logger
eventNamestringEvent name
timestampnumberEmission timestamp (ms since epoch)
correlationIdstringCorrelation ID for tracing
causationIdstring?Parent event ID (chain tracking)
emitFunctionEmit chained events

EventProvider Interface

interface EventProvider extends EventEmitter, EventLifecycle {}

interface EventEmitter {
  emit(eventName, payload, meta?, options?): EventSubscription;
  subscribe(eventName, handler): void | Promise<void>;
}

interface EventLifecycle {
  start(): Promise<void>;
  stop(): Promise<void>;
}

Utility Types

import type { Data, Result, EventConsumer, EventCtx } from '@orijs/core';

type UserData = Data<typeof UserCreated>;      // Extract data type
type UserResult = Result<typeof UserCreated>;  // Extract result type
type Consumer = EventConsumer<typeof UserCreated>; // Consumer interface
type Ctx = EventCtx<typeof UserCreated>;       // Context type

@orijs/workflows

Saga-pattern workflow orchestration with distributed step execution.

Workflow.define

Creates a type-safe workflow definition with optional steps.

import { Workflow } from '@orijs/core';
import { Type } from '@orijs/validation';

// Simple workflow (no steps)
const SendEmail = Workflow.define({
  name: 'send-email',
  data: Type.Object({ to: Type.String(), subject: Type.String() }),
  result: Type.Object({ messageId: Type.String() }),
});

// Workflow with steps
const ProcessOrder = Workflow.define({
  name: 'process-order',
  data: Type.Object({ orderId: Type.String() }),
  result: Type.Object({ processedAt: Type.Number() }),
}).steps(s => s
  .sequential(s.step('validate', Type.Object({ valid: Type.Boolean() })))
  .sequential(s.step('charge', Type.Object({ chargeId: Type.String() })))
  .parallel(
    s.step('notify', Type.Object({ sent: Type.Boolean() })),
    s.step('audit', Type.Object({ logged: Type.Boolean() }))
  )
);

IWorkflowConsumer

interface IWorkflowConsumer<TData, TResult, TSteps = Record<never, never>> {
  readonly steps?: {
    [K in keyof TSteps]?: StepHandler<TData, TSteps[K], TSteps>;
  };
  readonly onComplete: (ctx: WorkflowContext<TData, TSteps>) => Promise<TResult> | TResult;
  readonly onError?: (ctx: WorkflowContext<TData, TSteps>, error: Error) => Promise<void> | void;
}

interface StepHandler<TData, TOutput, TResults = Record<string, unknown>> {
  readonly execute: (ctx: StepContext<TData, TResults>) => Promise<TOutput> | TOutput;
  readonly rollback?: (ctx: StepContext<TData, TResults>) => Promise<void> | void;
}

WorkflowContext

PropertyTypeDescription
flowIdstringUnique workflow execution ID
dataTDataWorkflow input data
resultsTStepsTyped accumulated step results
logLoggerStructured logger
metaRecord<string, unknown>Propagation metadata
correlationIdstringCorrelation ID

StepContext

PropertyTypeDescription
flowIdstringWorkflow execution ID
dataTDataWorkflow input data
resultsTResultsAccumulated step results
logLoggerStructured logger
metaRecord<string, unknown>Propagation metadata
stepNamestringCurrent step name

WorkflowExecutor (ctx.workflows)

interface WorkflowExecutor {
  execute<TData, TResult>(
    workflow: WorkflowDefinition<TData, TResult>,
    data: TData,
    options?: WorkflowExecuteOptions
  ): Promise<WorkflowHandle<TResult>>;
}

WorkflowExecuteOptions:

PropertyTypeDefaultDescription
idstringUUIDCustom workflow ID (for idempotency)
prioritynumber0Priority (lower = higher)
delaynumber0Delay before start (ms)

WorkflowHandle:

MethodSignatureDescription
idstringWorkflow instance ID
status(): Promise<WorkflowStatus>Current status
result(): Promise<TResult>Wait for completion
cancel(): Promise<boolean>Cancel if running

WorkflowStatus: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled'


@orijs/cache

Entity-based caching with singleflight, grace periods, and cascade invalidation.

CacheEntityRegistry

Defines cacheable entities with scope and required parameters.

import { CacheEntityRegistry } from '@orijs/cache';

const Entities = CacheEntityRegistry.create({
  User: { scope: 'account', requiredParams: ['accountUuid'] },
  Monitor: { scope: 'project', requiredParams: ['accountUuid', 'projectUuid'] },
});

CacheService

The main caching interface. Injected as a provider.

MethodSignatureDescription
getOrSet(config, params, factory): Promise<T>Get from cache or compute
invalidate(entityName, params): Promise<void>Invalidate entity cache
invalidateAll(entityName): Promise<void>Invalidate all entries for entity

CacheProvider Interface

The interface custom cache providers must implement.

interface CacheProvider {
  get<T>(key: string): Promise<T | null>;
  set<T>(key: string, value: T, ttlSeconds: number): Promise<void>;
  del(key: string): Promise<number>;
  delMany(keys: string[]): Promise<number>;
  exists(key: string): Promise<boolean>;
  ttl(key: string): Promise<number>;
}

FactoryContext

Context passed to the factory function during cache miss.

Property/MethodTypeDescription
skip()neverDon’t cache, return undefined
fail(message)neverSignal error, use stale if available
staleValueT | undefinedStale value during grace period
staleAgenumber | undefinedAge of stale value (seconds)

InMemoryCacheProvider

Built-in in-memory cache provider. Suitable for development and testing.

import { InMemoryCacheProvider } from '@orijs/cache';

const provider = new InMemoryCacheProvider();

@orijs/websocket

WebSocket support with Bun’s native WebSocket server and pluggable scaling providers.

WebSocket Options

Configured via app.websocket(provider?, options?).

OriSocketRouter

Interface for WebSocket message routing.

interface OriSocketRouter<TState, TSocket> {
  configure(route: SocketRouteBuilder<TState, TSocket>): void;
}

SocketRouteBuilder

Fluent API for defining WebSocket routes.

MethodSignatureDescription
connectionGuard(guard): thisGuard that runs ONCE on upgrade
guard(guard): thisGuard that runs per-message
guards(guards): thisReplace all message guards
clearGuards(): thisClear message guards
on(messageType, handler, schema?): thisRegister message handler

SocketContext

Per-message context for socket handlers.

PropertyTypeDescription
stateTStateState from connection guards
dataunknownParsed message data
messageTypestringMessage type being handled
correlationIdstringCorrelation ID
socketIdstringSocket connection ID
appAppContext<TSocket>Application context with typed socket

SocketEmitter Interface

interface SocketEmitter {
  publish(topic: string, message: string | ArrayBuffer): Promise<void>;
  send(socketId: string, message: string | ArrayBuffer): void;
  broadcast(message: string | ArrayBuffer): void;
  emit<TData>(message: SocketMessageLike<TData>, topic: string, data: TData): Promise<void>;
}

WebSocketProvider Interface

Full interface for scaling providers.

interface WebSocketProvider extends SocketEmitter, SocketLifecycle {
  subscribe(socketId: string, topic: string): void;
  unsubscribe(socketId: string, topic: string): void;
  disconnect(socketId: string): void;
  isConnected(socketId: string): boolean;
  getConnectionCount(): number;
  getTopicSubscriberCount(topic: string): number;
  setServer(server: BunServer): void;
}

SocketMessage.define

Creates typed WebSocket message definitions.

import { SocketMessage } from '@orijs/core';
import { Type } from '@orijs/validation';

const IncidentCreated = SocketMessage.define({
  name: 'incident.created',
  data: Type.Object({ uuid: Type.String(), title: Type.String() }),
});

// Usage: await socket.emit(IncidentCreated, 'account:123', { uuid: '...', title: '...' });

@orijs/config

Environment-based configuration with validation.

EnvConfigProvider

Reads configuration from environment variables.

import { EnvConfigProvider } from '@orijs/config';

const config = new EnvConfigProvider();
const value = await config.get('DATABASE_URL');
const required = await config.getRequired('DATABASE_URL'); // throws if missing

ValidatedConfig

Validates configuration at startup.

import { ValidatedConfig } from '@orijs/config';

const config = new ValidatedConfig({
  DATABASE_URL: { required: true },
  PORT: { required: true, transform: Number },
  LOG_LEVEL: { required: false, default: 'info' },
});

await config.validate(); // Throws if required keys are missing

NamespacedConfig / createConfigProvider

Creates namespaced configuration with type-safe access.

import { createConfigProvider } from '@orijs/config';

const config = createConfigProvider({
  db: { url: 'DATABASE_URL', pool: { max: 'DB_POOL_MAX' } },
  redis: { host: 'REDIS_HOST', port: 'REDIS_PORT' },
});

@orijs/mapper

SQL result to TypeScript object mapping.

Mapper.defineTable

Defines table schemas for SQL result mapping.

import { Mapper, field } from '@orijs/mapper';

const Tables = Mapper.defineTable({
  User: {
    tableName: 'user',
    uuid: field('uuid').string(),
    displayName: field('display_name').string().optional(),
    email: field('email').string(),
    createdAt: field('created_at').date(),
    isActive: field('is_active').boolean(),
    metadata: field('metadata').any(), // JSONB
  },
});

Field types:

MethodDescription
field(column).string()String field
field(column).number()Number field
field(column).boolean()Boolean field
field(column).date()Date field (coerces from string/Date)
field(column).any()Any type (JSONB, etc.)
.optional()Makes field nullable

Mapper.for / .build

Creates a mapper for a specific table.

const UserMapper = Mapper.for<User>(Tables.User).build();

// Map a single row
const user: User = UserMapper.map(row);

// Map multiple rows
const users: User[] = UserMapper.mapMany(rows);

MapResult / MapOptions:

interface MapOptions {
  strict?: boolean; // Throw on missing columns (default: false)
}

@orijs/logging

Pino-inspired structured logging with transports.

Logger

import { Logger } from '@orijs/logging';

const log = new Logger('MyService', { level: 'info', transports: [...] });

Logger methods:

MethodSignatureDescription
debug(msg, data?): voidDebug level log
info(msg, data?): voidInfo level log
warn(msg, data?): voidWarn level log
error(msg, data?): voidError level log
fatal(msg, data?): voidFatal level log
child(name): LoggerCreate child logger
with(context): LoggerCreate logger with additional context
setMeta(key, value): voidSet metadata on context

Static methods:

MethodSignatureDescription
Logger.configure(options): voidSet global defaults
Logger.reset(): voidReset global state
Logger.shutdown(): Promise<void>Flush and close all transports

Transports

import { consoleTransport, fileTransport, filterTransport, multiTransport } from '@orijs/logging';

consoleTransport(options?)   // Console output (colorize, JSON)
fileTransport(options)       // File output with rotation
filterTransport(options)     // Level-filtered transport
multiTransport(transports)   // Fan-out to multiple transports

@orijs/test-utils

Testing utilities and infrastructure helpers.

createBunTestPreload

Creates a Bun test preload setup function.

import { createBunTestPreload } from '@orijs/test-utils';

const preload = createBunTestPreload({
  packageName: 'my-app',
  dependencies: ['redis'],
});

await preload();

teardownBunTest

Cleans up test containers.

import { teardownBunTest } from '@orijs/test-utils';

afterAll(() => teardownBunTest('my-app'));

createRedisTestHelper

Creates a Redis test helper for Testcontainer-based testing.

import { createRedisTestHelper } from '@orijs/test-utils';

const helper = createRedisTestHelper('my-app');
const redis = helper.createRedisClient();

Async Helpers

FunctionSignatureDescription
waitFor(condition, options?): Promise<void>Poll sync condition
waitForAsync(condition, options?): Promise<void>Poll async condition
withTimeout(promise, timeoutMs, message?): Promise<T>Timeout wrapper
delay(ms): Promise<void>Simple delay

WaitForOptions:

PropertyTypeDefaultDescription
timeoutnumber5000Max wait time (ms)
intervalnumber50Poll interval (ms)
messagestringCustom timeout error message

@orijs/bullmq

BullMQ providers for distributed events and workflows.

BullMQEventProvider

import { BullMQEventProvider, Redis } from '@orijs/bullmq';

const redis = new Redis({ host: 'localhost', port: 6379 });
const provider = new BullMQEventProvider({ connection: redis });

Ori.create()
  .eventProvider(provider)
  .event(UserCreated).consumer(UserCreatedConsumer, [EmailService])
  .listen(3000);

createBullMQWorkflowProvider

import { createBullMQWorkflowProvider, Redis } from '@orijs/bullmq';

const redis = new Redis({ host: 'localhost', port: 6379 });
const provider = createBullMQWorkflowProvider({ connection: redis });

Ori.create()
  .workflowProvider(provider)
  .workflow(SendEmail).consumer(SendEmailWorkflow, [SmtpClient])
  .listen(3000);

@orijs/cache-redis

Redis cache provider with dependency tracking.

createRedisCacheProvider

import { createRedisCacheProvider } from '@orijs/cache-redis';

const provider = createRedisCacheProvider({
  connection: { host: 'localhost', port: 6379 },
});

Ori.create()
  .cache(provider)
  .listen(3000);

RedisCacheProviderOptions:

PropertyTypeDescription
connectionRedis | RedisConnectionOptionsRedis connection or options

@orijs/websocket-redis

Redis WebSocket provider for horizontal scaling.

createRedisWsProvider

import { createRedisWsProvider } from '@orijs/websocket-redis';

const provider = createRedisWsProvider({
  connection: { host: 'localhost', port: 6379 },
});

Ori.create()
  .websocket(provider)
  .listen(3000);

RedisWsProviderOptions:

PropertyTypeDescription
connectionRedisConnectionOptionsRedis connection options

Previous: Migration from NestJS ← | Back to Table of Contents →