API Reference
API Reference
Section titled “API Reference”Complete API reference for Veloce-TS framework.
Table of Contents
Section titled “Table of Contents”Core Classes
Section titled “Core Classes”Veloce
Section titled “Veloce”The main application class.
Constructor
Section titled “Constructor”new Veloce(config?: VeloceConfig)Parameters:
config(optional): Configuration object
VeloceConfig Interface:
interface VeloceConfig { adapter?: 'hono' | 'express' | 'native'; title?: string; version?: string; description?: string; docs?: boolean | { path?: string; openapi?: string }; cors?: CorsOptions | boolean; plugins?: Plugin[];}Example:
const app = new Veloce({ title: 'My API', version: '1.0.0', description: 'API for my application', docs: true, cors: true,});Methods
Section titled “Methods”include(controller: Class): void
Section titled “include(controller: Class): void”Register a controller class with the application.
@Controller('/users')class UserController { @Get('/') async list() { return []; }}
app.include(UserController);includeRouter(router: Router): void
Section titled “includeRouter(router: Router): void”Register a router with the application.
const router = new Router();router.get('/health', () => ({ status: 'ok' }));
app.includeRouter(router);get(path: string, config: RouteConfig): void
Section titled “get(path: string, config: RouteConfig): void”Register a GET route using functional API.
app.get('/users', { handler: async (c) => { return [{ id: 1, name: 'John' }]; },});post(path: string, config: RouteConfig): void
Section titled “post(path: string, config: RouteConfig): void”Register a POST route using functional API.
const UserSchema = z.object({ name: z.string(), email: z.string().email(),});
app.post('/users', { schema: { body: UserSchema }, handler: async (c) => { const body = await c.req.json(); return { id: 2, ...body }; },});put(path: string, config: RouteConfig): void
Section titled “put(path: string, config: RouteConfig): void”Register a PUT route using functional API.
delete(path: string, config: RouteConfig): void
Section titled “delete(path: string, config: RouteConfig): void”Register a DELETE route using functional API.
patch(path: string, config: RouteConfig): void
Section titled “patch(path: string, config: RouteConfig): void”Register a PATCH route using functional API.
route(path: string): RouteBuilder
Section titled “route(path: string): RouteBuilder”Create a route builder for chaining multiple methods on the same path.
app.route('/users') .get({ handler: async (c) => { return []; }, }) .post({ handler: async (c) => { const body = await c.req.json(); return body; }, });group(prefix: string, callback: () => void): void
Section titled “group(prefix: string, callback: () => void): void”Group routes under a common prefix.
app.group('/api', () => { app.get('/users', { handler: async (c) => [] }); app.get('/posts', { handler: async (c) => [] });});// Creates: /api/users and /api/postsuse(middleware: Middleware): void
Section titled “use(middleware: Middleware): void”Register global middleware.
app.use(async (c, next) => { console.log(`${c.req.method} ${c.req.url}`); await next();});useCors(options?: CorsOptions): void
Section titled “useCors(options?: CorsOptions): void”Enable CORS with optional configuration.
app.useCors({ origin: 'https://example.com', methods: ['GET', 'POST'], credentials: true,});useRateLimit(options: RateLimitOptions): void
Section titled “useRateLimit(options: RateLimitOptions): void”Enable rate limiting.
app.useRateLimit({ windowMs: 15 * 60 * 1000, // 15 minutes max: 100, // 100 requests per window});useCompression(options?: CompressionOptions): void
Section titled “useCompression(options?: CompressionOptions): void”Enable response compression.
app.useCompression({ threshold: 1024, // Only compress responses > 1KB});usePlugin(plugin: Plugin): void
Section titled “usePlugin(plugin: Plugin): void”Register a plugin with the application.
import { OpenAPIPlugin } from 'veloce-ts';
app.usePlugin(new OpenAPIPlugin({ path: '/openapi.json', docsPath: '/docs',}));onError(handler: ErrorHandler): void
Section titled “onError(handler: ErrorHandler): void”Register a custom error handler.
app.onError((error, c) => { console.error('Error:', error); return c.json({ error: error.message, timestamp: new Date().toISOString(), }, 500);});listen(port: number, callback?: () => void): Server
Section titled “listen(port: number, callback?: () => void): Server”Start the server on the specified port.
app.listen(3000, () => { console.log('Server running on http://localhost:3000');});compile(): void
Section titled “compile(): void”Compile all routes and metadata. Called automatically by listen().
app.compile();getHono(): Hono
Section titled “getHono(): Hono”Get the underlying Hono instance.
const hono = app.getHono();getMetadata(): MetadataRegistry
Section titled “getMetadata(): MetadataRegistry”Get the metadata registry.
const metadata = app.getMetadata();const routes = metadata.getRoutes();getContainer(): DIContainer
Section titled “getContainer(): DIContainer”Get the dependency injection container.
const container = app.getContainer();container.register(DatabaseService, { scope: 'singleton' });Response
Section titled “Response”Response builder classes for different content types.
JSONResponse
Section titled “JSONResponse”import { JSONResponse } from 'veloce-ts';
@Get('/data')async getData() { return new JSONResponse({ data: 'value' }, 200);}HTMLResponse
Section titled “HTMLResponse”import { HTMLResponse } from 'veloce-ts';
@Get('/page')async getPage() { return new HTMLResponse('<h1>Hello</h1>', 200);}FileResponse
Section titled “FileResponse”import { FileResponse } from 'veloce-ts';
@Get('/download')async download() { return new FileResponse('/path/to/file.pdf', { filename: 'document.pdf', contentType: 'application/pdf', });}StreamResponse
Section titled “StreamResponse”import { StreamResponse } from 'veloce-ts';
@Get('/stream')async stream() { const stream = createReadStream('/path/to/large-file.txt'); return new StreamResponse(stream, { contentType: 'text/plain', });}RedirectResponse
Section titled “RedirectResponse”import { RedirectResponse } from 'veloce-ts';
@Get('/old-path')async redirect() { return new RedirectResponse('/new-path', 301);}Decorators
Section titled “Decorators”Class Decorators
Section titled “Class Decorators”@Controller(prefix?: string)
Section titled “@Controller(prefix?: string)”Marks a class as a controller and optionally sets a path prefix.
Parameters:
prefix(optional): Path prefix for all routes in the controller
Example:
@Controller('/api/users')class UserController { @Get('/') async list() { return []; }}@WebSocket(path: string)
Section titled “@WebSocket(path: string)”Marks a class as a WebSocket handler.
Parameters:
path: WebSocket endpoint path
Example:
@WebSocket('/chat')class ChatHandler { @OnConnect() handleConnect(client: WebSocketConnection) { console.log('Connected'); }}@Resolver()
Section titled “@Resolver()”Marks a class as a GraphQL resolver.
Example:
@Resolver()class UserResolver { @Query() async users() { return []; }}@UseMiddleware(...middleware: Middleware[])
Section titled “@UseMiddleware(...middleware: Middleware[])”Apply middleware to a controller or route.
Parameters:
middleware: One or more middleware functions
Example:
const authMiddleware = async (c, next) => { // Auth logic await next();};
@Controller('/admin')@UseMiddleware(authMiddleware)class AdminController { // All routes protected}Method Decorators
Section titled “Method Decorators”HTTP Method Decorators
Section titled “HTTP Method Decorators”@Get(path?: string)
Section titled “@Get(path?: string)”Register a GET route.
Parameters:
path(optional): Route path
Example:
@Get('/users')async getUsers() { return [];}
@Get('/users/:id')async getUser(@Param('id') id: string) { return { id };}@Post(path?: string)
Section titled “@Post(path?: string)”Register a POST route.
Example:
@Post('/users')async createUser(@Body(UserSchema) user: User) { return user;}@Put(path?: string)
Section titled “@Put(path?: string)”Register a PUT route.
Example:
@Put('/users/:id')async updateUser( @Param('id') id: string, @Body(UserSchema) user: User) { return { id, ...user };}@Delete(path?: string)
Section titled “@Delete(path?: string)”Register a DELETE route.
Example:
@Delete('/users/:id')async deleteUser(@Param('id') id: string) { return { success: true };}@Patch(path?: string)
Section titled “@Patch(path?: string)”Register a PATCH route.
Example:
@Patch('/users/:id')async patchUser( @Param('id') id: string, @Body(PartialUserSchema) data: Partial<User>) { return { id, ...data };}@All(path?: string)
Section titled “@All(path?: string)”Register a route that responds to all HTTP methods.
Example:
@All('/webhook')async webhook() { return { received: true };}GraphQL Method Decorators
Section titled “GraphQL Method Decorators”@Query()
Section titled “@Query()”Define a GraphQL query.
Example:
@Resolver()class UserResolver { @Query() async users() { return await db.getUsers(); }
@Query() async user(@Arg('id', z.number()) id: number) { return await db.getUserById(id); }}@Mutation()
Section titled “@Mutation()”Define a GraphQL mutation.
Example:
@Mutation()async createUser(@Arg('input', CreateUserInput) input: any) { return await db.createUser(input);}@Subscription()
Section titled “@Subscription()”Define a GraphQL subscription.
Example:
@Subscription()async userCreated() { return pubsub.asyncIterator('USER_CREATED');}WebSocket Method Decorators
Section titled “WebSocket Method Decorators”@OnConnect()
Section titled “@OnConnect()”Handle WebSocket connection events.
Example:
@OnConnect()handleConnect(client: WebSocketConnection) { console.log(`Client ${client.id} connected`);}@OnMessage(schema?: ZodSchema)
Section titled “@OnMessage(schema?: ZodSchema)”Handle WebSocket message events with optional validation.
Parameters:
schema(optional): Zod schema for message validation
Example:
const MessageSchema = z.object({ type: z.string(), content: z.string(),});
@OnMessage(MessageSchema)handleMessage( client: WebSocketConnection, message: z.infer<typeof MessageSchema>) { client.broadcast(message);}@OnDisconnect()
Section titled “@OnDisconnect()”Handle WebSocket disconnection events.
Example:
@OnDisconnect()handleDisconnect(client: WebSocketConnection) { console.log(`Client ${client.id} disconnected`);}Parameter Decorators
Section titled “Parameter Decorators”@Body(schema?: ZodSchema)
Section titled “@Body(schema?: ZodSchema)”Extract and validate request body.
Parameters:
schema(optional): Zod schema for validation
Example:
const UserSchema = z.object({ name: z.string().min(2), email: z.string().email(),});
@Post('/users')async createUser(@Body(UserSchema) user: z.infer<typeof UserSchema>) { return user;}@Query(schema?: ZodSchema)
Section titled “@Query(schema?: ZodSchema)”Extract and validate query parameters.
Parameters:
schema(optional): Zod schema for validation
Example:
const SearchSchema = z.object({ q: z.string(), page: z.string().transform(Number).default('1'),});
@Get('/search')async search(@Query(SearchSchema) query: z.infer<typeof SearchSchema>) { return { query: query.q, page: query.page };}@Param(name?: string)
Section titled “@Param(name?: string)”Extract route parameters.
Parameters:
name(optional): Specific parameter name to extract
Example:
@Get('/users/:id')async getUser(@Param('id') id: string) { return { id };}
// Extract all params@Get('/users/:userId/posts/:postId')async getPost(@Param() params: { userId: string; postId: string }) { return params;}@Header(name?: string, schema?: ZodSchema)
Section titled “@Header(name?: string, schema?: ZodSchema)”Extract and validate headers.
Parameters:
name(optional): Specific header name to extractschema(optional): Zod schema for validation
Example:
@Get('/protected')async getProtected(@Header('authorization') auth: string) { return { auth };}
const HeaderSchema = z.object({ 'x-api-key': z.string(),});
@Get('/api')async apiEndpoint(@Header(HeaderSchema) headers: z.infer<typeof HeaderSchema>) { return headers;}@Cookie(name?: string, schema?: ZodSchema)
Section titled “@Cookie(name?: string, schema?: ZodSchema)”Extract and validate cookies.
Parameters:
name(optional): Specific cookie name to extractschema(optional): Zod schema for validation
Example:
@Get('/profile')async getProfile(@Cookie('session') sessionId: string) { return { sessionId };}@Depends(provider: Provider, scope?: Scope)
Section titled “@Depends(provider: Provider, scope?: Scope)”Inject dependencies.
Parameters:
provider: Service class to injectscope(optional): Dependency scope (‘singleton’, ‘request’, ‘transient’)
Example:
class UserService { async getUsers() { return []; }}
@Controller('/users')class UserController { @Get('/') async list(@Depends(UserService) userService: UserService) { return await userService.getUsers(); }}@Arg(name: string, schema?: ZodSchema)
Section titled “@Arg(name: string, schema?: ZodSchema)”GraphQL argument with validation.
Parameters:
name: Argument nameschema(optional): Zod schema for validation
Example:
@Resolver()class UserResolver { @Query() async user(@Arg('id', z.number().int().positive()) id: number) { return await db.getUserById(id); }}Plugin System
Section titled “Plugin System”Plugin Interface
Section titled “Plugin Interface”interface Plugin { name: string; version?: string; dependencies?: string[]; install(app: Veloce): void | Promise<void>;}Creating a Plugin
Section titled “Creating a Plugin”class MyPlugin implements Plugin { name = 'my-plugin'; version = '1.0.0';
install(app: Veloce) { // Add routes app.get('/plugin-route', { handler: async (c) => { return { message: 'From plugin' }; }, });
// Add middleware app.use(async (c, next) => { console.log('Plugin middleware'); await next(); });
// Register services app.getContainer().register(MyService, { scope: 'singleton' }); }}Using Plugins
Section titled “Using Plugins”const app = new Veloce();app.usePlugin(new MyPlugin());Built-in Plugins
Section titled “Built-in Plugins”OpenAPIPlugin
Section titled “OpenAPIPlugin”import { OpenAPIPlugin } from 'veloce-ts';
app.usePlugin(new OpenAPIPlugin({ path: '/openapi.json', docsPath: '/docs', title: 'My API', version: '1.0.0', description: 'API description',}));Options:
path: OpenAPI spec endpoint (default:/openapi.json)docsPath: Swagger UI endpoint (default:/docs)title: API titleversion: API versiondescription: API description
GraphQLPlugin
Section titled “GraphQLPlugin”import { GraphQLPlugin } from 'veloce-ts';
app.usePlugin(new GraphQLPlugin({ path: '/graphql', playground: true, introspection: true,}));Options:
path: GraphQL endpoint (default:/graphql)playground: Enable GraphQL Playground (default:true)introspection: Enable introspection (default:true)
WebSocketPlugin
Section titled “WebSocketPlugin”import { WebSocketPlugin } from 'veloce-ts';
app.usePlugin(new WebSocketPlugin({ path: '/ws', maxConnections: 1000,}));Options:
path: WebSocket endpoint (default:/ws)maxConnections: Maximum concurrent connections
Testing Utilities
Section titled “Testing Utilities”createTestApp(config?: VeloceConfig): Veloce
Section titled “createTestApp(config?: VeloceConfig): Veloce”Creates a test instance of the application.
Example:
import { createTestApp } from 'veloce-ts/testing';
const app = createTestApp();app.include(UserController);TestClient
Section titled “TestClient”HTTP client for making test requests.
Methods:
get(path: string, options?: RequestOptions): Promise<Response>post(path: string, body?: any, options?: RequestOptions): Promise<Response>put(path: string, body?: any, options?: RequestOptions): Promise<Response>delete(path: string, options?: RequestOptions): Promise<Response>patch(path: string, body?: any, options?: RequestOptions): Promise<Response>
Example:
import { TestClient } from 'veloce-ts/testing';
const client = new TestClient(app);
const response = await client.get('/users');const data = await response.json();
expect(response.status).toBe(200);expect(data).toBeArray();mockDependency(provider: Class, mock: any): void
Section titled “mockDependency(provider: Class, mock: any): void”Mocks a dependency in the DI container.
Example:
import { mockDependency } from 'veloce-ts/testing';
const mockUserService = { getUsers: async () => [{ id: 1, name: 'Test' }],};
mockDependency(UserService, mockUserService);Error Classes
Section titled “Error Classes”HTTPException
Section titled “HTTPException”Base exception class for HTTP errors.
Constructor:
new HTTPException(status: number, message: string, details?: any)Example:
import { HTTPException } from 'veloce-ts';
@Get('/users/:id')async getUser(@Param('id') id: string) { const user = await db.getUserById(id);
if (!user) { throw new HTTPException(404, 'User not found'); }
return user;}ValidationException
Section titled “ValidationException”Exception for validation errors (422 status).
Example:
import { ValidationException } from 'veloce-ts';
throw new ValidationException([ { path: 'email', message: 'Invalid email format' },]);NotFoundException
Section titled “NotFoundException”Exception for not found errors (404 status).
Example:
import { NotFoundException } from 'veloce-ts';
throw new NotFoundException('Resource not found');UnauthorizedException
Section titled “UnauthorizedException”Exception for unauthorized errors (401 status).
Example:
import { UnauthorizedException } from 'veloce-ts';
throw new UnauthorizedException('Invalid credentials');ForbiddenException
Section titled “ForbiddenException”Exception for forbidden errors (403 status).
Example:
import { ForbiddenException } from 'veloce-ts';
throw new ForbiddenException('Access denied');VeloceConfig
Section titled “VeloceConfig”interface VeloceConfig { adapter?: 'hono' | 'express' | 'native'; title?: string; version?: string; description?: string; docs?: boolean | { path?: string; openapi?: string }; cors?: CorsOptions | boolean; plugins?: Plugin[];}RouteConfig
Section titled “RouteConfig”interface RouteConfig { handler: (c: Context) => any | Promise<any>; schema?: { body?: ZodSchema; query?: ZodSchema; params?: ZodSchema; headers?: ZodSchema; }; middleware?: Middleware[];}Middleware
Section titled “Middleware”type Middleware = (c: Context, next: () => Promise<void>) => Promise<void> | void;Context
Section titled “Context”Hono context object with request and response utilities.
Properties:
req: Request objectres: Response objectenv: Environment variablesexecutionCtx: Execution context
Methods:
json(data: any, status?: number): Responsetext(text: string, status?: number): Responsehtml(html: string, status?: number): Responseredirect(url: string, status?: number): Response
type Scope = 'singleton' | 'request' | 'transient';WebSocketConnection
Section titled “WebSocketConnection”interface WebSocketConnection { id: string; send(data: any): void; broadcast(data: any, includeSelf?: boolean): void; join(room: string): void; leave(room: string): void; close(): void;}Next Steps
Section titled “Next Steps”- Read the Decorators Guide for detailed decorator usage
- Learn about Dependency Injection
- Explore Plugins
- Check out Testing Guide
- View the Getting Started Guide