### Complete Workflow Example: Setup and Daily Usage Source: https://dcc-bs.github.io/documentation/howto/encrypt-env-files Provides a step-by-step example of the initial setup process, including creating .env files, encrypting them, storing keys in ProtonPass, and configuring `.gitignore`. It also demonstrates daily usage with the created aliases. ```bash # Initial Setup: # 1. Login to ProtonPass CLI pass-cli login # 2. Create your .env file echo "DATABASE_URL=postgresql://user:pass@localhost/db" > .env echo "API_KEY=secret-key-123" >> .env # 3. Encrypt the file dotenvx encrypt .env # 4. Store the encryption key in ProtonPass (manually or via CLI) # 5. Create .env.keys file echo "DOTENV_PRIVATE_KEY=pass://MyVault/DOTENV_KEY/Secret" > .env.keys # 6. Add .env and .env.keys to .gitignore echo ".env" >> .gitignore echo ".env.keys" >> .gitignore # Daily Usage: # Run your application with encrypted variables renv bun dev # Update an environment variable envx set API_KEY "new-secret-key-456" # View a decrypted value envx get API_KEY ``` -------------------------------- ### Local Development Setup with Bun Source: https://dcc-bs.github.io/documentation/nuxt-layers/index Commands to set up and develop Nuxt layers locally using Bun as the monorepo workspace manager. This includes cloning the repository, installing dependencies, and navigating to individual layers for development. ```sh # Clone the repository git clone https://github.com/DCC-BS/nuxt-layers.git # Install dependencies bun install # Work on individual layers cd auth && bun dev ``` -------------------------------- ### Install Dependencies and Prepare Nuxt Source: https://dcc-bs.github.io/documentation/nuxt-layers/logger After configuring the logger layer, install the necessary project dependencies using 'bun install'. Then, run 'bun dev:prepare' to prepare the Nuxt development environment, ensuring all configurations and layers are correctly set up. ```sh bun i bun dev:prepare ``` -------------------------------- ### Example .env File for Configuration (Bash) Source: https://dcc-bs.github.io/documentation/backend-common/config Provides an example of a `.env.example` file used for local development and configuration. This file lists common environment variables with placeholder values, serving as a template for developers to set up their local environment. ```bash # .env.example CLIENT_URL=http://localhost:3000 HMAC_SECRET=your-secret-here OPENAI_API_KEY=sk-your-key-here LLM_MODEL=gpt-4o OPTIMIZER_MODEL=gpt-4o-mini DEBUG_MODE=false ``` -------------------------------- ### Kubernetes Startup Probe Configuration (YAML) Source: https://dcc-bs.github.io/documentation/nuxt-layers/health_check Example Kubernetes configuration for a startup probe. This YAML snippet outlines how Kubernetes verifies that the application has successfully started, defining the endpoint, port, and retry parameters. ```yaml startupProbe: httpGet: path: api/health/startup port: 3000 initialDelaySeconds: 0 periodSeconds: 5 timeoutSeconds: 3 failureThreshold: 30 successThreshold: 1 ``` -------------------------------- ### Install dcc-backend-common Package Source: https://dcc-bs.github.io/documentation/backend-common/usage_tracking Installs the 'ddc-backend-common' package using the 'uv' package manager. This package includes the usage tracking module. ```bash uv add ddc-backend-common ``` -------------------------------- ### Configure Logger Implementation (Pino) Source: https://dcc-bs.github.io/documentation/nuxt-layers/logger This example demonstrates how to configure the logger layer to use the Pino implementation for production environments. It involves setting the `LOGGER_LAYER_URI` environment variable. For Pino, you also need to install `pino` and `pino-pretty` as development dependencies. ```bash # For production (Pino): LOGGER_LAYER_URI=github:DCC-BS/nuxt-layers/pino-logger # Install dependencies: bun add pino bun add -D pino-pretty ``` -------------------------------- ### Install common-ui.bs.js Library Source: https://dcc-bs.github.io/documentation/howto/changelogs Installs the `common-ui.bs.js` library using various package managers. This library is essential for the Changelogs component functionality. ```bash # bun bun add @dcc-bs/common-ui.bs.js # npm npm install @dcc-bs/common-ui.bs.js # pnpm pnpm add @dcc-bs/common-ui.bs.js # yarn yarn add @dcc-bs/common-ui.bs.js ``` -------------------------------- ### Quick Start: FastAPI Error Handling Setup and Usage Source: https://dcc-bs.github.io/documentation/backend-common/error_handler Demonstrates how to set up and use the error handling module in a FastAPI application. It includes registering the error handler in the application's lifespan and raising custom API errors. ```python from contextlib import asynccontextmanager from fastapi import FastAPI from dcc_backend_common.fastapi_error_handling import ( ApiErrorException, ApiErrorCodes, api_error_exception, inject_api_error_handler, ) @asynccontextmanager async def lifespan(app: FastAPI): """Application lifespan handler.""" inject_api_error_handler(app) # Register error handler yield app = FastAPI(lifespan=lifespan) @app.get("/users/{user_id}") async def get_user(user_id: int): if user_id < 1: raise api_error_exception( errorId=ApiErrorCodes.INVALID_REQUEST, status=400, debugMessage="User ID must be positive", ) return {"id": user_id, "name": "John Doe"} ``` -------------------------------- ### Kubernetes Deployment Configuration Source: https://dcc-bs.github.io/documentation/backend-common/probes Example Kubernetes deployment configuration for a service named 'my-service'. It includes container definitions, port configurations, and liveness, readiness, and startup probes with specific thresholds and delays. ```yaml apiVersion: apps/v1 kind: Deployment metadata: name: my-service spec: template: spec: containers: - name: app image: my-service:latest ports: - containerPort: 8000 livenessProbe: httpGet: path: /health/liveness port: 8000 initialDelaySeconds: 5 periodSeconds: 10 failureThreshold: 3 readinessProbe: httpGet: path: /health/readiness port: 8000 initialDelaySeconds: 5 periodSeconds: 5 failureThreshold: 3 startupProbe: httpGet: path: /health/startup port: 8000 initialDelaySeconds: 0 periodSeconds: 5 failureThreshold: 30 # Allow 2.5 minutes for slow startups ``` -------------------------------- ### Hadolint Installation and Usage Source: https://dcc-bs.github.io/documentation/docker Provides instructions for installing and using Hadolint, a Dockerfile linter. It covers installation methods for Windows and Ubuntu, and demonstrates basic CLI usage for local linting. ```bash # Windows: scoop install hadolint # Ubuntu: sudo wget -qO /usr/local/bin/hadolint https://github.com/hadolint/hadolint/releases/latest/download/hadolint-Linux-x86_64 sudo chmod a+x /usr/local/bin/hadolint # Usage: hadolint Dockerfile ``` -------------------------------- ### Install dotenvx and ProtonPass CLI Source: https://dcc-bs.github.io/documentation/howto/encrypt-env-files Installs the necessary command-line tools for encrypting environment files and managing secrets with ProtonPass. Ensure Node.js is installed for npm. ```bash # Install dotenvx npm install -g @dotenvx/dotenvx # Install ProtonPass CLI # See: https://protonpass.github.io/pass-cli/ ``` -------------------------------- ### Docker Compose 'extends' Pattern Example Source: https://dcc-bs.github.io/documentation/docker This example demonstrates the 'extends' pattern in Docker Compose for modularity. It shows how to define base service configurations in one file (`services.compose.yml`) and extend them in development (`docker-compose.dev.yml`) and production (`docker-compose.yml`) configurations, reducing duplication. ```yaml # docker-compose.dev.yml services: app-backend: extends: file: ./docker/services.compose.yml service: app-backend environment: - DEBUG=true ports: - "8000:8000" llm: extends: file: ./docker/services.compose.yml service: llm ``` ```yaml # docker-compose.yml networks: app-network: driver: bridge services: nginx: extends: file: ./docker/services.compose.yml service: nginx depends_on: - app-frontend networks: - app-network llm: extends: file: ./docker/services.compose.yml service: llm networks: - app-network app-backend: extends: file: ./docker/services.compose.yml service: app-backend networks: - app-network app-frontend: extends: file: ./docker/services.compose.yml service: app-frontend networks: - app-network ``` -------------------------------- ### Configure Authentication Layer URI Example Source: https://dcc-bs.github.io/documentation/nuxt-layers/auth Provides examples of how to set the 'AUTH_LAYER_URI' environment variable to specify different authentication implementations, including Azure AD, no authentication, and a local custom layer. ```bash # Use Azure AD authentication AUTH_LAYER_URI=github:DCC-BS/nuxt-layers/azure-auth # Use no authentication AUTH_LAYER_URI=github:DCC-BS/nuxt-layers/no-auth # Use local layer (for development) AUTH_LAYER_URI=./layers/custom-auth ``` -------------------------------- ### Example Changelog Markdown File Source: https://dcc-bs.github.io/documentation/howto/changelogs Demonstrates the structure of a changelog file using Markdown format with frontmatter. It includes essential metadata like title, version, and publication date, followed by release notes. ```markdown --- title: "Version 1.1.0" version: "1.1.0" published_at: "2024-01-15" --- ## New Features - Added new changelog component - Improved performance - Enhanced user interface ## Bug Fixes - Fixed memory leak issue - Resolved login timeout problem ## Breaking Changes - Deprecated old API endpoints ``` -------------------------------- ### API Route File Naming Convention in TXT Source: https://dcc-bs.github.io/documentation/nuxt-layers/backend_communication Provides an example of a descriptive file naming convention for API routes within a server structure. This convention helps in organizing API endpoints, making it clear which HTTP method and path each file corresponds to (e.g., index.get.ts for GET /api/users). ```txt server/api/ ├── users/ │ ├── index.get.ts # GET /api/users │ ├── index.post.ts # POST /api/users │ └── [id].get.ts # GET /api/users/:id └── orders/ └── index.get.ts # GET /api/orders ``` -------------------------------- ### Configure Backend Communication Layer Environment Variables Source: https://dcc-bs.github.io/documentation/nuxt-layers/backend_communication This example shows how to set up the necessary environment variables for the backend communication layer in a `.env` file. `API_URL` is mandatory, while `LOGGER_LAYER_URI` and `DUMMY` are optional. ```bash # .env API_URL=https://api.example.com LOGGER_LAYER_URI=github:DCC-BS/nuxt-layers/pino-logger DUMMY=true ``` -------------------------------- ### Google-style Docstring Example in Python Source: https://dcc-bs.github.io/documentation/coding/python Demonstrates the correct implementation of a Google-style docstring for a Python function. It includes a summary line, detailed arguments, return values, raised exceptions, and an example usage. This adheres to the project's standard for documenting modules, classes, and functions. ```python # ✅ Right - Google-style docstring def translate_text( text: str, source_lang: str, target_lang: str, *, preserve_formatting: bool = True, ) -> TranslationResult: """Translate text from source language to target language. Uses the configured LLM to perform translation while optionally preserving the original formatting. Args: text: The text to translate. source_lang: ISO 639-1 language code of the source language. target_lang: ISO 639-1 language code of the target language. preserve_formatting: Whether to maintain original text formatting. Returns: A TranslationResult containing the translated text and metadata. Raises: ValueError: If source_lang or target_lang is not a valid language code. TranslationError: If the translation service fails. Example: >>> result = translate_text("Hello", "en", "de") >>> print(result.text) "Hallo" """ pass ``` -------------------------------- ### Use Structured Logging in Python Source: https://dcc-bs.github.io/documentation/backend-common This Python example illustrates the use of structured logging with `dcc-backend-common`. It emphasizes logging key-value pairs for better readability and machine-parseability, rather than using string interpolation. ```python logger.info("User created", user_id=user.id, email=user.email) ``` -------------------------------- ### Example Server Response for Changelogs (JSON) Source: https://dcc-bs.github.io/documentation/user-interface/components/changelogs Illustrates the expected JSON structure for the server response when fetching changelog data. ```json [ { "title": "Version 1.1.0", "version": "1.1.0", "published_at": "2024-01-15T10:00:00Z", "content": "## New Features\n- Feature 1\n- Feature 2" }, { "title": "Version 1.0.0", "version": "1.0.0", "published_at": "2024-01-01T10:00:00Z", "content": "## Initial Release\n- First version" } ] ``` -------------------------------- ### Backend Handler Execution Flow Example Source: https://dcc-bs.github.io/documentation/nuxt-layers/backend_communication Demonstrates the execution flow of a handler built with backendHandlerBuilder. It shows how methods like withMethod, withBodyProvider, extendFetchOptions, and postMap are applied sequentially to process a request and transform the response. ```typescript export default backendHandlerBuilder() .withMethod('POST') .withBodyProvider(async (event) => { const body = await readBody(event) return { ...body, timestamp: Date.now() } }) .extendFetchOptions(async (options) => ({ ...options, headers: { ...options.headers, 'X-Custom': 'value' } })) .postMap(async (response) => ({ success: true, data: response })) .build('/users') // ...executes in this order when called: // 1. Build URL: Parse '/users' // 2. withBodyProvider: Read and transform body // 3. extendFetchOptions: Add custom headers // 4. Fetch: Make POST request to backend // 5. postMap: Transform response // 6. Return: { success: true, data: {...} } ``` -------------------------------- ### Backend Communication Layer API Documentation Source: https://dcc-bs.github.io/documentation/nuxt-layers/backend_communication Documentation for the backend communication layer, including installation, basic usage, configuration, and builder API. ```APIDOC ## Backend Communication Layer API Documentation ### Description This documentation covers the Backend Communication Layer for Nuxt.js, which provides utilities for building type-safe and configurable API handlers in Nuxt server routes. It simplifies communication between your Nuxt application and backend APIs with a fluent builder interface. ### Features * **Fluent Builder API**: Chain methods to configure your handlers. * **Type Safety**: Full TypeScript support with automatic type inference. * **Request/Response Transformation**: Custom body providers and response transformers. * **Flexible Fetch Options**: Extend and customize HTTP requests. * **Error Handling**: Built-in error transformation and handling with proper HTTP status codes. * **Integration Ready**: Works seamlessly with auth layers. * **Method Inheritance**: Automatically inherits HTTP method from incoming requests. * **Dummy Data Mode**: Mock API responses for development and testing. * **Dynamic Path Construction**: Build URLs dynamically using router and query parameters. ### Installation Add the layer to your `nuxt.config.ts`: ```typescript export default defineNuxtConfig({ extends: [ ['github:DCC-BS/nuxt-layers/backend_communication', { install: true }] ] }) ``` ### Basic Usage Create a simple pass-through API handler: ```typescript // server/api/users.get.ts import { backendHandlerBuilder } from '#backend_communication' export default backendHandlerBuilder() .build('/users') ``` This creates a handler that forwards requests to `${API_URL}/users`. By default, it inherits the HTTP method from the incoming request (GET in this case). ### Configuration Environment Variables: | Variable | Required | Description | Example | | ------------------ | -------- | ----------------------------------------- | ----------------------- | | `API_URL` | Yes | Base URL of your backend API | `https://api.example.com` | | `LOGGER_LAYER_URI` | No | URI to logger implementation layer | `github:DCC-BS/nuxt-layers/pino-logger` | | `DUMMY` | No | Enable dummy data mode (set to "true") | `true` or empty string | Example `.env` file: ```bash API_URL=https://api.example.com LOGGER_LAYER_URI=github:DCC-BS/nuxt-layers/pino-logger DUMMY=true ``` Runtime Configuration in `nuxt.config.ts`: ```typescript export default defineNuxtConfig({ runtimeConfig: { apiUrl: process.env.API_URL, useDummyData: process.env.DUMMY || "", }, }); ``` | Option | Type | Default | Description | | -------------- | ------ | ------- | --------------------------------------------------------------------------- | | `apiUrl` | string | - | Base URL of backend API | | `useDummyData` | string | `""` | Set to `"true"` to use dummy data fetcher instead of real backend requests. | When `useDummyData` is set to `"true"`, all backend handlers will use the dummy fetcher (if configured) instead of making real HTTP requests. This is useful for frontend development without a running backend, testing, debugging, and offline development. ### Builder API The `backendHandlerBuilder()` provides a chainable interface for configuring handlers. All methods return a new builder instance, making them immutable and composable. #### Immutability and Composition Each builder method returns a **new** builder instance rather than modifying the existing one. This allows you to create variations: ```typescript const baseBuilder = backendHandlerBuilder() .extendFetchOptions(async (options) => ({ ...options, headers: { ...options.headers, 'X-API-Version': 'v1' } })) // Create variations without affecting the base const getUserHandler = baseBuilder.build('/users') const postUserHandler = baseBuilder .withMethod('POST') .withBodyProvider(async (event) => readBody(event)) .build('/users') ``` #### Type Safety and Method Availability The builder maintains type safety by dynamically adjusting which methods are available based on the current builder state. This prevents invalid configurations and ensures type correctness throughout the chain. ``` -------------------------------- ### GET /users/{user_id} Source: https://dcc-bs.github.io/documentation/backend-common/error_handler Example endpoint demonstrating the usage of `api_error_exception` to raise specific API errors based on request parameters. ```APIDOC ## GET /users/{user_id} ### Description Retrieves user information by ID. Raises an `INVALID_REQUEST` error if the user ID is not positive. ### Method GET ### Endpoint /users/{user_id} ### Parameters #### Path Parameters - **user_id** (int) - Required - The unique identifier for the user. ### Request Example ``` GET /users/123 ``` ### Response #### Success Response (200) - **id** (int) - The user's ID. - **name** (str) - The user's name. #### Response Example ```json { "id": 123, "name": "John Doe" } ``` #### Error Response (400) - **errorId** (str) - `INVALID_REQUEST` - **status** (int) - 400 - **debugMessage** (str) - User ID must be positive #### Error Response Example ```json { "errorId": "INVALID_REQUEST", "status": 400, "debugMessage": "User ID must be positive" } ``` ``` -------------------------------- ### Configuring Custom Auth Layer in Nuxt (TypeScript) Source: https://dcc-bs.github.io/documentation/nuxt-layers/auth Example of how to extend a Nuxt project with a custom auth layer by modifying `.nuxt.config.ts`. It specifies the path to the custom layer and enables installation. ```typescript export default defineNuxtConfig({ extends: [ ['github:DCC-BS/nuxt-layers/auth', { install: true }] ], devtools: { enabled: true }, }); ``` -------------------------------- ### Example Server Health Check Endpoint Setup (Nuxt) Source: https://dcc-bs.github.io/documentation/user-interface/components/onlinestatus Demonstrates how to set up a basic health check endpoint in a Nuxt application using server API routes, returning a status and timestamp. ```typescript // server/api/health.get.ts export default defineEventHandler(() => { return { status: 'ok', timestamp: new Date().toISOString(), }; }); ``` -------------------------------- ### Startup Probe Source: https://dcc-bs.github.io/documentation/backend-common/probes The Startup Probe checks if the application has finished its initialization. Kubernetes will block liveness and readiness probes until this probe succeeds. ```APIDOC ## GET /health/startup ### Description Checks if the application has finished its initialization process. This is useful for applications that require significant setup time, such as loading large models or caches. ### Method GET ### Endpoint /health/startup ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **status** (str) - Indicates the application has started ('started'). - **timestamp** (str) - The timestamp when the application finished starting. #### Response Example ```json { "status": "started", "timestamp": "2025-12-04T10:30:00.000000+00:00" } ``` ``` -------------------------------- ### Initialize FastAPI App with AppConfig Source: https://dcc-bs.github.io/documentation/backend-common/config Demonstrates how to initialize a FastAPI application with the built-in AppConfig. The configuration is loaded from environment variables once at the application's entry point using an async context manager for the lifespan. ```python from contextlib import asynccontextmanager from dcc_backend_common.config import AppConfig from fastapi import FastAPI @asynccontextmanager async def lifespan(app: FastAPI): """Application lifespan handler.""" config = AppConfig.from_env() print(config) # Secrets are automatically masked yield app = FastAPI(lifespan=lifespan) ``` -------------------------------- ### Create Custom AppConfig by Inheriting AbstractAppConfig Source: https://dcc-bs.github.io/documentation/backend-common/config Illustrates how to create a project-specific configuration class by inheriting from `AbstractAppConfig`. This example defines required and optional fields, customizes loading logic with `get_env_or_throw`, and implements a masked string representation using `log_secret`. ```python # utils/app_config.py import os from typing import override from dcc_backend_common.config import AbstractAppConfig, get_env_or_throw, log_secret from pydantic import Field class AppConfig(AbstractAppConfig): """Application configuration loaded from environment variables.""" openai_api_key: str = Field(description="The API key for authenticating with OpenAI") llm_model: str = Field(description="The language model to use for text generation") client_url: str = Field(description="The URL for the client application") hmac_secret: str = Field(description="The secret key for HMAC authentication") # Optional with defaults optimizer_model: str = Field( default="gpt-4o-mini", description="Model to use for optimization", ) debug_mode: bool = Field( default=False, description="Enable debug mode for verbose logging", ) @classmethod @override def from_env(cls) -> "AppConfig": """Load configuration from environment variables.""" # Required variables - will raise AppConfigError if missing openai_api_key = get_env_or_throw("OPENAI_API_KEY") llm_model = get_env_or_throw("LLM_MODEL") client_url = get_env_or_throw("CLIENT_URL") hmac_secret = get_env_or_throw("HMAC_SECRET") # Optional variables with defaults optimizer_model = os.getenv("OPTIMIZER_MODEL", "gpt-4o-mini") debug_raw = os.getenv("DEBUG_MODE", "false").lower() debug_mode = debug_raw in {"1", "true", "yes", "on"} return cls( openai_api_key=openai_api_key, llm_model=f"openai/{llm_model}", client_url=client_url, hmac_secret=hmac_secret, optimizer_model=f"openai/{optimizer_model}", debug_mode=debug_mode, ) @override def __str__(self) -> str: """Return string representation with secrets masked.""" return f""" AppConfig( client_url={self.client_url}, llm_model={self.llm_model}, openai_api_key={log_secret(self.openai_api_key)}, hmac_secret={log_secret(self.hmac_secret)}, optimizer_model={self.optimizer_model}, debug_mode={self.debug_mode} ) """ ``` -------------------------------- ### NavigationBar Migration Example (Vue) Source: https://dcc-bs.github.io/documentation/user-interface/components/navigationbar Provides a migration guide for updating NavigationBar usage from older versions that only supported `center` and `right` slots to the newer version with `rightPreItems` and `rightPostItems`. This allows retaining default elements like `DisclaimerButton` and `LanguageSelect` while adding custom content. ```vue ``` -------------------------------- ### Quick Start: Log Usage Event with UsageTrackingService Source: https://dcc-bs.github.io/documentation/backend-common/usage_tracking Demonstrates initializing the UsageTrackingService with an HMAC secret and logging a sample usage event. This includes specifying the module, function, user ID, and custom event data like data size and processing time. ```python from dcc_backend_common.usage_tracking import UsageTrackingService # Initialize the service with an HMAC secret usage_tracking = UsageTrackingService(hmac_secret="your-secret-key") # Log a usage event usage_tracking.log_event( module="my_module", func="process_data", user_id="user123", data_size=1024, processing_time=0.5 ) ``` -------------------------------- ### Switching Auth Layers via Environment Variables (Bash) Source: https://dcc-bs.github.io/documentation/nuxt-layers/auth Examples showing how to switch between different authentication layers (`no-auth` and `azure-auth`) using `.env` files. This allows for flexible configuration per environment or per developer. ```bash # .env.local AUTH_LAYER_URI=github:DCC-BS/nuxt-layers/no-auth # .env.production AUTH_LAYER_URI=github:DCC-BS/nuxt-layers/azure-auth ``` ```bash # Alice's .env.local (has Azure access) AUTH_LAYER_URI=github:DCC-BS/nuxt-layers/azure-auth AUTH_AZURE_AD_CLIENT_ID=... # Bob's .env.local (no Azure access) AUTH_LAYER_URI=github:DCC-BS/nuxt-layers/no-auth ``` -------------------------------- ### GET /users - Build Endpoint Source: https://dcc-bs.github.io/documentation/nuxt-layers/backend_communication Configures and builds an event handler for a GET request to the `/users` endpoint. ```APIDOC ## GET /users ### Description Build and return the configured event handler. Must be called last in the builder chain. ### Method GET ### Endpoint /users ### Parameters #### Path Parameters - **path** (string | ((event: H3Event) => string)) - The backend API endpoint path (relative to `API_URL`). Can be a static string, a function returning a string based on the event, or a string containing dynamic placeholders like `[r:paramName]` or `[q:paramName]`. ### Request Example ```typescript export default backendHandlerBuilder() .withMethod('GET') .build('/users') ``` ### Response #### Success Response (200) - **EventHandler** (object) - A H3 event handler that can be exported from your server route file. #### Response Example (The response is an event handler function, not a direct JSON response) ``` -------------------------------- ### POST /users - Combined Fetcher and Dummy Fetcher Source: https://dcc-bs.github.io/documentation/nuxt-layers/backend_communication Demonstrates combining a real fetcher for production with a dummy fetcher as a fallback for development or testing environments. ```APIDOC ## POST /users - Combined Fetcher and Dummy Fetcher ### Description Combines a real fetcher for production with a dummy fetcher as a fallback for development or testing environments. ### Method POST ### Endpoint /users ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **TBody** (any) - The request body, as provided by `withBodyProvider` or default. ### Request Example ```typescript export default backendHandlerBuilder() .withFetcher(async (options) => { // Real fetcher for production return await $fetch(options.url, options) }) .withDummyFetcher({ // Fallback dummy data for development mock: true, data: [] }) .build('/users') ``` ### Response #### Success Response (200) - **TNewResponse** (any) - The response from the real fetcher or the dummy fetcher. #### Response Example ```json { "mock": true, "data": [] } ``` ``` -------------------------------- ### Initialize Logger and Get Logger Instance in FastAPI Application Source: https://dcc-bs.github.io/documentation/backend-common/logger Demonstrates how to initialize the logger once at application startup using `init_logger()` and retrieve a logger instance for a specific module using `get_logger(__name__)` within a FastAPI application's lifespan. ```python from contextlib import asynccontextmanager from dcc_backend_common.logger import init_logger, get_logger from fastapi import FastAPI @asynccontextmanager async def lifespan(app: FastAPI): """Application lifespan handler.""" init_logger() # Initialize once at startup logger = get_logger(__name__) logger.info("Application started") yield logger.info("Application shutting down") app = FastAPI(lifespan=lifespan) ``` -------------------------------- ### Interactive Disclaimer Example (Vue) Source: https://dcc-bs.github.io/documentation/user-interface/components/disclaimer An interactive example showcasing a fully customized Disclaimer component. It demonstrates passing dynamic HTML content for the main body and postfix, along with custom confirmation text. This example highlights the component's flexibility in handling rich content and user input. ```vue ``` -------------------------------- ### NavigationBar Complete Customization Example Source: https://dcc-bs.github.io/documentation/user-interface/components/navigationbar A comprehensive example showcasing the use of multiple slots (left, center, rightPreItems, rightPostItems) in the NavigationBar for full customization, including dynamic content and internationalization. ```vue ``` -------------------------------- ### Readiness Probe Source: https://dcc-bs.github.io/documentation/backend-common/probes The Readiness Probe checks if the application is ready to handle requests. If this probe fails, Kubernetes will stop sending traffic to the pod. It should check critical dependencies. ```APIDOC ## GET /health/readiness ### Description Checks if the application is ready to handle user requests. This probe verifies the health of critical external services and databases. ### Method GET ### Endpoint /health/readiness ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **status** (str) - Indicates the application is ready ('ready'). - **checks** (object) - A map of service names to their health status. #### Response Example (healthy) ```json { "status": "ready", "checks": { "database": "healthy", "external-api": "healthy" } } ``` #### Error Response (503) - **status** (str) - Indicates the application is unhealthy ('unhealthy'). - **checks** (object) - A map of service names to their health status, including errors. - **error** (str) - A general error message indicating the service is unavailable. #### Response Example (unhealthy) ```json { "status": "unhealthy", "checks": { "database": "error: Connection refused", "external-api": "unhealthy (status: 503)" }, "error": "Service unavailable" } ``` ``` -------------------------------- ### Install Backend Communication Layer in Nuxt Source: https://dcc-bs.github.io/documentation/nuxt-layers/backend_communication This snippet shows how to add the backend communication layer to your Nuxt project by extending the configuration. It requires the `install: true` option to enable the layer. ```typescript export default defineNuxtConfig({ extends: [ ['github:DCC-BS/nuxt-layers/backend_communication', { install: true }] ] }) ``` -------------------------------- ### Valid Backend Handler Configuration with TypeScript Source: https://dcc-bs.github.io/documentation/nuxt-layers/backend_communication Demonstrates a valid sequence of configuring a backend handler using the builder pattern. It shows the correct order of calling withBodyProvider, withFetcher, and postMap, followed by build. This example highlights type safety and the intended flow of configuration. ```typescript const handler1 = backendHandlerBuilder() .withBodyProvider(async (event) => ({ name: 'Test' })) .withFetcher(async (options) => ({ id: 1, name: options.body?.name })) .postMap(async (response) => ({ userId: response.id })) .build('/users') const handler5 = backendHandlerBuilder() .withBodyProvider(async (event) => ({ name: 'Test' })) .withFetcher(async (options) => ({ id: 1 })) .postMap(async (response) => ({ userId: response.id })) .withMethod('POST') // Still available .extendFetchOptions(async (options) => ({ ...options })) // Still available .build('/users') ``` -------------------------------- ### Class Docstring Example in Python Source: https://dcc-bs.github.io/documentation/coding/python Provides an example of a well-structured docstring for a Python class. It includes a summary, a more detailed explanation, and documentation for attributes. This demonstrates how to document the purpose, capabilities, and state of a class, such as a `TranslationService`. ```python # ✅ Right - Class docstring class TranslationService: """Service for translating text between languages. This service wraps the LLM-based translation logic and provides caching and rate limiting capabilities. Attributes: model: The LLM model identifier used for translations. cache_enabled: Whether translation caching is active. """ def __init__(self, config: AppConfig) -> None: """Initialize the translation service. Args: config: Application configuration containing LLM settings. """ self.model = config.llm_model self.cache_enabled = True ``` -------------------------------- ### Configure Dummy Fetcher with Static Data Source: https://dcc-bs.github.io/documentation/nuxt-layers/backend_communication Sets up a dummy fetcher to return mock data instead of making actual HTTP requests. This is useful for development and testing. The static data provided will be returned directly. ```typescript export default backendHandlerBuilder() .withDummyFetcher({ id: 1, name: "Test User", email: "test@example.com" }) .build('/users') ``` -------------------------------- ### TypeScript Typing Rules Example (TypeScript) Source: https://dcc-bs.github.io/documentation/coding/nuxt Illustrates the correct handling of unknown error types in TypeScript, emphasizing validation before use. This example shows how to safely catch and log errors by checking if the caught error is an instance of `Error`. ```typescript // ✅ Right try { // ... some code } catch (error: unknown) { if (error instanceof Error) { console.error(error.message); } } ``` -------------------------------- ### Integrate AppConfig with Dependency Injection (Python) Source: https://dcc-bs.github.io/documentation/backend-common/config Shows how to register `AppConfig` as a singleton provider within a Dependency Injector container. This allows other services in the application to easily access the application's configuration, ensuring a consistent and centralized way to manage settings. ```python # container.py from dependency_injector import containers, providers from myapp.utils.app_config import AppConfig class Container(containers.DeclarativeContainer): config = providers.Singleton(AppConfig.from_env) # Other services can depend on config translation_service = providers.Factory( TranslationService, config=config, ) ``` -------------------------------- ### Get Structured Logger Instance (Python) Source: https://dcc-bs.github.io/documentation/backend-common/logger This function retrieves a structured logger instance. It can be used with an optional name, typically the module name (`__name__`), or without a name to get an anonymous logger. The function returns a structlog bound logger instance. ```python from dcc_backend_common.logger import get_logger logger = get_logger(__name__) # Pass module name for context logger = get_logger() # Or get anonymous logger ``` -------------------------------- ### Extend Nuxt with Layers Source: https://dcc-bs.github.io/documentation/nuxt-layers/index Configures Nuxt to extend specific layers from a GitHub repository. The `extends` array in `nuxt.config.ts` specifies the layers to include, with options like `install: true` to enable automatic installation and integration. This allows for modular and reusable Nuxt application structures. ```typescript export default defineNuxtConfig({ extends: [ ['github:DCC-BS/nuxt-layers/auth', { install: true }], ['github:DCC-BS/nuxt-layers/health_check', { install: true }] ] }) ``` ```typescript export default defineNuxtConfig({ extends: [ ['github:DCC-BS/nuxt-layers/logger', { install: true }], ['github:DCC-BS/nuxt-layers/auth', { install: true }], ['github:DCC-BS/nuxt-layers/backend_communication', { install: true }], ['github:DCC-BS/nuxt-layers/health_check', { install: true }], ['github:DCC-BS/nuxt-layers/feedback-control', { install: true }] ] }) ``` -------------------------------- ### Get and Use Structured Logger Instance Source: https://dcc-bs.github.io/documentation/backend-common/logger Shows how to obtain a structured logger instance for a module using `get_logger(__name__)` and log messages with contextual information such as source language, target language, and text length. It also includes error handling for translation failures. ```python from dcc_backend_common.logger import get_logger # Pass the module name for context logger = get_logger(__name__) def process_translation(request: TranslationRequest) -> TranslationResult: logger.info( "Processing translation request", source_lang=request.source_lang, target_lang=request.target_lang, text_length=len(request.text), ) try: result = translate(request) logger.info("Translation completed", result_length=len(result.text)) return result except TranslationError as e: logger.error("Translation failed", error=str(e), request_id=request.id) raise ``` -------------------------------- ### Simple vs. Complex Body Transformations in TypeScript Source: https://dcc-bs.github.io/documentation/nuxt-layers/backend_communication Contrasts good and bad practices for body transformations within API handlers. The 'good' example shows a single responsibility transformation (adding a timestamp), while the 'bad' example illustrates overly complex logic within the body provider, which should be refactored for maintainability. ```typescript // ✅ Good - single responsibility export default backendHandlerBuilder() .withBodyProvider(async (event) => addTimestamp(await readBody(event))) .build('/users') // ❌ Bad - too much logic export default backendHandlerBuilder() .withBodyProvider(async (event) => { // 50 lines of complex logic }) .build('/users') ``` -------------------------------- ### GET /users - Response Normalization Source: https://dcc-bs.github.io/documentation/nuxt-layers/backend_communication Standardizes the response format from the backend API. ```APIDOC ## GET /users - Response Normalization ### Description Standardizes the response format from the backend API. ### Method GET ### Endpoint /users ### Parameters (No specific parameters for this transformation example) ### Request Example ```typescript // server/api/users.get.ts export default backendHandlerBuilder() .postMap(async (response) => { return { success: true, data: response, meta: { timestamp: Date.now(), version: '1.0' } } }) .build('/users') ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the operation was successful. - **data** (any) - The original response data from the backend. - **meta** (object) - Metadata about the response. - **timestamp** (number) - The timestamp of the response. - **version** (string) - The API version. #### Response Example ```json { "success": true, "data": { ... }, "meta": { "timestamp": 1678886400000, "version": "1.0" } } ``` ``` -------------------------------- ### POST /users - withDummyFetcher (Static Data) Source: https://dcc-bs.github.io/documentation/nuxt-layers/backend_communication Configures a dummy fetcher that returns mock data instead of making real HTTP requests. This is useful for development and testing when a backend is not available. This example shows static dummy data. ```APIDOC ## POST /users - withDummyFetcher (Static Data) ### Description Configures a dummy fetcher that returns mock data instead of making real HTTP requests. This is useful for development and testing when a backend is not available. This example uses static dummy data. ### Method POST ### Endpoint /users ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **TBody** (any) - The request body, as provided by `withBodyProvider` or default. ### Request Example ```typescript export default backendHandlerBuilder() .withDummyFetcher({ id: 1, name: "Test User", email: "test@example.com" }) .build('/users') ``` ### Response #### Success Response (200) - **TNewResponse** (any) - The static dummy data provided. #### Response Example ```json { "id": 1, "name": "Test User", "email": "test@example.com" } ``` ``` -------------------------------- ### GET /users/{user_id} Source: https://dcc-bs.github.io/documentation/coding/python Retrieves a specific user's information by their unique ID. ```APIDOC ## GET /users/{user_id} ### Description Retrieves a user by their unique ID. ### Method GET ### Endpoint /users/{user_id} ### Parameters #### Path Parameters - **user_id** (string) - Required - The unique identifier of the user to retrieve. ### Response #### Success Response (200 OK) - **user_id** (string) - The unique identifier for the user. - **username** (string) - The username of the user. - **email** (string) - The email address of the user. #### Response Example ```json { "user_id": "a1b2c3d4-e5f6-7890-1234-567890abcdef", "username": "johndoe", "email": "johndoe@example.com" } ``` #### Error Response (404 Not Found) - **detail** (string) - "User not found" #### Error Response Example ```json { "detail": "User not found" } ``` ``` -------------------------------- ### Development and Production Environment Variables (Bash) Source: https://dcc-bs.github.io/documentation/nuxt-layers/auth Configuration examples for `.env` files in development and production environments. These variables define API URLs and authentication layer URIs, including specific Azure AD credentials for production. ```bash # .env.development API_URL=http://localhost:8000 AUTH_LAYER_URI=github:DCC-BS/nuxt-layers/no-auth ``` ```bash # .env.production API_URL=https://api.example.com AUTH_LAYER_URI=github:DCC-BS/nuxt-layers/azure-auth AUTH_AZURE_AD_CLIENT_ID=... AUTH_AZURE_AD_TENANT_ID=... AUTH_AZURE_AD_CLIENT_SECRET=... AUTH_AZURE_AD_API_CLIENT_ID=... AUTH_AUTH_SECRET=... AUTH_ORIGIN=https://app.example.com ``` -------------------------------- ### GET /external/data - Custom Headers and Timeout Source: https://dcc-bs.github.io/documentation/nuxt-layers/backend_communication Demonstrates how to add custom headers and configure a timeout for the fetch request. ```APIDOC ## GET /external/data - Custom Headers and Timeout ### Description Adds custom headers and configures a timeout for the fetch request to an external API. ### Method GET ### Endpoint /external/data ### Parameters #### Query Parameters (Depends on the specific external API) ### Request Example ```typescript // server/api/external.get.ts export default backendHandlerBuilder() .extendFetchOptions(async (options) => { return { ...options, headers: { ...options.headers, 'X-API-Key': process.env.EXTERNAL_API_KEY!, 'Accept': 'application/json' }, // ofetch timeout option (in milliseconds) timeout: 10000 } }) .build('/external/data') ``` ### Response #### Success Response (200) (Depends on the external API's response) #### Response Example (Depends on the external API's response) ``` -------------------------------- ### Enabling Dummy Data Mode via Environment Variable Source: https://dcc-bs.github.io/documentation/nuxt-layers/backend_communication Shows how to enable dummy data mode for the backend communication layer by setting the `DUMMY` environment variable to `true`. This is useful for development and testing, allowing the use of mock data instead of live API calls. ```bash # .env DUMMY=true API_URL=http://localhost:8000 ```