### Install Dependencies and Start Local Development Source: https://forklaunch.com/docs/creating-an-application Installs project dependencies using pnpm and starts the local development server with hot-reloading. ForkLaunch automatically spins up necessary services like databases and queues via docker-compose. ```bash pnpm install pnpm dev ``` -------------------------------- ### Install Dependencies and Setup Database Source: https://forklaunch.com/docs/local-development Installs project dependencies and initializes/runs database migrations for all services. This includes starting Docker containers, initializing the migration folder, running migrations, and seeding the database. ```bash pnpm install pnpm database:setup ``` -------------------------------- ### Local Development Setup Source: https://forklaunch.com/docs/getting-started Install project dependencies and start the local development server with hot reload enabled using pnpm. Ensure Docker is running for service orchestration. ```bash pnpm install && pnpm dev ``` -------------------------------- ### Start Production Mode Source: https://forklaunch.com/docs/local-development Starts the application in production mode. ```bash pnpm start ``` -------------------------------- ### Create Application with High-Performance Setup Source: https://forklaunch.com/docs/cli/init Generate a new application optimized for performance. This example uses TypeBox for validation, Hyper-Express for the HTTP framework, and Bun as the runtime. ```bash forklaunch init application my-fast-app \ --path ./my-fast-app \ --database postgresql \ --validator typebox \ --http-framework hyper-express \ --runtime bun \ --formatter biome \ --linter oxlint \ --test-framework vitest ``` -------------------------------- ### Install ForkLaunch CLI Source: https://forklaunch.com/docs/getting-started Install the ForkLaunch CLI globally using npm, pnpm, or bun. Ensure Node.js, pnpm/bun, Git, and Docker are installed and meet the version requirements. ```bash npm install -g forklaunch ``` -------------------------------- ### Initialize Libraries with Options Source: https://forklaunch.com/docs/adding-projects/libraries Examples of initializing libraries with different paths, descriptions, and custom directories. ```bash # Basic library (shared utilities for dice roll app) forklaunch init library dice-utils --path ./my-app/src/modules # Library with custom description forklaunch init library validation --path ./my-app/src/modules --description "Input validation utilities" # Library in specific directory forklaunch init library api-client --path ./shared # Statistics calculation library forklaunch init library stats-helpers --path ./my-app/src/modules --description "Statistical calculation utilities" ``` -------------------------------- ### Example with All Options Source: https://forklaunch.com/docs/framework/universal-sdk Demonstrates how to use all available request options for a product update. ```APIDOC ### Example with All Options ```typescript await productsSdk.updateProduct({ params: { id: 'prod-123' }, query: { notify: 'true' }, body: { name: 'New Product Name', price: 29.99 }, headers: { 'x-idempotency-key': 'unique-key' } }); ``` ``` -------------------------------- ### Configuration Examples Source: https://forklaunch.com/docs/cli/config Demonstrates pulling and pushing environment configurations, including filtering by service and specifying output/input files. ```bash # Pull configuration for staging forklaunch config pull --region us-east-1 --environment staging ``` ```bash # Pull configuration for a specific service forklaunch config pull --region us-east-1 --environment staging --service payments ``` ```bash # Pull configuration to a specific file forklaunch config pull --region us-east-1 --environment production --output ./config/.env.prod ``` ```bash # Push configuration for staging forklaunch config push --region us-east-1 --environment staging ``` ```bash # Push configuration from a specific file forklaunch config push --region us-east-1 --environment production --input ./config/.env.prod ``` -------------------------------- ### Start Local Infrastructure with ForkLaunch CLI Source: https://forklaunch.com/docs/guides/pulumi-export Command to start local infrastructure services defined in docker-compose.yaml. ```bash forklaunch dev ``` -------------------------------- ### Setup Generic Database Container Source: https://forklaunch.com/docs/guides/testing Sets up a database container based on the specified type and configuration. Returns the started container instance or null for SQLite. ```typescript async setupDatabaseContainer( type: DatabaseType, config?: DatabaseConfig ): Promise ``` ```typescript const manager = new TestContainerManager(); const container = await manager.setupDatabaseContainer('postgres', { user: 'test_user', password: 'test_password', database: 'test_db' }); const host = container.getHost(); const port = container.getMappedPort(5432); ``` -------------------------------- ### Dependency Injection Setup Source: https://forklaunch.com/docs/framework/universal-sdk The recommended way to use Universal SDK is through dependency injection in your `registrations.ts`. ```APIDOC ## Dependency Injection Setup The recommended way to use Universal SDK is through dependency injection in your `registrations.ts`: ```typescript import { universalSdk } from '@forklaunch/universal-sdk'; import type { ProductsSdkClient } from '@ecommerce-api/products'; import { Lifetime, type } from '@forklaunch/core/services'; const runtimeDependencies = environmentConfig.chain({ ProductsSdk: { lifetime: Lifetime.Singleton, type: type>(), factory: ({ PRODUCTS_URL }) => universalSdk({ host: PRODUCTS_URL, registryOptions: { path: 'api/v1/openapi' } }) } }); // Resolve in your application const productsSdk = await ci.resolve(tokens.ProductsSdk); ``` ``` -------------------------------- ### Install WebSocket Libraries Source: https://forklaunch.com/docs/guides/websockets Install the core WebSocket library and a schema validator like Zod or TypeBox. ```bash pnpm add @forklaunch/ws ws # Schema validator (choose one) pnpm add @forklaunch/validator zod # or pnpm add @forklaunch/validator @sinclair/typebox ``` -------------------------------- ### Real-World Billing Module Example Source: https://forklaunch.com/docs/guides/contract-first-development A comprehensive example from the ForkLaunch billing module demonstrating reusable schemas, mappers, authentication, and type safety in production. ```typescript import { handlers, schemaValidator, string, array, IdSchema, IdsSchema } from '@forklaunch-platform/core'; // Using mappers for schema validation import { CreatePlanMapper, PlanMapper, UpdatePlanMapper } from '../../domain/mappers/plan.mappers'; import { PlanSchemas } from '../../domain/schemas'; // HMAC-authenticated create endpoint export const createPlan = handlers.post( schemaValidator, '/', { name: 'Create Plan', summary: 'Create a plan', auth: { hmac: { secretKeys: { default: process.env.HMAC_SECRET_KEY } } }, body: CreatePlanMapper.schema, responses: { 200: PlanMapper.schema } }, async (req, res) => { res.status(200).json(await planService.createPlan(req.body)); } ); // Path parameter example export const getPlan = handlers.get( schemaValidator, '/:id', { name: 'Get Plan', summary: 'Get a plan', auth: { hmac: { secretKeys: { default: process.env.HMAC_SECRET_KEY } } }, params: IdSchema, // Reusable schema: { id: string } responses: { 200: PlanSchemas.PlanSchema } }, async (req, res) => { res.status(200).json(await planService.getPlan(req.params)); } ); // Query parameter example export const listPlans = handlers.get( schemaValidator, '/', { name: 'List Plans', summary: 'List plans', query: IdsSchema, // Reusable schema: { ids: array(string) } auth: { hmac: { secretKeys: { default: process.env.HMAC_SECRET_KEY } } }, responses: { 200: array(PlanSchemas.PlanSchema) } }, async (req, res) => { res.status(200).json(await planService.listPlans(req.query)); } ); // Delete endpoint returning string export const deletePlan = handlers.delete( schemaValidator, '/:id', { name: 'Delete Plan', summary: 'Delete a plan', params: IdSchema, auth: { hmac: { secretKeys: { default: process.env.HMAC_SECRET_KEY } } }, responses: { 200: string } }, async (req, res) => { await planService.deletePlan(req.params); res.status(200).send(`Deleted plan ${req.params.id}`); } ); ``` -------------------------------- ### Setup Kafka Test Container Source: https://forklaunch.com/docs/guides/testing Configures and starts a Kafka test container. Accepts optional Kafka configuration for cluster ID, partitions, and replication factor. ```typescript async setupKafkaContainer( config?: KafkaConfig ): Promise ``` ```typescript interface KafkaConfig { clusterId?: string; // Default: 'test-cluster' numPartitions?: number; // Default: 1 replicationFactor?: number; // Default: 1 env?: Record; // Additional environment variables } ``` ```typescript const container = await manager.setupKafkaContainer({ clusterId: 'my-cluster', numPartitions: 3, replicationFactor: 1 }); const broker = `${container.getHost()}:${container.getMappedPort(9092)}`; ``` -------------------------------- ### Setup S3 (MinIO) Test Container Source: https://forklaunch.com/docs/guides/testing Configures and starts a MinIO (S3-compatible) test container. Allows customization of root credentials, default bucket, and region. ```typescript async setupS3Container( config?: S3Config ): Promise ``` ```typescript interface S3Config { rootUser?: string; // Default: 'minioadmin' rootPassword?: string; // Default: 'minioadmin' defaultBucket?: string; // Default: 'test-bucket' region?: string; // Default: 'us-east-1' } ``` ```typescript const container = await manager.setupS3Container({ rootUser: 'myaccesskey', rootPassword: 'mysecretkey', defaultBucket: 'my-test-bucket', region: 'us-west-2' }); const endpoint = `http://${container.getHost()}:${container.getMappedPort(9000)}`; ``` -------------------------------- ### Install Testing Dependencies Source: https://forklaunch.com/docs/guides/testing Install the necessary testing packages for ForkLaunch blueprints and testcontainers. ```bash pnpm add -D @forklaunch/testing testcontainers ``` -------------------------------- ### Start Development Server with pnpm or bun Source: https://forklaunch.com/docs/changing-projects/applications Launch the development server for local testing and iteration using pnpm or bun. ```bash pnpm run dev ``` ```bash bun run dev ``` -------------------------------- ### Initialize router with path and infrastructure Source: https://forklaunch.com/docs/adding-projects/routers Examples of initializing a router, specifying the target service path and optionally including infrastructure like Redis or S3. ```bash # Basic router in current service forklaunch init router products --path ./my-app/src/modules/my-service # Router in specific service with path forklaunch init router users --path ./my-app/src/modules/user-service # Router with Redis infrastructure forklaunch init router orders --path ./my-app/src/modules/commerce-service --infrastructure redis # Router with multiple infrastructure forklaunch init router files --path ./my-app/src/modules/storage-service --infrastructure redis s3 ``` -------------------------------- ### Install Cache Dependencies Source: https://forklaunch.com/docs/guides/cache Install the core cache interface and the Redis implementation using pnpm. ```bash pnpm add @forklaunch/core pnpm add @forklaunch/infrastructure-redis redis ``` -------------------------------- ### Authentication Workflow Example Source: https://forklaunch.com/docs/cli/authentication A typical workflow demonstrating how to check authentication status, log in if necessary, and then use authenticated commands. ```bash # Check current session forklaunch whoami # Authenticate if needed forklaunch login # Use authenticated commands forklaunch release create --version 1.0.0 forklaunch deploy create --release 1.0.0 --environment staging --region us-east-1 # Logout when done (optional) forklaunch logout ``` -------------------------------- ### Simplify Local Development Setup Source: https://forklaunch.com/docs/changing-projects/services Modify a service to use SQLite for local development and remove external dependencies like Redis. This simplifies setup for developers. ```bash # Use SQLite for easier local setup forklaunch change service --path ./user-service --database sqlite # Remove Redis dependency forklaunch change service --path ./user-service --infrastructure ``` -------------------------------- ### Cleanup Example: Simplifying Architecture by Removing Routers and Libraries Source: https://forklaunch.com/docs/deleting-projects This example shows how to remove redundant routers and unused libraries as part of an architecture simplification effort. ```bash # Remove redundant routers forklaunch delete router admin-v1 # keeping admin-v2 forklaunch delete router internal # moving routes to main router # Remove unused libraries forklaunch delete library old-validation # using new validation service ``` -------------------------------- ### setupMySQLContainer Source: https://forklaunch.com/docs/guides/testing Setup a MySQL test container with optional configuration. ```APIDOC ## setupMySQLContainer ### Description Setup a MySQL test container. ### Method ```typescript async setupMySQLContainer(config?: MySQLConfig): Promise ``` ### Parameters #### Request Body * `config` (MySQLConfig): Optional configuration for the MySQL container. * `user` (string): Default: 'test_user' * `password` (string): Default: 'test_password' * `database` (string): Default: 'test_db' * `rootPassword` (string): Default: 'root_password' ### Example ```typescript const container = await manager.setupMySQLContainer({ user: 'myuser', password: 'mypass', database: 'mydb', rootPassword: 'rootpass' }); ``` ``` -------------------------------- ### setupPostgresContainer Source: https://forklaunch.com/docs/guides/testing Setup a PostgreSQL test container with optional configuration. ```APIDOC ## setupPostgresContainer ### Description Setup a PostgreSQL test container. ### Method ```typescript async setupPostgresContainer(config?: PostgresConfig): Promise ``` ### Parameters #### Request Body * `config` (PostgresConfig): Optional configuration for the PostgreSQL container. * `user` (string): Default: 'test_user' * `password` (string): Default: 'test_password' * `database` (string): Default: 'test_db' * `command` (string[]): Default: ['postgres', '-c', 'log_statement=all'] ### Example ```typescript const container = await manager.setupPostgresContainer({ user: 'myuser', password: 'mypass', database: 'mydb', command: ['postgres', '-c', 'max_connections=200'] }); ``` ``` -------------------------------- ### Install and Use AsyncAPI Generator Source: https://forklaunch.com/docs/guides/asyncapi Install the AsyncAPI Generator globally and use it to generate HTML or Markdown documentation from your asyncapi.yaml file. You can also serve the generated documentation locally. ```bash # Install AsyncAPI Generator npm install -g @asyncapi/generator # Generate HTML documentation ag asyncapi.yaml @asyncapi/html-template -o docs/ # Generate Markdown documentation ag asyncapi.yaml @asyncapi/markdown-template -o docs/ # Serve documentation locally cd docs && python3 -m http.server 8080 ``` -------------------------------- ### Setup New Environment Workflow Source: https://forklaunch.com/docs/guides/cli-commands A multi-step workflow for setting up a new environment, including validating and syncing variables, and then manually filling in values. ```bash # Validate what variables are needed forklaunch environment validate # Add all missing variables with placeholders forklaunch environment sync # Fill in values nano .env.local nano modules/api-service/.env ``` -------------------------------- ### setupMSSQLContainer Source: https://forklaunch.com/docs/guides/testing Setup a Microsoft SQL Server test container with optional configuration. ```APIDOC ## setupMSSQLContainer ### Description Setup a Microsoft SQL Server test container. ### Method ```typescript async setupMSSQLContainer(config?: MSSQLConfig): Promise ``` ### Parameters #### Request Body * `config` (MSSQLConfig): Optional configuration for the MSSQL container. * `user` (string): Default: 'SA' * `password` (string): Default: 'Test_Password123!' * `database` (string): Default: 'test_db' * `saPassword` (string): Default: 'Test_Password123!' ### Example ```typescript const container = await manager.setupMSSQLContainer({ saPassword: 'MyStrong!Pass123' }); ``` ``` -------------------------------- ### Run Development Server Source: https://forklaunch.com/docs/guides/cli-commands Start the local development server using npm. This command is standard for running local development environments. ```bash npm run dev ``` -------------------------------- ### setupDatabaseContainer Source: https://forklaunch.com/docs/guides/testing Setup a database container based on type. Supports PostgreSQL, MySQL, MongoDB, MSSQL, and SQLite. ```APIDOC ## setupDatabaseContainer ### Description Setup a database container based on type. ### Method ```typescript async setupDatabaseContainer(type: DatabaseType, config?: DatabaseConfig): Promise ``` ### Parameters * `type`: Database type (`'postgres'`, `'mysql'`, `'mongodb'`, `'mssql'`, `'sqlite'`, etc.) * `config`: Database-specific configuration (optional) ### Returns Started container instance or `null` for SQLite ### Example ```typescript const manager = new TestContainerManager(); const container = await manager.setupDatabaseContainer('postgres', { user: 'test_user', password: 'test_password', database: 'test_db' }); const host = container.getHost(); const port = container.getMappedPort(5432); ``` ``` -------------------------------- ### Service Initialization Examples Source: https://forklaunch.com/docs/adding-projects/services Demonstrates various ways to initialize a service using the `forklaunch init` command, including specifying databases, infrastructure, custom paths, and descriptions. ```bash # Basic service (see dice roll example) forklaunch init service roll-dice-svc --path ./my-app/src/modules --database postgresql ``` ```bash # Service with Redis cache forklaunch init service game-stats-svc --path ./my-app/src/modules --database postgresql --infrastructure redis ``` ```bash # Service with multiple infrastructure forklaunch init service file-upload-svc --path ./my-app/src/modules --database postgresql --infrastructure redis s3 ``` ```bash # Custom path and description forklaunch init service user-management --path ./user-svc --description "User management service" ``` ```bash # Sync manually created service forklaunch sync service custom-service --path ./custom-svc ``` -------------------------------- ### Complete Route Example with Schemas Source: https://forklaunch.com/docs/guides/contract-first-development Define request and response schemas using Zod types for POST, GET, PATCH, and DELETE operations on a user resource. This example demonstrates how to integrate schema validation into route handlers. ```typescript // api/controllers/user.controller.ts import { handlers, schemaValidator, string, boolean, array, union, literal, optional } from '@forklaunch-platform/core'; // Request schema - plain object with Zod types const UserRequestSchema = { name: string, email: string, age: optional(string), role: union([literal('user'), literal('admin')]), preferences: optional({ newsletter: boolean, notifications: boolean }) }; // Response schema - plain object with Zod types const UserResponseSchema = { id: string, name: string, email: string, age: optional(string), role: string, createdAt: string, updatedAt: string }; // Create user route export const userPost = handlers.post( schemaValidator, '/', { name: 'User Post', summary: 'Create a new user', body: UserRequestSchema, responses: { 200: UserResponseSchema, 400: { error: string } } }, async (req, res) => { const user = await userService.userPost(req.body); res.json(user); } ); // Get user route export const userGet = handlers.get( schemaValidator, '/:id', { name: 'User Get', summary: 'Get user by ID', params: { id: string }, query: { include: optional(array(string)) }, responses: { 200: UserResponseSchema, 404: { error: string } } }, async (req, res) => { const user = await userService.userGet( req.params.id, req.query.include ); if (!user) { res.status(404).json({ error: 'User not found' }); return; } res.json(user); } ); // Update user route export const userPatch = handlers.patch( schemaValidator, '/:id', { name: 'User Patch', summary: 'Update user', params: { id: string }, body: { name: optional(string), email: optional(string), preferences: optional({ newsletter: boolean, notifications: boolean }) }, responses: { 200: UserResponseSchema, 404: { error: string } } }, async (req, res) => { const user = await userService.userPatch(req.params.id, req.body); res.json(user); } ); // Delete user route export const userDelete = handlers.delete( schemaValidator, '/:id', { name: 'User Delete', summary: 'Delete user', params: { id: string }, responses: { 200: string, 404: { error: string } } }, async (req, res) => { await userService.userDelete(req.params.id); res.status(200).send(`Deleted user ${req.params.id}`); } ); ``` -------------------------------- ### Initialize Application with Database Source: https://forklaunch.com/docs/infrastructure/overview Use the CLI to initialize a new application, specifying infrastructure choices like the database type. ```bash forklaunch init application my-app --database postgresql --runtime node ``` -------------------------------- ### Phase 1: Prepare Development - Test and Run Development Server (bun) Source: https://forklaunch.com/docs/changing-projects/services After updating the service configuration, run tests and start the development server using bun. ```bash bun test bun run dev ``` -------------------------------- ### Kafka Consumer Setup Source: https://forklaunch.com/docs/infrastructure/queues Configure and run a Kafka consumer to process 'deployment-events'. Ensure KAFKA_BROKERS environment variable is set. ```typescript import { KafkaConsumer } from '@forklaunch/infrastructure-kafka'; const consumer = new KafkaConsumer({ brokers: [process.env.KAFKA_BROKERS], groupId: 'deployment-tracker' }); await consumer.subscribe({ topic: 'deployment-events' }); await consumer.run({ eachMessage: async ({ topic, partition, message }) => { const event = JSON.parse(message.value.toString()); switch (event.type) { case 'DEPLOYMENT_STARTED': await trackDeploymentStart(event); break; case 'DEPLOYMENT_COMPLETED': await trackDeploymentComplete(event); break; } } }); ``` -------------------------------- ### Run Development Server with Bun Source: https://forklaunch.com/docs/changing-projects Start the development server using Bun. This command is used for local development, enabling hot-reloading and other development features. ```bash bun run dev ``` -------------------------------- ### Example Request with All Options Source: https://forklaunch.com/docs/framework/universal-sdk Demonstrates making a request using the SDK client with all available options: path parameters, query parameters, request body, and custom headers. ```typescript await productsSdk.updateProduct({ params: { id: 'prod-123' }, query: { notify: 'true' }, body: { name: 'New Product Name', price: 29.99 }, headers: { 'x-idempotency-key': 'unique-key' } }); ``` -------------------------------- ### Test API Endpoints with cURL Source: https://forklaunch.com/docs/creating-an-application Demonstrates how to test API endpoints using cURL. Includes examples for creating a user via POST and retrieving a user by ID via GET. ```bash # Create a user curl -X POST http://localhost:3000/users \ -H "Content-Type: application/json" \ -d '{"email":"user@example.com","name":"John Doe"}' # Get user by ID curl http://localhost:3000/users/ ``` -------------------------------- ### Initialize and Sync Application Source: https://forklaunch.com/docs/guides/cli-commands Use these commands to initialize a new application and synchronize all its components. Ensure you are in the correct directory. ```bash forklaunch init application my-app --path ./my-app forklaunch sync all ``` -------------------------------- ### Express Router Setup Source: https://forklaunch.com/docs/framework/http Instantiate an Express router using forklaunchRouter. Configure options for busboy, text, JSON, and URL-encoded parsing. ```typescript import { forklaunchRouter } from '@forklaunch/express'; const router = forklaunchRouter( basePath, schemaValidator, openTelemetryCollector, options?: { busboy?: BusboyConfig; text?: OptionsText; json?: OptionsJson; urlencoded?: OptionsUrlencoded; } ); ``` -------------------------------- ### Onboard New Developer Workflow Source: https://forklaunch.com/docs/guides/cli-commands Steps for onboarding a new developer, including cloning the repository, syncing environment variables, and setting local values. ```bash # New developer clones repository git clone cd # Sync environment variables forklaunch env sync # Developer fills in their local values nano .env.local ``` -------------------------------- ### Install Dependencies with pnpm or bun Source: https://forklaunch.com/docs/changing-projects/applications Use these commands to install project dependencies depending on your package manager. ```bash pnpm install ``` ```bash bun install ``` -------------------------------- ### Get User By ID Endpoint Source: https://forklaunch.com/docs/guides/contract-first-development Defines a GET endpoint to retrieve a specific user by their unique ID. ```APIDOC ## GET /:id ### Description Retrieves a specific user by their ID. ### Method GET ### Endpoint /:id ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the user. ### Response #### Success Response (200) - **UserResponseSchema** (object) - The schema for the user object. #### Error Response (404) - **error** (string) - A message indicating that the user was not found. ``` -------------------------------- ### Generated AsyncAPI Document Example Source: https://forklaunch.com/docs/guides/websockets This is an example of the AsyncAPI 3.0 document generated from the provided schemas and configuration. ```json { "asyncapi": "3.0.0", "info": { "title": "Chat WebSocket API", "version": "1.0.0", "description": "Real-time chat application WebSocket API" }, "defaultContentType": "application/json", "channels": { "chat": { "address": "chat", "messages": { "chat": { "name": "chat", "payload": { /* Zod/TypeBox schema */ } } } } }, "operations": { "receive-chat-chat": { "action": "receive", "channel": { "$ref": "#/channels/chat" }, "messages": [{ "$ref": "#/channels/chat/messages/chat" }] }, "send-chat-chat": { "action": "send", "channel": { "$ref": "#/channels/chat" }, "messages": [{ "$ref": "#/channels/chat/messages/chat" }] } } } ``` -------------------------------- ### Initialize a New ForkLaunch Project Source: https://forklaunch.com/docs/cli Use this command to set up a new ForkLaunch project with specified application name, path, database, and runtime. ```bash forklaunch init application my-app --path ./my-app --database postgresql --runtime node ``` -------------------------------- ### Prepare for Deployment Source: https://forklaunch.com/docs/guides/cli-commands Integrate your application with the platform, sync all components, and validate environment variables before proceeding with deployment. ```bash forklaunch integrate --app forklaunch sync all forklaunch environment validate ``` -------------------------------- ### Install Object Store Dependencies Source: https://forklaunch.com/docs/guides/objectstore Install the core object store interface and the S3 implementation with AWS SDK. ```bash pnpm add @forklaunch/core pnpm add @forklaunch/infrastructure-s3 @aws-sdk/client-s3 ``` -------------------------------- ### Phase 1: Prepare Development - Test and Run Development Server (pnpm) Source: https://forklaunch.com/docs/changing-projects/services After updating the service configuration, run tests and start the development server using pnpm. ```bash pnpm test pnpm run dev ``` -------------------------------- ### Basic Factory Function Example Source: https://forklaunch.com/docs/guides/dependency-management A simple factory function example demonstrating how to create a service with a single dependency. ```typescript { UserService: { lifetime: Lifetime.Scoped, type: BaseUserService, factory: ({ EntityManager }) => new BaseUserService(EntityManager) } } ``` -------------------------------- ### Install Dependencies with Bun Source: https://forklaunch.com/docs/changing-projects Use this command to install project dependencies when using Bun. It fetches and links all necessary packages. ```bash bun install ``` -------------------------------- ### Initialize Library with ForkLaunch CLI Source: https://forklaunch.com/docs/cli/init Use this command to initialize a new library. You can specify the library name and description. ```bash forklaunch init library [OPTIONS] [name] ``` -------------------------------- ### Install Dependencies with pnpm Source: https://forklaunch.com/docs/changing-projects Use this command to install project dependencies when using pnpm. It ensures all required packages are downloaded and linked. ```bash pnpm install ``` -------------------------------- ### User GET Route Source: https://forklaunch.com/docs/guides/contract-first-development Defines a GET route to retrieve a user by their ID, with optional query parameters for including related data. ```APIDOC ## GET /:id ### Description Get user by ID. ### Method GET ### Endpoint /:id ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the user to retrieve #### Query Parameters - **include** (array) - Optional - Array of related data to include (e.g., ['posts', 'profile']) ### Responses #### Success Response (200) - **id** (string) - Description - **name** (string) - Description - **email** (string) - Description - **age** (string) - Optional - Description - **role** (string) - Description - **createdAt** (string) - Description - **updatedAt** (string) - Description #### Error Response (404) - **error** (string) - Description ``` -------------------------------- ### Initialize Application with ForkLaunch CLI Source: https://forklaunch.com/docs/cli/init Use this command to initialize a new application. You can specify various options to configure the application's structure and dependencies. ```bash forklaunch init application [OPTIONS] [name] ``` -------------------------------- ### Billing Module Example Source: https://forklaunch.com/docs/guides/contract-first-development A comprehensive real-world example of the billing module, showcasing patterns like reusable schemas, mappers, authentication, and type safety. ```APIDOC ## Real-World Example: Billing Module ### Description This section provides a complete example from the ForkLaunch platform's billing module, demonstrating production-ready patterns for API development. ### Endpoints #### POST / ##### Description Create a new plan. ##### Method POST ##### Endpoint / ##### Authentication HMAC authentication with a default secret key from `process.env.HMAC_SECRET_KEY`. ##### Request Body - **Schema**: `CreatePlanMapper.schema` ##### Responses * **200 OK**: Returns the created plan. - **Schema**: `PlanMapper.schema` #### GET /:id ##### Description Retrieve a specific plan by its ID. ##### Method GET ##### Endpoint /:id ##### Parameters * **Path Parameters** - **id** (string) - Required - The ID of the plan to retrieve. ##### Authentication HMAC authentication with a default secret key from `process.env.HMAC_SECRET_KEY`. ##### Responses * **200 OK**: Returns the requested plan. - **Schema**: `PlanSchemas.PlanSchema` #### GET / ##### Description List all plans, optionally filtered by IDs. ##### Method GET ##### Endpoint / ##### Parameters * **Query Parameters** - **ids** (array(string)) - Optional - An array of plan IDs to filter the list. ##### Authentication HMAC authentication with a default secret key from `process.env.HMAC_SECRET_KEY`. ##### Responses * **200 OK**: Returns a list of plans. - **Schema**: `array(PlanSchemas.PlanSchema)` #### DELETE /:id ##### Description Delete a plan by its ID. ##### Method DELETE ##### Endpoint /:id ##### Parameters * **Path Parameters** - **id** (string) - Required - The ID of the plan to delete. ##### Authentication HMAC authentication with a default secret key from `process.env.HMAC_SECRET_KEY`. ##### Responses * **200 OK**: Returns a success message indicating the plan was deleted. - **Schema**: `string` ### Key Patterns 1. **Reusable Schemas**: `IdSchema` and `IdsSchema` are defined once and reused. 2. **Mapper Schemas**: Complex validation encapsulated in mappers with `.schema` property. 3. **Authentication**: HMAC auth configured at the route level. 4. **Type Safety**: Request/response types inferred from schemas. 5. **OpenAPI Ready**: Routes automatically generate OpenAPI documentation. ### Example Code ```typescript import { handlers, schemaValidator, string, array, IdSchema, IdsSchema } from '@forklaunch-platform/core'; // Using mappers for schema validation import { CreatePlanMapper, PlanMapper, UpdatePlanMapper } from '../../domain/mappers/plan.mappers'; import { PlanSchemas } from '../../domain/schemas'; // HMAC-authenticated create endpoint export const createPlan = handlers.post( schemaValidator, '/', { name: 'Create Plan', summary: 'Create a plan', auth: { hmac: { secretKeys: { default: process.env.HMAC_SECRET_KEY } } }, body: CreatePlanMapper.schema, responses: { 200: PlanMapper.schema } }, async (req, res) => { res.status(200).json(await planService.createPlan(req.body)); } ); // Path parameter example export const getPlan = handlers.get( schemaValidator, '/:id', { name: 'Get Plan', summary: 'Get a plan', auth: { hmac: { secretKeys: { default: process.env.HMAC_SECRET_KEY } } }, params: IdSchema, // Reusable schema: { id: string } responses: { 200: PlanSchemas.PlanSchema } }, async (req, res) => { res.status(200).json(await planService.getPlan(req.params)); } ); // Query parameter example export const listPlans = handlers.get( schemaValidator, '/', { name: 'List Plans', summary: 'List plans', query: IdsSchema, // Reusable schema: { ids: array(string) } auth: { hmac: { secretKeys: { default: process.env.HMAC_SECRET_KEY } } }, responses: { 200: array(PlanSchemas.PlanSchema) } }, async (req, res) => { res.status(200).json(await planService.listPlans(req.query)); } ); // Delete endpoint returning string export const deletePlan = handlers.delete( schemaValidator, '/:id', { name: 'Delete Plan', summary: 'Delete a plan', params: IdSchema, auth: { hmac: { secretKeys: { default: process.env.HMAC_SECRET_KEY } } }, responses: { 200: string } }, async (req, res) => { await planService.deletePlan(req.params); res.status(200).send(`Deleted plan ${req.params.id}`); } ); ``` ``` -------------------------------- ### Initialize Service with ForkLaunch CLI Source: https://forklaunch.com/docs/cli/init Use this command to initialize a new service. You can specify the service name, database type, and infrastructure components. ```bash forklaunch init service [OPTIONS] [name] ``` -------------------------------- ### Global Delete Examples Source: https://forklaunch.com/docs/cli/delete Demonstrates various ways to use the delete command, including deleting services with and without confirmation, specifying a custom path, and a batch deletion script for multiple components. ```bash # Delete with confirmation forklaunch delete service billing # Delete without confirmation forklaunch delete service billing --continue # Delete in specific directory forklaunch delete service billing --path ~/ my-app # Batch deletion script forklaunch delete service old-service --continue forklaunch delete worker deprecated-worker --continue ``` -------------------------------- ### Generated OpenAPI 3.1.0 Specification Example Source: https://forklaunch.com/docs/guides/contract-first-development This is an example of an OpenAPI 3.1.0 specification generated by ForkLaunch, detailing API paths, operations, request bodies, and responses. ```yaml openapi: 3.1.0 info: title: Users API version: 1.0.0 description: User management API servers: - url: https://api.example.com description: Production - url: http://localhost:3000 description: Development paths: /users: post: operationId: User Post summary: Create a new user tags: - Users requestBody: required: true content: application/json: schema: type: object properties: name: type: string email: type: string age: type: number role: type: string enum: [user, admin] required: - name - email - role responses: '200': description: Successful response content: application/json: schema: type: object properties: id: type: string name: type: string email: type: string createdAt: type: string format: date-time /users/{id}: get: operationId: User Get summary: Get user by ID parameters: - name: id in: path required: true schema: type: string - name: include in: query required: false schema: type: array items: type: string responses: '200': description: User found '404': description: User not found ``` -------------------------------- ### Initialize Fresh Application Sync Source: https://forklaunch.com/docs/guides/cli-commands Synchronizes all components of a fresh ForkLaunch application. Use this command after creating a new application to set up all artifacts and configurations. ```bash # After creating a new ForkLaunch application forklaunch sync all --confirm-all ``` -------------------------------- ### Development Setup with Live SDK Mode Source: https://forklaunch.com/docs/guides/cli-commands Initiates development with live SDK mode, enabling hot type reloading for services. Changes made to services will be reflected immediately in type updates. ```bash # Start development with live SDK mode forklaunch sdk mode --type live # Work on services with hot type reloading # Make changes and see type updates immediately ``` -------------------------------- ### Example S3 Lifecycle Policy Configuration Source: https://forklaunch.com/docs/guides/objectstore An example JSON configuration for S3 bucket lifecycle rules, specifying expiration for objects with a 'temp/' prefix after 7 days. ```json { "Rules": [ { "Id": "DeleteTempFilesAfter7Days", "Status": "Enabled", "Prefix": "temp/", "Expiration": { "Days": 7 } } ] } ``` -------------------------------- ### Initialize a Library with Description Source: https://forklaunch.com/docs/adding-projects Create a shared library and provide a description for its functionality. This helps in understanding the purpose of the library at a glance. ```bash forklaunch init library validation --path ./my-app/src/modules --description "Input validation utilities" ``` -------------------------------- ### Example .npmrc Format for Private Registry Source: https://forklaunch.com/docs/guides/docker-build-secrets This is an example of how your .npmrc file should be formatted to authenticate with private registries, including GitHub Packages. Ensure the token is correctly referenced. ```ini //registry.npmjs.org/:_authToken=${NPM_TOKEN} @your-scope:registry=https://npm.pkg.github.com //npm.pkg.github.com/:_authToken=${GITHUB_TOKEN} ``` -------------------------------- ### Initialize a new ForkLaunch application Source: https://forklaunch.com/docs/creating-an-application Run this command to scaffold a new multi-service application. ForkLaunch will prompt for runtime, HTTP framework, and other configurations. ```bash forklaunch init app my-app cd my-app ``` -------------------------------- ### Initialize a Service with Multiple Infrastructure Source: https://forklaunch.com/docs/adding-projects Create a service that integrates with multiple infrastructure components, such as Redis and S3 storage. This allows for more complex data handling and storage needs. ```bash forklaunch init service files --path ./my-app/src/modules --database postgresql --infrastructure redis s3 ``` -------------------------------- ### Setup Test Database with Migrations for Blueprint Testing Source: https://forklaunch.com/docs/guides/testing Configure BlueprintTestHarness for PostgreSQL, enabling migrations and specifying the migration path. Includes setup for test data using an EntityManager. ```typescript import { BlueprintTestHarness, clearTestDatabase } from '@forklaunch/testing'; import * as path from 'path'; let harness: BlueprintTestHarness; let orm: MikroORM; const setupTestDatabase = async () => { harness = new BlueprintTestHarness({ getConfig: async () => { const { default: config } = await import('../mikro-orm.config'); return config; }, databaseType: 'postgres', useMigrations: true, // Use migrations for IAM blueprints migrationsPath: path.join(__dirname, '../migrations') }); const setup = await harness.setup(); orm = setup.orm!; return setup; }; const setupTestData = async (em: EntityManager) => { const { User } = await import('../persistence/entities/user.entity'); const { Role } = await import('../persistence/entities/role.entity'); const role = em.create(Role, { id: '123e4567-e89b-12d3-a456-426614174000', name: 'admin' }); em.create(User, { id: '123e4567-e89b-12d3-a456-426614174001', email: 'test@example.com', name: 'Test User', roles: [role] }); await em.flush(); }; describe('User API', () => { beforeAll(async () => { await setupTestDatabase(); }, 60000); beforeEach(async () => { await clearTestDatabase({ orm }); const em = orm.em.fork(); await setupTestData(em); }); afterAll(async () => { await harness.cleanup(); }, 30000); it('should get a user', async () => { const { getUserRoute } = await import('../api/routes/user.routes'); const response = await getUserRoute.sdk.getUser({ params: { id: '123e4567-e89b-12d3-a456-426614174001' }, headers: { authorization: TEST_TOKENS.AUTH } }); expect(response.code).toBe(200); expect(response.response.email).toBe('test@example.com'); }); }); ``` -------------------------------- ### Start Development Mode with Hot Reload Source: https://forklaunch.com/docs/local-development Starts all services with hot reloading enabled. File changes are automatically detected, allowing individual services to restart without rebuilding the entire stack. ```bash pnpm dev ``` -------------------------------- ### Microservices Dependency Group Example Source: https://forklaunch.com/docs/cli/depcheck Example TOML configuration for grouping microservices. 'auth_services' includes 'auth-api' and 'user-api', while 'data_services' includes 'analytics-api' and 'reporting-api'. This is useful for ensuring shared dependencies are consistent across related services. ```toml [project-peer-topologies] auth_services = ["auth-api", "user-api"] data_services = ["analytics-api", "reporting-api"] ``` -------------------------------- ### Zod Schema Validation Setup Source: https://forklaunch.com/docs/guides/websockets Initialize `ZodSchemaValidator` and define your message schemas using Zod. This setup enables type-safe message handling for client and server communications, including complex structures like discriminated unions. ```typescript import { ZodSchemaValidator } from '@forklaunch/validator/zod'; import { z } from 'zod'; const validator = new ZodSchemaValidator(); const schemas = { ping: { shape: z.object({ ts: z.number() }) }, pong: { shape: z.object({ ts: z.number() }) }, clientMessages: { // Discriminated union for type safety chat: { shape: z.object({ type: z.literal('chat'), message: z.string().min(1).max(1000), userId: z.string().uuid(), roomId: z.string().optional() }) }, typing: { shape: z.object({ type: z.literal('typing'), userId: z.string().uuid(), isTyping: z.boolean() }) } }, serverMessages: { chat: { shape: z.object({ type: z.literal('chat'), message: z.string(), userId: z.string().uuid(), username: z.string(), timestamp: z.string().datetime() }) }, userJoined: { shape: z.object({ type: z.literal('user-joined'), userId: z.string().uuid(), username: z.string() }) } }, errors: { error: { shape: z.object({ code: z.string(), message: z.string(), details: z.unknown().optional() }) } }, closeReason: { normal: { shape: z.object({ code: z.literal(1000), message: z.string() }) }, unauthorized: { shape: z.object({ code: z.literal(1008), message: z.string() }) } } }; ``` -------------------------------- ### Scaffold a New Application with CLI Source: https://forklaunch.com/docs/getting-started Manually scaffold a new application using the ForkLaunch CLI. Follow the interactive prompts to set up your project structure. ```bash forklaunch init application "my-app" ``` -------------------------------- ### Frontend/Backend Split Dependency Group Example Source: https://forklaunch.com/docs/cli/depcheck Example TOML configuration for separating frontend and backend dependency checks. 'frontend' groups 'web-app' and 'mobile-app', while 'backend' groups 'api-server' and 'worker'. This helps manage dependencies specific to each part of the application. ```toml [project-peer-topologies] frontend = ["web-app", "mobile-app"] backend = ["api-server", "worker"] ``` -------------------------------- ### Initialize New Services with ForkLaunch CLI Source: https://forklaunch.com/docs/creating-an-application Use the ForkLaunch CLI to quickly initialize new services, each with its own isolated database, routes, and Docker configuration. This command automatically updates your project manifest and sets up necessary infrastructure. ```bash forklaunch init service products forklaunch init service orders ``` -------------------------------- ### setupRedisContainer Source: https://forklaunch.com/docs/guides/testing Setup a Redis test container with optional configuration. ```APIDOC ## setupRedisContainer ### Description Setup a Redis test container. ### Method ```typescript async setupRedisContainer(config?: RedisConfig): Promise ``` ### Parameters #### Request Body * `config` (RedisConfig): Optional configuration for the Redis container. * `command` (string[]): Default: ['redis-server', '--appendonly', 'yes'] ### Example ```typescript const container = await manager.setupRedisContainer({ command: ['redis-server', '--maxmemory', '256mb'] }); ``` ``` -------------------------------- ### Troubleshooting Local Development Setup Source: https://forklaunch.com/docs/local-development Steps to troubleshoot common errors after adding a new service, including ensuring Docker containers are running, initializing/applying migrations, and rebuilding the application. ```bash # Make sure Docker containers are running docker-compose up -d # Initialize and apply migrations for the new service pnpm migrate:init pnpm migrate:up # Rebuild if necessary pnpm build && pnpm dev ```