### Install Dependencies with Dart Source: https://doc.vaden.dev/docs/Introduction/getting-started Installs the necessary project dependencies using the Dart SDK's package manager. This command downloads and links all required libraries specified in the project's pubspec.yaml file. ```bash dart pub get ``` -------------------------------- ### Run the Vaden Project Source: https://doc.vaden.dev/docs/Introduction/getting-started Executes the main entry point of the Vaden application. This command starts the server, allowing you to access and test your application's functionality. ```bash dart run bin/server.dart ``` -------------------------------- ### Project Setup and Server Initialization (Dart) Source: https://context7.com/context7/doc_vaden_dev/llms.txt This snippet shows how to set up a new Vaden project, install dependencies, run the class scanner for code generation, and start the development server. It highlights the main entry point `bin/server.dart` and accessing the Swagger UI. ```dart // Generate project at https://start.vaden.dev // Then install dependencies // Terminal: // dart pub get // Run class scanner to generate application code // Terminal: // dart run build_runner watch // bin/server.dart - Main entry point import 'package:example/vaden_application.dart'; Future main(List args) async { final vaden = VadenApplicationImpl(); await vaden.setup(); final server = await vaden.run(args); print('Server listening on port ${server.port}'); } // Access Swagger UI at http://localhost:8080/docs/ ``` -------------------------------- ### Run Class Scanner with build_runner Source: https://doc.vaden.dev/docs/Introduction/getting-started Initiates the build process using build_runner, which includes running the Vaden Class Scanner. This command is essential for development as it enables hot-reloading and recompilation of code changes. ```bash dart run build_runner watch ``` -------------------------------- ### Dart Vaden ApplicationRunner Example Source: https://doc.vaden.dev/docs/basic-usage/warm_up An example of an ApplicationRunner component in Vaden, which executes automatically at application startup. This is suitable for general initialization tasks such as preparing the database or initializing logging services. ```dart @Component() class AppWarmup implements ApplicationRunner { @override Future run(VadenApplication app) async { await prepareDatabase(); initializeLogger(); } } ``` -------------------------------- ### Product API Client Example Source: https://doc.vaden.dev/docs/addons/flutter-vaden Example demonstrating how to define an API client using the @ApiClient annotation for RESTful API interactions. ```APIDOC ## @ApiClient Example ### Description This section showcases the usage of the `@ApiClient` annotation to define an abstract class that acts as a client for a RESTful API. It demonstrates how to define methods for various HTTP operations (GET, POST, PUT, DELETE) and how to map them to API endpoints and parameters. ### Method N/A (This is a code definition, not an executable endpoint) ### Endpoint N/A (This is a code definition, not an executable endpoint) ### Parameters N/A ### Request Body N/A ### Response N/A ### Code Example ```dart // Assume ProductDTO is defined with @DTO annotation @Configuration() class DioConfiguration { @Bean() Dio dio() { final dio = Dio(BaseOptions(baseUrl: 'https://api.example.com')); dio.interceptors.add(LogInterceptor(responseBody: true)); return dio; } } @ApiClient() abstract class ProductApi { @Get('/product/') Future getProduct(@Param() int id); @Post('/product') Future createProduct(@Body() ProductDTO product); @Put('/product/') Future updateProduct(@Param() int id, @Body() ProductDTO product); @Delete('/product/') Future deleteProduct(@Param() int id); @Get('/products') Future> getAllProducts(); } ``` ### Notes - All return objects and `@Body()` parameters must be annotated with `@DTO()`. - The `@ApiClient()` annotation simplifies API integration by generating the necessary code for making HTTP requests, internally using Dio. ``` -------------------------------- ### Dart Vaden CommandLineRunner Example Source: https://doc.vaden.dev/docs/basic-usage/warm_up An example of a CommandLineRunner component in Vaden, which runs based on command-line arguments. This allows for conditional startup behavior, such as running database migrations or seeding data based on arguments like 'migrate' or 'seed'. ```dart @Component() class AppRunner implements CommandLineRunner { @override Future run(List args) async { if (args.contains('migrate')) { await runMigrations(); } else if (args.contains('seed')) { await seedDatabase(); } } } ``` -------------------------------- ### YAML Configuration Example Source: https://doc.vaden.dev/docs/basic-usage/project_structure This YAML snippet illustrates a typical configuration for a Vaden application, specifying server details (port, host), database connection parameters, and OpenAPI metadata. These settings are automatically loaded into 'ApplicationSettings' and can be injected into services. ```yaml server: port: 8080 host: localhost database: provider: postgres postgres: host: localhost port: 5432 database: my_app username: user password: pass openapi: title: My API version: 1.0.0 description: Auto-generated by Vaden ``` -------------------------------- ### VadenApp Widget Entry Point Source: https://doc.vaden.dev/docs/full_stack_migration/frontend_application Example of how to use the generated VadenApp widget as the entry point for the Flutter application in the main function. ```dart void main() { runApp(VadenApp(child: const MyApp())); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), ), home: const MyHomePage(title: 'Flutter Demo Home Page'), ); } } ``` -------------------------------- ### Dart Server Entry Point Source: https://doc.vaden.dev/docs/basic-usage/project_structure This Dart code snippet demonstrates the main entry point for a Vaden application server. It initializes the Vaden application, sets up necessary configurations, and starts the HTTP server, logging the port it's listening on. It requires the 'vaden_application.dart' file generated by 'vaden_class_scanner'. ```dart import 'package:example/vaden_application.dart'; Future main(List args) async { final vaden = VadenApplicationImpl(); await vaden.setup(); final server = await vaden.run(args); print('Server listening on port ${server.port}'); } ``` -------------------------------- ### Enable OpenAPI Support Source: https://doc.vaden.dev/docs/addons/openapi To enable OpenAPI support, select the OpenAPI add-on during project creation using the Vaden Generator. This includes default configuration and controller examples. ```APIDOC ## Enabling OpenAPI Support When generating a new project using the Vaden Generator, make sure to select the OpenAPI add-on. This will create: * Default `openapi.dart` configuration under `lib/config/`. * Controller examples using `@Api()` and `@ApiResponse()`. **Note:** If the add-on is not enabled, the documentation system will not be available by default. ``` -------------------------------- ### Define Application Module Source: https://doc.vaden.dev/docs/full_stack_migration/frontend_application Example of defining the main application module using the @VadenModule annotation, listing its dependencies such as DomainModule and AppConfig. ```dart @VadenModule([DomainModule, AppConfig]) class AppModule {} ``` -------------------------------- ### Controller with Constructor Injection Source: https://doc.vaden.dev/docs/basic-usage/controller Illustrates a Controller that utilizes constructor injection to get dependencies like services. ```APIDOC ## GET /hello/ping ### Description This endpoint demonstrates a controller with constructor injection, where `HelloService` is automatically provided. ### Method GET ### Endpoint /hello/ping ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "request body" } ``` ### Response #### Success Response (200) - **message** (String) - The response from the HelloService. #### Response Example ```json { "message": "pong" } ``` ``` -------------------------------- ### Dart Vaden AppWarmup and AppRunner Configuration Source: https://doc.vaden.dev/docs/basic-usage/warm_up This snippet demonstrates how to configure initialization tasks in Vaden by creating classes that implement ApplicationRunner and CommandLineRunner. ApplicationRunner runs on app start, while CommandLineRunner runs based on provided arguments. Both are annotated with @Component. ```dart import 'package:vaden/vaden.dart'; @Component() class AppWarmup implements ApplicationRunner { @override Future run(VadenApplication app) async { print('ApplicationRunner'); } } @Component() class AppRunner implements CommandLineRunner { @override Future run(List args) async { print('My args: $args'); } } ``` -------------------------------- ### Manual Configuration with @Configuration and @Bean Source: https://doc.vaden.dev/docs/basic-usage/component The @Configuration() annotation combined with @Bean() methods allows for manual registration and configuration of components, especially useful for instances requiring parameters or complex setup. Beans can be synchronous or asynchronous. ```dart @Configuration() class AppConfiguration { @Bean() Logger logger() => Logger(); @Bean() Future api(ApplicationSettings settings) async { return ApiClient(baseUrl: settings['api']['url']); } } ``` -------------------------------- ### Documenting an Endpoint with @ApiOperation() and @ApiResponse() Source: https://doc.vaden.dev/docs/addons/openapi This example shows how to document a specific API endpoint using `@ApiOperation()` for summary and description, and `@ApiResponse()` to define the expected responses. This provides detailed information about the endpoint's behavior and outcomes. ```dart @ApiOperation(summary: 'Ping the server', description: 'Simple health check') @ApiResponse(200, description: 'Success') @Get('/ping') String ping() => 'pong'; ``` -------------------------------- ### Dart Controller with Vaden HTTP Routing Source: https://doc.vaden.dev/docs/Introduction/core-concepts Shows how to define an HTTP controller in Vaden using the @Controller() annotation for base routing and @Get() for specific endpoint mapping. It includes constructor injection for dependencies. ```dart @Controller('/auth') class AuthController { final AuthService authService; AuthController(this.authService); @Get('/ping') Response ping() => Response.ok(authService.ping()); } ``` -------------------------------- ### Define API Client with Flutter Vaden Source: https://doc.vaden.dev/docs/addons/flutter-vaden This Dart code shows how to define a RESTful API client using Flutter Vaden's `@ApiClient()` annotation. It includes examples of GET, POST, PUT, DELETE requests, parameter mapping, and body serialization, utilizing Dio internally. ```dart @Configuration() class DioConfiguration { @Bean() Dio dio() { final dio = Dio(BaseOptions(baseUrl: 'https://api.example.com')); dio.interceptors.add(LogInterceptor(responseBody: true)); return dio; } } @ApiClient() abstract class ProductApi { @Get('/product/') Future getProduct(@Param() int id); @Post('/product') Future createProduct(@Body() ProductDTO product); @Put('/product/') Future updateProduct(@Param() int id, @Body() ProductDTO product); @Delete('/product/') Future deleteProduct(@Param() int id); @Get('/products') Future> getAllProducts(); } ``` -------------------------------- ### Organize DTOs in a Domain Module (Dart) Source: https://doc.vaden.dev/docs/full_stack_migration/domain_package Shows how to group defined DTOs and other related classes into a Vaden module using the `@VadenModule` annotation. This makes the DTOs available for dependency injection and serialization across the application. The example includes `DefaultMessage`, `Todo`, and `TodoCreate` within the `DomainModule`. ```dart @VadenModule([ DefaultMessage, Todo, TodoCreate, ]) class DomainModule {} ``` -------------------------------- ### Todo Management API Source: https://doc.vaden.dev/docs/full_stack_migration/backend_application This API provides endpoints for managing todo items. It supports retrieving all todos, getting a specific todo by ID, and adding new todos. ```APIDOC ## GET /todos ### Description Retrieves a list of all todo items. ### Method GET ### Endpoint /todos ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **List** - A list of todo objects. #### Response Example ```json [ { "id": 1, "title": "Learn Vaden", "completed": false } ] ``` ## GET /todos/{id} ### Description Retrieves a specific todo item by its ID. ### Method GET ### Endpoint /todos/{id} ### Parameters #### Path Parameters - **id** (int) - Required - The unique identifier of the todo item. #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **Todo** - The todo object corresponding to the provided ID. #### Response Example ```json { "id": 1, "title": "Learn Vaden", "completed": false } ``` ## POST /todos ### Description Adds a new todo item. ### Method POST ### Endpoint /todos ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **TodoCreate** (object) - Required - The data for the new todo item. - **title** (string) - Required - The title of the todo. - **completed** (boolean) - Optional - The completion status of the todo. ### Request Example ```json { "title": "Implement API" } ``` ### Response #### Success Response (200) - **DefaultMessage** (object) - A success message. - **message** (string) - The success message. #### Response Example ```json { "message": "Todo added successfully" } ``` ``` -------------------------------- ### Install Flutter Vaden Dependencies Source: https://doc.vaden.dev/docs/addons/flutter-vaden This snippet shows how to add Flutter Vaden and its development dependencies to your project's pubspec.yaml file. It requires flutter_vaden and vaden_class_scanner for functionality, and build_runner for code generation. ```yaml dependencies: flutter_vaden: ^latest_version dev_dependencies: vaden_class_scanner: ^latest_version build_runner: ^latest_version ``` -------------------------------- ### HTTP Route Handlers with Controllers (Dart) Source: https://context7.com/context7/doc_vaden_dev/llms.txt Illustrates how to define HTTP endpoints using the `@Controller` and related annotations (`@Get`, `@Post`, `@Query`, `@Param`, `@Body`). This snippet covers automatic routing, parameter extraction, JSON body parsing, DTO serialization, and manual response handling. ```dart @Controller('/users') class UserController { final UserService userService; UserController(this.userService); // GET /users/all @Get('/all') String getAll() => 'Listing all users'; // GET /users/2 - Path parameter @Get('/') String getUser(@Param('id') int id) => 'User $id'; // GET /users/search?term=admin - Query parameter @Get('/search') String search(@Query('term') String term) => 'Searching $term'; // POST /users - JSON body with DTO @Post('/') UserDTO createUser(@Body() CreateUserRequest request) { return userService.create(request); } // Return DTO directly - auto-serialized to JSON @Get('/profile') UserProfile getProfile() => UserProfile('Alice', 'alice@example.com'); // Return Response for full control @Get('/custom') Future advanced() async { return Response.ok('Manual response', headers: {'X-Custom': 'value'}); } // WebSocket and advanced routing @Mount('/chat') Response handleWebSocket(Request request) { return websocketHandler(request); } } ``` -------------------------------- ### Vaden HTTP Method Handlers Source: https://doc.vaden.dev/docs/basic-usage/controller Vaden supports various HTTP method decorators to handle different HTTP request methods. These include @Get(), @Post(), @Put(), @Delete(), @Head(), and @Options(). ```dart @Get() @Post() @Put() @Delete() @Head() @Options() ``` -------------------------------- ### Documenting Security Scheme with @ApiSecurity() Source: https://doc.vaden.dev/docs/addons/openapi This example demonstrates how to document the security requirements for an endpoint using the `@ApiSecurity()` annotation. It specifies that the `/login` endpoint requires a 'bearer' token for authentication, which will be reflected in the OpenAPI specification. ```dart @ApiSecurity(['bearer']) @ApiResponse( 200, description: 'Successful login', content: ApiContent(type: 'application/json', schema: TokenResponse), ) @Post('/login') Future login(@Body() LoginRequest request) async { // Your login logic here } ``` -------------------------------- ### Todo REST Controller for API Endpoints Source: https://doc.vaden.dev/docs/full_stack_migration/backend_application Implements the REST controller for managing todos. It utilizes Vaden annotations like `@Controller`, `@Get`, `@Post` to define API endpoints and depends on `TodoRepository` for data operations. Handles request bodies (`@Body`) and parameter injection (`@Param`). ```dart @Api(tag: 'todos', description: 'Todo management API') @Controller('/todos') class TodoController { final TodoRepository _todoRepository; TodoController(this._todoRepository); @Get('/') Future> getAll() async { return _todoRepository.getAll(); } @Get('/') Future getById(@Param() int id) async { return _todoRepository.getById(id); } @Post('/') Future add(@Body() TodoCreate todo) async { await _todoRepository.add(todo); return DefaultMessage(message: 'Todo added successfully'); } // ... other endpoints } ``` -------------------------------- ### Define a Basic DTO with @DTO() Annotation Source: https://doc.vaden.dev/docs/basic-usage/dto Annotate a class with @DTO() to enable Vaden's automatic fromJson/toJson conversion, input validation, and OpenAPI schema generation. This example defines a simple DTO for credentials. ```dart import 'package:vaden/vaden.dart'; @DTO() class Credentials with Validator { final String username; final String password; const Credentials(this.username, this.password); } ``` -------------------------------- ### Define Abstract API Client Interface with Vaden Annotations Source: https://doc.vaden.dev/docs/full_stack_migration/frontend_application Defines an abstract class for API interactions using Vaden's `@ApiClient()` annotation. This serves as a contract for Vaden's code generator to create a concrete implementation. It supports standard HTTP methods like GET, POST, PUT, and DELETE, with support for request bodies, path parameters, and model serialization/deserialization, provided DTOs are properly annotated. ```dart import 'package:vaden/annotations.dart'; @ApiClient() abstract class TodoApi { @Get('/todos') Future> getAllTodos(); @Post('/todos') Future createTodo(@Body() TodoModel todo); @Put('/todos/{id}') Future updateTodo(@Param('id') String id, @Body() TodoModel todo); @Delete('/todos/{id}') Future deleteTodo(@Param('id') String id); } ``` -------------------------------- ### Configure HttpSecurity Rules for VadenSecurity Source: https://doc.vaden.dev/docs/addons/vaden-security This Dart code defines HttpSecurity rules for VadenSecurity, specifying access controls for different API endpoints using RequestMatcher and HTTP methods. It allows public access to '/auth/**' and '/docs/**', permits GET requests to '/public', restricts DELETE requests to '/admin/**' to users with the 'admin' role, and authenticates all other requests. ```dart import 'package:vaden/vaden.dart'; import 'package:vaden_security/vaden_security.dart'; @Configuration() class SecurityConfiguration { // ... other beans @Bean() HttpSecurity httpSecurity() { return HttpSecurity([ RequestMatcher('/auth/**').permitAll(), RequestMatcher('/docs/**').permitAll(), RequestMatcher('/public', HttpMethod.get).permitAll(), RequestMatcher('/admin/**', HttpMethod.delete).hasRole('admin'), AnyRequest().authenticated(), ]); } } ``` -------------------------------- ### Controller Basics Source: https://doc.vaden.dev/docs/basic-usage/controller Demonstrates how to define a Controller with a route prefix and associate methods with specific endpoints. ```APIDOC ## POST /api/users ### Description A `@Controller()` in Vaden defines a class that handles HTTP routes. The value passed to `@Controller('/path')` defines a route prefix applied to all methods in that class. ### Method POST ### Endpoint /users/all ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "request body" } ``` ### Response #### Success Response (200) - **message** (String) - A success message. #### Response Example ```json { "message": "Listing all users" } ``` ``` -------------------------------- ### Serving the Documentation Source: https://doc.vaden.dev/docs/addons/openapi Once enabled, Vaden automatically exposes the OpenAPI specification at `/docs/openapi.json` and the Swagger UI at `/docs/`. ```APIDOC ## Serving the Documentation Once enabled, your project will expose: * `/docs/openapi.json` – The raw OpenAPI spec. * `/docs/` – Swagger UI rendered via static resources. You don’t need to configure these manually — they’re included with the add-on and mounted automatically. ``` -------------------------------- ### Create Vaden Module with Custom Configuration Source: https://doc.vaden.dev/docs/basic-usage/vaden_module Shows how to create a Vaden module that extends `CommonModule` to include custom configuration logic during application startup. This allows for middleware registration and service manipulation via the dependency injector. ```typescript import { VadenModule, CommonModule } from '@vaden/core'; import { DartVadenApplication } from '@vaden/dart'; import { Pipeline } from '@vaden/pipeline'; import { GlobalSecurityMiddleware } from './middlewares/security.middleware'; import { UserDetails } from './user.details'; import { Tokenization } from './tokenization'; import { VadenSecurityError } from './security.error'; import { AuthController } from './auth.controller'; // This module imports other necessary components. @VadenModule([ UserDetails, Tokenization, VadenSecurityError, AuthController, ]) class VadenSecurity extends CommonModule { // The register method is called by Vaden during app startup. @override FutureOr register(DartVadenApplication app) { final injector = app.injector; // Get existing services from the injector var pipeline = injector.get(); // Add custom middleware pipeline = pipeline.addVadenMiddleware(GlobalSecurityMiddleware(...)); // Replace the old instance with the new one injector.replaceInstance(pipeline); // ... other configuration logic } } ``` -------------------------------- ### Dependency Injection Components Source: https://context7.com/context7/doc_vaden_dev/llms.txt Demonstrates the usage of Vaden's dependency injection system, including @Component, @Service, and @Repository annotations, along with scope management for singletons and instances. ```APIDOC ## Component: Logger ### Description A basic component for logging messages. ### Annotation `@Component()` ### Usage Can be injected into other components, services, or controllers. ## Service: UserService ### Description Provides business logic for user-related operations, injecting UserRepository and Logger. ### Annotation `@Service()` ### Dependencies - **UserRepository**: For data access. - **Logger**: For logging operations. ### Methods - `getUsers()`: Logs and retrieves all users. - `createUser(String username)`: Logs and saves a new user. ## Repository: UserRepository ### Description Handles data access operations for users. ### Annotation `@Repository()` ### Methods - `findAllUsers()`: Returns a list of all users. - `save(String username)`: Simulates saving a user to a data source. ## Scoped Services ### DatabaseService - **Annotation**: `@Scope(BindType.singleton)` - **Description**: Ensures only a single instance of DatabaseService is created and reused throughout the application. ### Counter - **Annotation**: `@Scope(BindType.instance)` - **Description**: Creates a new instance of Counter each time it is injected. ``` -------------------------------- ### Dependency Injection with Components, Services, and Repositories (Dart) Source: https://context7.com/context7/doc_vaden_dev/llms.txt Shows how to define and inject components, services, and repositories using Vaden's annotations (`@Component`, `@Service`, `@Repository`). It demonstrates constructor injection, dependency management, and scope management (`@Scope` with `BindType.singleton` and `BindType.instance`). ```dart // Base component @Component() class Logger { void log(String message) => print('[LOG] $message'); } // Business logic service @Service() class UserService { final UserRepository repository; final Logger logger; UserService(this.repository, this.logger); List getUsers() { logger.log('Fetching all users'); return repository.findAllUsers(); } void createUser(String username) { logger.log('Creating user: $username'); repository.save(username); } } // Data access layer @Repository() class UserRepository { List findAllUsers() => ['Alice', 'Bob', 'Charlie']; void save(String username) { // Save to database } } // Singleton vs instance scope @Scope(BindType.singleton) class DatabaseService { void connect() => print('Connected'); } @Scope(BindType.instance) // New instance per injection class Counter { int count = 0; } ``` -------------------------------- ### Create Simple Vaden Module Source: https://doc.vaden.dev/docs/basic-usage/vaden_module Demonstrates the creation of a root application module in Vaden by annotating a class with `@VadenModule` and importing other modules. This module acts as a container for other functionalities. ```typescript import { VadenModule } from '@vaden/core'; import { DomainModule } from './domain.module'; import { VadenSecurity } from './security.module'; @VadenModule([ DomainModule, VadenSecurity // Imports all providers and configurations from VadenSecurity ]) class AppModule {} ``` -------------------------------- ### Modular Application Architecture with VadenModule (Dart) Source: https://context7.com/context7/doc_vaden_dev/llms.txt Demonstrates how to structure a Vaden application using `VadenModule`. It shows a simple root module importing others and an advanced module with custom configuration, including modifying the middleware pipeline and registering additional services. ```dart // Simple root module importing other modules @VadenModule([ DomainModule, VadenSecurity, ]) class AppModule {} // Advanced module with custom configuration @VadenModule([ UserDetails, Tokenization, VadenSecurityError, AuthController, ]) class VadenSecurity extends CommonModule { @override FutureOr register(DartVadenApplication app) { final injector = app.injector; // Modify pipeline with custom middleware var pipeline = injector.get(); pipeline = pipeline.addVadenMiddleware(GlobalSecurityMiddleware()); injector.replaceInstance(pipeline); // Register additional services // Configure OpenAPI specs, etc. } } ``` -------------------------------- ### Dart Configuration for Application Settings and Database Source: https://context7.com/context7/doc_vaden_dev/llms.txt This Dart code demonstrates how to define application settings and configure a database connection using Vaden's annotation-driven architecture. It loads settings from 'application.yaml' and establishes a PostgreSQL connection based on the provided configuration. ```dart @Configuration() class AppConfiguration { @Bean() ApplicationSettings settings() { return ApplicationSettings.load('application.yaml'); } @Bean() Future database(ApplicationSettings settings) async { final config = settings['database']['postgres']; return DatabaseConnection( host: config['host'], port: config['port'], database: config['database'], username: config['username'], password: config['password'], ); } } ``` -------------------------------- ### Define Component Scope with @Scope() Annotation Source: https://doc.vaden.dev/docs/basic-usage/dependencies-injector The @Scope() annotation registers components within a dependency injection container. It accepts a BindType enum to control instance behavior. Default is lazySingleton. Examples show singleton and instance BindTypes. ```dart @Scope(BindType.singleton) class DatabaseService { void connect() => print('Connected'); } @Scope(BindType.instance) class Counter { int count = 0; } ``` ```dart @Serices() @Scope() class AuthService {} ``` -------------------------------- ### Dart Configuration and Bean Registration Source: https://context7.com/context7/doc_vaden_dev/llms.txt Configures beans with custom initialization logic and injects environment settings. Supports simple beans, asynchronous beans with dependencies, and database connections. Loads application settings from YAML. ```dart @Configuration() class AppConfiguration { // Simple bean @Bean() Logger logger() => Logger(); // Async bean with dependencies @Bean() Future apiClient(ApplicationSettings settings) async { final baseUrl = settings['api']['url']; return ApiClient(baseUrl: baseUrl); } // Database connection with settings @Bean() Future database(ApplicationSettings settings) async { final config = settings['database']['postgres']; return DatabaseConnection( host: config['host'], port: config['port'], database: config['database'], username: config['username'], password: config['password'], ); } // Load application settings from YAML @Bean() ApplicationSettings settings() { return ApplicationSettings.load('application.yaml'); } } ``` -------------------------------- ### Implement Validator Mixin for DTO Validation Source: https://doc.vaden.dev/docs/basic-usage/dto DTOs can implement the Validator mixin to enforce data criteria. If validation fails, Vaden automatically returns a 400 Bad Request response with validation errors. This example ensures username is not empty and password has a minimum length. ```dart import 'package:vaden/vaden.dart'; @DTO() class Credentials with Validator { final String username; final String password; const Credentials(this.username, this.password); @override LucidValidator validate(ValidatorBuilder builder) { return builder .ruleFor((c) => c.username, key: 'username').notEmpty() .ruleFor((c) => c.password, key: 'password').minLength(6); } } ``` -------------------------------- ### Dart Dependency Injection with Vaden Annotations Source: https://doc.vaden.dev/docs/Introduction/core-concepts Illustrates Vaden's dependency injection system using annotations like @Configuration(), @Bean(), @Service(), and @Component(). It shows how to define injectable classes and configuration beans. ```dart @Configuration() class AppConfiguration { @Bean() Future storage(ApplicationSettings settings) { return Storage.createStorageService(settings); } @Bean() Pipeline globalMiddleware() { return Pipeline()..addMiddleware(logRequests()); } } ``` -------------------------------- ### Generate VadenApp Class and Run Application Source: https://doc.vaden.dev/docs/addons/flutter-vaden This Dart code demonstrates how to run the build_runner to generate the VadenApp class and subsequently use it within the runApp method to bootstrap the Flutter application. This integrates Vaden's dependency injection system. ```dart void main() { runApp(VadenApp()); } ``` -------------------------------- ### Documenting Endpoints Source: https://doc.vaden.dev/docs/addons/openapi Describe individual routes using `@ApiOperation()` and `@ApiResponse()` annotations. You can also specify return schemas using DTOs. ```APIDOC ## Documenting Endpoints Each route can be further described using `@ApiOperation()` and one or more `@ApiResponse()` annotations: ```dart @ApiOperation(summary: 'Ping the server', description: 'Simple health check') @ApiResponse(200, description: 'Success') @Get('/ping') String ping() => 'pong'; ``` You can also specify a return schema using a DTO: ```dart @ApiResponse( 200, description: 'Successful login', content: ApiContent(type: 'application/json', schema: TokenResponse), ) ``` ``` -------------------------------- ### Configure Global Middlewares with Pipeline Source: https://doc.vaden.dev/docs/basic-usage/middleware Defines global middlewares that apply to all incoming requests using the `Pipeline` class within an `@Configuration` class. It allows adding Shelf middlewares via `addMiddleware` and Vaden-compatible middlewares via `addVadenMiddleware`. These are executed before controller logic. ```typescript @Configuration() class AppConfiguration { @Bean() ApplicationSettings settings() { return ApplicationSettings.load('application.yaml'); } @Bean() Pipeline globalMiddleware(ApplicationSettings settings) { return Pipeline() .addMiddleware(cors(allowedOrigins: ['*'])) .addVadenMiddleware(EnforceJsonContentType()) .addMiddleware(logRequests()); } } ``` -------------------------------- ### User Controller API Source: https://context7.com/context7/doc_vaden_dev/llms.txt Defines HTTP endpoints for user management, including listing users, retrieving a specific user by ID, searching users by a term, creating new users via a DTO, and returning user profiles. It also shows how to return custom responses and mount WebSocket handlers. ```APIDOC ## GET /users/all ### Description Retrieves a list of all users. ### Method GET ### Endpoint /users/all ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **String**: A message indicating the action. #### Response Example ```json "Listing all users" ``` ## GET /users/ ### Description Retrieves a specific user by their ID. ### Method GET ### Endpoint /users/ ### Parameters #### Path Parameters - **id** (int) - Required - The ID of the user to retrieve. #### Query Parameters None #### Request Body None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **String**: A message indicating the user ID. #### Response Example ```json "User 2" ``` ## GET /users/search?term=admin ### Description Searches for users based on a given term. ### Method GET ### Endpoint /users/search ### Parameters #### Path Parameters None #### Query Parameters - **term** (String) - Required - The search term. #### Request Body None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **String**: A message indicating the search term. #### Response Example ```json "Searching admin" ``` ## POST /users ### Description Creates a new user with the provided details. ### Method POST ### Endpoint /users ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **request** (CreateUserRequest DTO) - Required - The data for the new user. ### Request Example ```json { "example": "CreateUserRequest object" } ``` ### Response #### Success Response (200) - **UserDTO**: The created user data. #### Response Example ```json { "example": "UserDTO object" } ``` ## GET /users/profile ### Description Retrieves the profile information for the current user. ### Method GET ### Endpoint /users/profile ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **UserProfile**: The user's profile information. #### Response Example ```json { "name": "Alice", "email": "alice@example.com" } ``` ## GET /users/custom ### Description Provides a custom response, demonstrating manual control over the response object. ### Method GET ### Endpoint /users/custom ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **Response**: A manually constructed HTTP response. #### Response Example ```json { "status": 200, "body": "Manual response", "headers": { "X-Custom": "value" } } ``` ## MOUNT /users/chat ### Description Mounts a WebSocket handler for chat functionality. ### Method MOUNT (typically used for WebSockets or advanced routing) ### Endpoint /users/chat ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **Response**: The response from the WebSocket handler. #### Response Example ```json { "example": "WebSocket response" } ``` ``` -------------------------------- ### Controller Return Types Source: https://doc.vaden.dev/docs/basic-usage/controller Explains the various return types a controller method can have and how Vaden handles them. ```APIDOC ## GET /text ### Description Returns a plain text string. ### Method GET ### Endpoint /text ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "request body" } ``` ### Response #### Success Response (200) - **Body** (String) - Plain text. #### Response Example ```json { "body": "Hello World" } ``` ``` ```APIDOC ## GET /json ### Description Returns a JSON object serialized from a DTO. ### Method GET ### Endpoint /json ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "request body" } ``` ### Response #### Success Response (200) - **user** (UserDTO) - The user object. #### Response Example ```json { "user": { "username": "admin" } } ``` ``` ```APIDOC ## GET /list ### Description Returns a JSON array serialized from a list of DTOs. ### Method GET ### Endpoint /list ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "request body" } ``` ### Response #### Success Response (200) - **users** (List) - A list of user objects. #### Response Example ```json { "users": [ { "username": "a" }, { "username": "b" } ] } ``` ``` ```APIDOC ## GET /custom ### Description Returns a custom `Response` object, allowing for manual control over the response. ### Method GET ### Endpoint /custom ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "request body" } ``` ### Response #### Success Response (200) - **Body** (String) - Manual response body. #### Response Example ```json { "body": "Manual" } ``` ``` -------------------------------- ### HTTP Method Handlers Source: https://doc.vaden.dev/docs/basic-usage/controller Lists the supported HTTP method decorators available in Vaden. ```APIDOC ## HTTP Methods ### Description Vaden supports the following HTTP method decorators for handling different request types: - `@Get()` - `@Post()` - `@Put()` - `@Delete()` - `@Head()` - `@Options()` ### Method Any ### Endpoint Any ### Parameters None ### Request Example ```json { "example": "request body" } ``` ### Response #### Success Response (200) - **response** (any) - The result of the handled request. #### Response Example ```json { "response": "Handled request" } ``` ``` -------------------------------- ### Abstract Todo Repository Contract Source: https://doc.vaden.dev/docs/full_stack_migration/backend_application Defines the abstract contract for the TodoRepository. It specifies methods for fetching, retrieving by ID, and adding todos, serving as a blueprint for concrete implementations. No external dependencies are explicitly shown here. ```dart abstract class TodoRepository { Future> getAll(); Future getById(int id); Future add(TodoCreate todo); // ... other methods } ``` -------------------------------- ### @Param and @Query Source: https://doc.vaden.dev/docs/basic-usage/controller Shows how to extract data from URL path parameters and query strings using @Param and @Query decorators. ```APIDOC ## GET /user/{id} ### Description Retrieves a user by their ID from the path parameter. ### Method GET ### Endpoint /user/ ### Parameters #### Path Parameters - **id** (int) - Required - The ID of the user. #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "request body" } ``` ### Response #### Success Response (200) - **message** (String) - Confirmation message with the user ID. #### Response Example ```json { "message": "User 2" } ``` ``` ```APIDOC ## GET /search ### Description Performs a search based on a query term. ### Method GET ### Endpoint /search ### Parameters #### Path Parameters None #### Query Parameters - **term** (String) - Required - The search term. #### Request Body None ### Request Example ```json { "example": "request body" } ``` ### Response #### Success Response (200) - **message** (String) - Confirmation message with the search term. #### Response Example ```json { "message": "Searching Text" } ``` ``` ```APIDOC ## GET /product/{id} ### Description Retrieves a product by its ID, demonstrating omitting the parameter name in the annotation. ### Method GET ### Endpoint /product/ ### Parameters #### Path Parameters - **id** (String) - Required - The ID of the product. #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "request body" } ``` ### Response #### Success Response (200) - **message** (String) - Confirmation message with the product ID. #### Response Example ```json { "message": "Product 123" } ``` ``` ```APIDOC ## GET /search/optional ### Description Performs a search, where the search term is an optional query parameter. ### Method GET ### Endpoint /search/optional ### Parameters #### Path Parameters None #### Query Parameters - **term** (String?) - Optional - The search term. #### Request Body None ### Request Example ```json { "example": "request body" } ``` ### Response #### Success Response (200) - **message** (String) - Confirmation message with the search term or indicating no term was provided. #### Response Example ```json { "message": "Searching: OptionalTerm" or "No search term provided." } ``` ``` -------------------------------- ### Configure Dio HTTP Client Source: https://doc.vaden.dev/docs/full_stack_migration/frontend_application Configuration class using @Configuration and @Bean annotations to provide and set up the Dio HTTP client, including base URL and interceptors. ```dart @Configuration() class DioConfiguration { @Bean() Dio dio() { final dio = Dio(BaseOptions(baseUrl: 'http://localhost:8080/api')); dio.interceptors.add(LogInterceptor(responseBody: true)); // Example interceptor return dio; } } ``` -------------------------------- ### Run Vaden Code Generator Source: https://doc.vaden.dev/docs/full_stack_migration/frontend_application Command to execute the Vaden code generator using dart run build_runner build, which generates necessary files for dependency injection and API clients. ```bash dart run build_runner build ``` -------------------------------- ### Concrete Todo Repository Implementation with Drift ORM Source: https://doc.vaden.dev/docs/full_stack_migration/backend_application Provides a concrete implementation of the TodoRepository using the Drift ORM for database operations. It depends on `AppDatabase` and maps database results to `Todo` objects. This implementation handles fetching all todos from the database. ```dart @Repository() class TodoRepositoryImpl implements TodoRepository { final AppDatabase _appDatabase; TodoRepositoryImpl(this._appDatabase); @override Future> getAll() async { final tables = await _appDatabase.select(_appDatabase.todoTable).get(); return tables.map(_mapToTodo).toList(); } // ... other implementations } ``` -------------------------------- ### Wildcard Routing with @Mount Source: https://doc.vaden.dev/docs/basic-usage/controller Illustrates the use of the @Mount() decorator for wildcard routing, suitable for advanced scenarios like WebSockets. ```APIDOC ## MOUNT /socket/chat ### Description Handles requests for wildcard endpoints using `@Mount()`, useful for WebSockets or proxy handlers. ### Method MOUNT ### Endpoint /socket/chat ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "request body" } ``` ### Response #### Success Response (200) - **response** (Response) - The result of the websocket or proxy handler. #### Response Example ```json { "response": "WebSocket connection established" } ``` ``` -------------------------------- ### Documenting Security Schemes Source: https://doc.vaden.dev/docs/addons/openapi Use the `@ApiSecurity()` annotation to document security schemes, such as Bearer token authentication, for your endpoints. ```APIDOC ## Security To document security schemes, you can use the `@ApiSecurity()` annotation. This allows you to specify authentication methods for your endpoints. ```dart @ApiSecurity(['bearer']) @ApiResponse( 200, description: 'Successful login', content: ApiContent(type: 'application/json', schema: TokenResponse), ) @Post('/login') Future login(@Body() LoginRequest request) async { // Your login logic here } ``` This will add a security requirement to the generated OpenAPI spec, indicating that the endpoint requires a Bearer token for authentication. ```