### Complete Multi-Tenant Job Architecture Example Source: https://github.com/felipebarcelospro/igniter-js/blob/main/apps/www/content/docs/jobs/multi-tenancy.mdx A comprehensive example demonstrating the setup of a multi-tenant job system, including adapter creation, tenant router factory, and job merging. ```typescript // 1. Create adapter with global prefix const jobs = createBullMQAdapter({ store: redisStore, globalPrefix: process.env.ENVIRONMENT || 'local', }); // 2. Factory function for tenant routers function createTenantJobRouter(tenantId: string) { return jobs.router({ namespace: `tenant-${tenantId}`, defaultOptions: { queue: { name: 'default', prefix: `tenant-${tenantId}`, }, }, jobs: { processOrder: jobs.register({ name: 'Process Order', input: z.object({ orderId: z.string() }), handler: async ({ payload, context }) => { // Use tenant-specific database const tenantDb = context.getTenantDatabase(tenantId); return await tenantDb.orders.process(payload.orderId); }, }), sendEmail: jobs.register({ name: 'Send Email', input: z.object({ email: z.string().email() }), handler: async ({ payload }) => { // Job logic }, }), }, }); } // 3. Create routers for tenants const tenants = ['acme', 'contoso', 'fabrikam']; const tenantRouters = tenants.reduce((acc, tenantId) => { acc[`tenant-${tenantId}`] = createTenantJobRouter(tenantId); return acc; }, {} as Record); // 4. Merge all tenant routers export const REGISTERED_JOBS = jobs.merge(tenantRouters); // 5. Use in application await igniter.jobs['tenant-acme'].schedule({ task: 'processOrder', input: { orderId: '123' }, }); ``` -------------------------------- ### Install Dependencies and Sync Database Source: https://github.com/felipebarcelospro/igniter-js/wiki/06-Starter-Guides/02-Tanstack-Start-Starter-Guide After setting up the environment and starting services, install project dependencies and apply the Prisma schema to your database. ```bash npm install npx prisma db push ``` -------------------------------- ### Igniter.js Context Setup Example Source: https://github.com/felipebarcelospro/igniter-js/blob/main/apps/www/content/docs/core/(core-concepts)/context.mdx This example demonstrates a production-ready context setup in Igniter.js. It includes core dependencies like database and Redis clients, services, authentication logic, request metadata extraction, and feature flags. Use this as a template for your application's context. ```typescript import { Igniter } from '@igniter-js/core'; import { PrismaClient } from '@prisma/client'; import { Redis } from 'ioredis'; // Services const db = new PrismaClient(); const redis = new Redis(process.env.REDIS_URL); const emailService = createEmailService(); // Context callback const igniter = Igniter .context(async (req: Request) => { // Extract request metadata const requestId = crypto.randomUUID(); const ip = req.headers.get('x-forwarded-for') || 'unknown'; const userAgent = req.headers.get('user-agent') || 'unknown'; // Authentication const token = req.headers.get('authorization')?.replace('Bearer ', ''); let user = null; let session = null; if (token) { try { const decoded = await verifyJWT(token); user = await db.users.findUnique({ where: { id: decoded.userId } }); session = await redis.get(`session:${decoded.sessionId}`); } catch (error) { console.error('Auth error:', error); } } return { // Core dependencies db, redis, // Services email: emailService, // Authentication user, session, // Request metadata requestId, ip, userAgent, timestamp: new Date(), // Feature flags features: { enableAnalytics: process.env.FEATURE_ANALYTICS === 'true', enableNotifications: process.env.FEATURE_NOTIFICATIONS === 'true' } }; }) .create(); export { igniter }; ``` -------------------------------- ### Quick Example: Setting Up and Using Igniter Jobs Source: https://github.com/felipebarcelospro/igniter-js/blob/main/apps/www/content/docs/jobs/index.mdx Demonstrates the basic setup for Igniter.js Jobs, including adapter creation, job router definition, merging routers, registering with Igniter, and scheduling a job. ```typescript // 1. Create the adapter import { createBullMQAdapter } from '@igniter-js/adapter-bullmq'; import { createRedisStoreAdapter } from '@igniter-js/adapter-redis'; import { Redis } from 'ioredis'; import { z } from 'zod'; const redis = new Redis(process.env.REDIS_URL); const store = createRedisStoreAdapter({ client: redis }); const jobs = createBullMQAdapter({ store, autoStartWorker: { concurrency: 5 }, }); // 2. Define a job router const emailRouter = jobs.router({ namespace: 'emails', jobs: { sendWelcome: jobs.register({ input: z.object({ email: z.string().email() }), handler: async ({ payload, context }) => { await context.emailService.sendWelcome(payload.email); return { sent: true }; }, }), }, }); // 3. Merge routers const REGISTERED_JOBS = jobs.merge({ emails: emailRouter, }); // 4. Register with Igniter import { Igniter } from '@igniter-js/core'; export const igniter = Igniter .context() .store(store) .jobs(REGISTERED_JOBS) .create(); // 5. Use in your actions igniter.jobs.emails.schedule({ task: 'sendWelcome', input: { email: 'user@example.com' }, }); ``` -------------------------------- ### Install Redis on macOS Source: https://github.com/felipebarcelospro/igniter-js/blob/main/apps/www/content/docs/(store)/installation.mdx Install and start the Redis server on macOS using Homebrew. ```bash brew install redis brew services start redis ``` -------------------------------- ### Initialize TanStack Start Project with Igniter.js CLI Source: https://github.com/felipebarcelospro/igniter-js/wiki/06-Starter-Guides/02-Tanstack-Start-Starter-Guide Use this command to scaffold a new project. Select 'TanStack Start' during setup and enable 'Store (Redis)' and 'Queues (BullMQ)' for full feature support. ```bash npx @igniter-js/cli init my-tanstack-app ``` -------------------------------- ### Complete Example: Dynamic Command Loading Source: https://github.com/felipebarcelospro/igniter-js/blob/main/apps/www/content/docs/bots/(commands)/dynamic-commands.mdx Demonstrates dynamically loading commands from a directory, ideal for production bots. This example scans a directory, imports command modules, and registers them before starting the bot. ```typescript import { Bot, telegram } from '@igniter-js/bot' import { readdir } from 'fs/promises' import { join } from 'path' const bot = Bot.create({ id: 'dynamic-bot', name: 'Dynamic Bot', adapters: { telegram: telegram({ token: process.env.TELEGRAM_TOKEN!, handle: '@dynamic_bot', webhook: { url: process.env.TELEGRAM_WEBHOOK_URL! } }) }, commands: { start: { name: 'start', aliases: [], description: 'Start the bot', help: 'Use /start', async handle(ctx) { await ctx.bot.send({ provider: ctx.provider, channel: ctx.channel.id, content: { type: 'text', content: 'Bot started! Commands loaded dynamically.' } }) } } } }) // Load commands from directory async function loadCommands() { const commandsDir = join(__dirname, 'commands') const files = await readdir(commandsDir) for (const file of files) { if (file.endsWith('.ts')) { const commandModule = await import(`./commands/${file}`) const command = commandModule.default bot.registerCommand(command.name, command) console.log(`Loaded command: ${command.name}`) } } } // Load commands on startup await loadCommands() await bot.start() ``` -------------------------------- ### Initialize New Project with Igniter.js CLI Source: https://github.com/felipebarcelospro/igniter-js/blob/main/apps/www/content/learn/01-creating-your-project.mdx Use this command to start a new project named 'shortify' with the Igniter.js CLI. It launches an interactive setup wizard. ```bash npx @igniter-js/cli init shortify ``` -------------------------------- ### Start Docker Services Source: https://github.com/felipebarcelospro/igniter-js/wiki/06-Starter-Guides/03-Bun-React-Starter-Guide Launch the PostgreSQL database and Redis instance using Docker Compose. Ensure these services are running before proceeding with installation. ```bash docker-compose up -d ``` -------------------------------- ### Complete Igniter MCP Server Configuration Example Source: https://github.com/felipebarcelospro/igniter-js/blob/main/apps/www/content/docs/mcp-server/builder-pattern.mdx This comprehensive example demonstrates building an Igniter MCP Server with various configurations, including server info, instructions, custom tools, prompts, resources, OAuth, and event handlers. It shows how to chain multiple builder methods for a fully customized server setup. ```typescript import { IgniterMcpServer } from '@igniter-js/adapter-mcp-server'; import { AppRouter } from '@/igniter.router'; import { z } from 'zod'; const { handler, auth } = IgniterMcpServer .create() .router(AppRouter) .withServerInfo({ name: 'Acme Corporation API', version: '1.0.0', }) .withInstructions( "This server provides tools to manage users, products, and orders. " + "Use the appropriate tools to interact with each resource." ) .addTool({ name: 'calculateTax', description: 'Calculate tax for an amount', args: { amount: z.number(), taxRate: z.number(), }, handler: async (args, context) => { const tax = args.amount * args.taxRate; return { content: [{ type: 'text', text: `Tax: $${tax.toFixed(2)}` }] }; }, }) .addPrompt({ name: 'debugUser', description: 'Debug user account', args: { userId: z.string() }, handler: async (args, context) => { return { messages: [{ role: 'user', content: { type: 'text', text: `Debug user ${args.userId}` } }] }; }, }) .addResource({ uri: 'config://app/settings', name: 'App Settings', description: 'Application configuration', mimeType: 'application/json', handler: async (context) => { const settings = await getAppSettings(); return { contents: [{ uri: 'config://app/settings', mimeType: 'application/json', text: JSON.stringify(settings, null, 2) }] }; } }) .withOAuth({ issuer: 'https://auth.example.com', verifyToken: async ({ bearerToken, context }) => { const result = await verifyJWT(bearerToken); return { valid: result.valid, user: result.user }; } }) .withEvents({ onToolCall: async (toolName, args, context) => { console.log(`Tool called: ${toolName}`); }, onToolError: async (toolName, error, context) => { console.error(`Tool error: ${toolName}`, error); } }) .build(); export const GET = handler; export const POST = handler; export const OPTIONS = auth.cors; ``` -------------------------------- ### Complete Advanced MCP Server Example Source: https://github.com/felipebarcelospro/igniter-js/blob/main/apps/www/content/docs/mcp-server/advanced.mdx This example demonstrates a comprehensive setup of an MCP server, integrating custom tool transformations, response formatting, logging, and event handling. ```typescript import { IgniterMcpServer } from '@igniter-js/adapter-mcp-server'; import { ServerCapabilities } from '@modelcontextprotocol/sdk/types'; const { handler, auth } = IgniterMcpServer .create() .router(AppRouter) .withServerInfo({ name: 'Advanced MCP Server', version: '1.0.0', }) .withInstructions( "This server provides advanced tools for managing resources. " + "Use appropriate tools based on your needs." ) .withCapabilities({ tools: { listChanged: true }, resources: { subscribe: true }, }) .withToolTransform((controller, action, actionConfig) => { // Only expose public actions if (!actionConfig.tags?.includes('public')) { return null; } // Custom naming and description return { name: `${controller}_${action}`, description: actionConfig.summary || actionConfig.description || `Execute ${action}`, schema: actionConfig.body || actionConfig.query || {}, tags: [controller, actionConfig.method?.toLowerCase()].filter(Boolean), }; }) .withResponse({ transform: async (igniterResponse, toolName, context) => { return { content: [{ type: 'text', text: JSON.stringify(igniterResponse, null, 2) }] }; }, onError: async (error, toolName, context) => { return { content: [{ type: 'text', text: `Error in ${toolName}: ${error.message}` }], isError: true }; } }) .withLogger({ log: (message) => console.log(`[MCP] ${message}`), error: (message) => console.error(`[MCP ERROR] ${message}`), warn: (message) => console.warn(`[MCP WARN] ${message}`), debug: (message) => console.debug(`[MCP DEBUG] ${message}`), }) .withEvents({ onToolCall: async (toolName, args, context) => { console.log(`Tool called: ${toolName}`); }, onToolError: async (toolName, error, context) => { console.error(`Tool error: ${toolName}`, error); } }) .build(); export const GET = handler; export const POST = handler; ``` -------------------------------- ### Start Production Server Source: https://github.com/felipebarcelospro/igniter-js/blob/main/apps/starter-bun-rest-api/README.md Starts the application in production mode. ```bash bun run start ``` -------------------------------- ### Copy Environment Example File Source: https://github.com/felipebarcelospro/igniter-js/blob/main/apps/www/content/learn/01-creating-your-project.mdx Create a local environment file by copying the provided example file. ```bash cp .env.example .env ``` -------------------------------- ### Complete Bot Example with Custom Adapter Source: https://github.com/felipebarcelospro/igniter-js/blob/main/apps/www/content/docs/bots/(adapters)/creating-custom-adapters.mdx This TypeScript code demonstrates how to create and start a bot using a custom adapter. It shows the integration of the custom adapter factory with the Bot.create function and includes a sample command handler. ```typescript import { Bot } from '@igniter-js/bot' import { myPlatform } from './adapters/my-platform' const bot = Bot.create({ id: 'my-bot', name: 'My Bot', adapters: { myPlatform: myPlatform({ apiKey: process.env.MY_PLATFORM_API_KEY!, handle: 'mybot' }) }, commands: { start: { name: 'start', description: 'Start command', async handle(ctx) { await ctx.bot.send({ provider: 'my-platform', channel: ctx.channel.id, content: { type: 'text', content: 'Hello from my platform!' } }) } } } }) await bot.start() ``` -------------------------------- ### Start Bot with Telegram Webhook Setup Source: https://github.com/felipebarcelospro/igniter-js/blob/main/apps/www/content/docs/bots/(adapters)/telegram.mdx When bot.start() is called, the Telegram adapter automatically handles webhook setup, including deleting old webhooks, syncing commands, and registering the new endpoint. Ensure your bot's token and webhook URL are correctly configured. ```typescript import { Bot, telegram } from '@igniter-js/bot' const bot = Bot.create({ id: 'my-bot', name: 'My Bot', adapters: { telegram: telegram({ token: process.env.TELEGRAM_TOKEN!, handle: '@my_bot', webhook: { url: 'https://your-domain.com/api/telegram', secret: process.env.TELEGRAM_SECRET } }) } }) // This automatically sets up the webhook await bot.start() ``` -------------------------------- ### Development Setup with Simple OpenTelemetry Adapter Source: https://github.com/felipebarcelospro/igniter-js/blob/main/packages/adapter-opentelemetry/README.md Set up a basic OpenTelemetry adapter for development environments. This example shows how to integrate it with Igniter.js and manually create child spans for database operations. ```typescript import { Igniter } from '@igniter-js/core'; import { createSimpleOpenTelemetryAdapter } from '@igniter-js/adapter-opentelemetry'; // Simple setup for development const telemetry = await createSimpleOpenTelemetryAdapter('my-api'); const igniter = Igniter .context<{ db: Database }>() .telemetry(telemetry) .create(); export const router = igniter.router({ getUser: igniter.query({ handler: async ({ context, input }) => { // Telemetry is automatically injected const span = context.span; // Current HTTP span const childSpan = context.telemetry.startSpan('db.query'); try { const user = await context.db.user.findUnique({ where: { id: input.id } }); childSpan.setTag('user.found', !!user); return user; } finally { childSpan.finish(); } } }) }); ``` -------------------------------- ### Install Dependencies Source: https://github.com/felipebarcelospro/igniter-js/blob/main/CONTRIBUTING.md Use this command to install project dependencies. ```bash bun install ``` -------------------------------- ### Install OpenTelemetry Adapter and Dependencies Source: https://github.com/felipebarcelospro/igniter-js/blob/main/packages/adapter-opentelemetry/README.md Install the main adapter package and necessary OpenTelemetry SDKs. Also, install optional exporters for specific backends like Jaeger, Prometheus, or OTLP. ```bash npm install @igniter-js/adapter-opentelemetry # Peer dependencies (install the exporters you need) npm install @opentelemetry/api @opentelemetry/sdk-node # Optional exporters npm install @opentelemetry/exporter-jaeger # For Jaeger npm install @opentelemetry/exporter-prometheus # For Prometheus npm install @opentelemetry/exporter-otlp-http # For OTLP ``` -------------------------------- ### Start Development Server with Custom Port Source: https://github.com/felipebarcelospro/igniter-js/blob/main/apps/www/content/learn/01-creating-your-project.mdx Starts the development server on a custom port. ```bash npx igniter dev --port 4000 ``` -------------------------------- ### Install Redis Adapter with bun Source: https://github.com/felipebarcelospro/igniter-js/blob/main/apps/www/content/docs/(store)/installation.mdx Install the Redis adapter and its peer dependency ioredis using bun. ```bash bun add @igniter-js/adapter-redis ioredis ``` -------------------------------- ### Start Production Server Script Source: https://github.com/felipebarcelospro/igniter-js/blob/main/apps/starter-deno-rest-api/README.md Starts the Deno application in production mode. ```bash deno task start ``` -------------------------------- ### Minimal Igniter.js Setup Source: https://github.com/felipebarcelospro/igniter-js/blob/main/apps/www/content/docs/core/(core-concepts)/builder.mdx A basic setup for Igniter.js, suitable for getting started or simple APIs. It requires importing Igniter and defining the application context. ```typescript import { Igniter } from '@igniter-js/core'; interface AppContext { db: Database; } const igniter = Igniter .context(createIgniterAppContext()) .create(); // Ready to create actions! ``` -------------------------------- ### Complete Telegram Bot Example Source: https://github.com/felipebarcelospro/igniter-js/blob/main/apps/www/content/docs/bots/(adapters)/telegram.mdx This example demonstrates the full setup of a Telegram bot using Igniter.js, including adapter configuration, command handling, message logging, and error handling. It's a starting point for building your own Telegram bots. ```typescript import { Bot, telegram } from '@igniter-js/bot' const bot = Bot.create({ id: 'telegram-bot', name: 'Telegram Bot', adapters: { telegram: telegram({ token: process.env.TELEGRAM_TOKEN!, handle: '@my_telegram_bot', webhook: { url: process.env.TELEGRAM_WEBHOOK_URL!, secret: process.env.TELEGRAM_SECRET } }) }, commands: { start: { name: 'start', aliases: ['hello'], description: 'Start the bot', help: 'Use /start to begin', async handle(ctx) { await ctx.bot.send({ provider: ctx.provider, channel: ctx.channel.id, content: { type: 'text', content: `👋 Hello! Welcome to ${ctx.bot.name}` } }) } } }, on: { message: async (ctx) => { // Log all text messages if (ctx.message.content?.type === 'text') { console.log(`Text from ${ctx.message.author.name}: ${ctx.message.content.content}`) } }, error: async (ctx) => { // @ts-expect-error console.error('Error:', ctx.error) } } }) await bot.start() ``` -------------------------------- ### bot.start Source: https://github.com/felipebarcelospro/igniter-js/blob/main/apps/www/content/docs/bots/api-reference.mdx Initializes all configured adapters, including setting up webhooks and synchronizing commands. ```APIDOC ## bot.start() ### Description Initializes all adapters (webhooks, command sync). ### Returns - `Promise` ### Example ```typescript await bot.start() ``` ``` -------------------------------- ### Install Redis on Linux (Ubuntu/Debian) Source: https://github.com/felipebarcelospro/igniter-js/blob/main/apps/www/content/docs/(store)/installation.mdx Install and start the Redis server on Ubuntu/Debian-based Linux distributions. ```bash sudo apt-get install redis-server sudo systemctl start redis ``` -------------------------------- ### Navigate to Project Directory Source: https://github.com/felipebarcelospro/igniter-js/wiki/01-Getting-Started/01-Quick-Start-Guide After initializing the project, change into the newly created project directory. ```bash cd my-first-api ``` -------------------------------- ### Initialize Project Interactively Source: https://github.com/felipebarcelospro/igniter-js/blob/main/apps/www/content/blog/introducing-igniter-templates.mdx Use this command to start a new project and follow interactive prompts to select your desired template. ```bash npx @igniter-js/cli init my-app # Follow prompts to select template ``` -------------------------------- ### Install Redis Adapter with npm Source: https://github.com/felipebarcelospro/igniter-js/blob/main/apps/www/content/docs/(store)/installation.mdx Install the Redis adapter and its peer dependency ioredis using npm. ```bash npm install @igniter-js/adapter-redis ioredis ``` -------------------------------- ### Clone Repository and Navigate Source: https://github.com/felipebarcelospro/igniter-js/blob/main/apps/starter-deno-rest-api/README.md Clone the starter repository and navigate into the Deno REST API application directory. ```bash git clone https://github.com/felipebarcelospro/igniter-js.git cd igniter-js/apps/starter-deno-rest-api ``` -------------------------------- ### Start Local Services with Docker Compose Source: https://github.com/felipebarcelospro/igniter-js/blob/main/apps/www/content/blog/introducing-igniter-templates.mdx Start PostgreSQL and Redis services locally using Docker Compose. Ensure Docker is installed and running. ```bash # Start PostgreSQL and Redis with Docker docker-compose up -d ``` -------------------------------- ### Quick Start Igniter.js Bot Source: https://github.com/felipebarcelospro/igniter-js/blob/main/packages/bot/README.md Create a basic Telegram bot using the IgniterBot builder. This example shows how to add an adapter, define a command, and start the bot. ```typescript import { IgniterBot, telegram } from '@igniter-js/bot' const bot = IgniterBot .create() .withHandle('@mybot') // ← Your bot's handle (ID and name auto-derived) .addAdapter('telegram', telegram({ token: process.env.TELEGRAM_TOKEN!, // handle inherited from global })) .addCommand('start', { name: 'start', aliases: ['hello'], description: 'Start the bot', help: 'Use /start to begin', async handle(ctx) { await ctx.reply('👋 Welcome! I am your bot.') } }) .build() // Initialize the bot (registers webhooks, commands, etc) await bot.start() // Use in Next.js API route export async function POST(req: Request) { return bot.handle('telegram', req) } ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/felipebarcelospro/igniter-js/blob/main/apps/starter-bun-react-app/README.md Create a .env file in the starter's root directory and add your Redis connection URL. ```env # .env REDIS_URL="redis://127.0.0.1:6379" ``` -------------------------------- ### Complete Igniter.js Bot Example Source: https://github.com/felipebarcelospro/igniter-js/blob/main/apps/www/content/docs/bots/(commands)/command-basics.mdx A full example of an Igniter.js bot featuring 'start', 'info', and 'echo' commands. It demonstrates bot creation, adapter configuration, and command definitions. ```typescript import { Bot, telegram } from '@igniter-js/bot' const bot = Bot.create({ id: 'example-bot', name: 'Example Bot', adapters: { telegram: telegram({ token: process.env.TELEGRAM_TOKEN!, handle: '@example_bot', webhook: { url: process.env.TELEGRAM_WEBHOOK_URL! } }) }, commands: { start: { name: 'start', aliases: ['hello'], description: 'Start the bot', help: 'Use /start to begin', async handle(ctx) { await ctx.bot.send({ provider: ctx.provider, channel: ctx.channel.id, content: { type: 'text', content: `👋 Welcome, ${ctx.message.author.name}!` } }) } }, info: { name: 'info', aliases: ['about'], description: 'Show bot information', help: 'Use /info to see bot details', async handle(ctx) { const info = ` 🤖 Bot Information Name: ${ctx.bot.name} ID: ${ctx.bot.id} Provider: ${ctx.provider} Channel: ${ctx.channel.name} `.trim() await ctx.bot.send({ provider: ctx.provider, channel: ctx.channel.id, content: { type: 'text', content: info } }) } }, echo: { name: 'echo', aliases: [], description: 'Echo your message', help: 'Usage: /echo ', async handle(ctx, params) { if (params.length === 0) { await ctx.bot.send({ provider: ctx.provider, channel: ctx.channel.id, content: { type: 'text', content: '❌ Please provide text.\nUsage: /echo ' } }) return } await ctx.bot.send({ provider: ctx.provider, channel: ctx.channel.id, content: { type: 'text', content: params.join(' ') } }) } } } }) await bot.start() ``` -------------------------------- ### Start Development Server with Igniter Studio Source: https://github.com/felipebarcelospro/igniter-js/blob/main/apps/www/content/blog/introducing-igniter-studio.mdx Start the development server and enable Igniter Studio by passing the --docs flag to the npm run dev script. Alternatively, configure this permanently in package.json. ```bash # Start dev server with Studio npm run dev -- --docs ``` ```json # Or configure it permanently # package.json { "scripts": { "dev": "igniter dev --docs" } } ``` -------------------------------- ### Start Application Source: https://github.com/felipebarcelospro/igniter-js/blob/main/apps/www/content/docs/jobs/getting-started.mdx Use this command to start your application in development mode. Ensure your environment variables are correctly set. ```bash npm run dev ``` -------------------------------- ### Run the Development Server Source: https://github.com/felipebarcelospro/igniter-js/blob/main/apps/sample-realtime-chat/README.md Start the Next.js development server. ```bash bun dev ``` -------------------------------- ### Clone the Igniter.js Repository Source: https://github.com/felipebarcelospro/igniter-js/blob/main/apps/www/content/templates/starter-nextjs.mdx Clone the official Igniter.js repository to get started with the starter-nextjs template. ```bash git clone https://github.com/felipebarcelospro/igniter-js.git cd igniter-js/apps/starter-nextjs ``` -------------------------------- ### Initialize Deno API Project Source: https://github.com/felipebarcelospro/igniter-js/blob/main/apps/www/content/blog/introducing-igniter-templates.mdx Use this command to create a new project with the Deno API template. ```bash npx @igniter-js/cli init my-api --template deno-api ``` -------------------------------- ### Install Dependencies and Sync Database Source: https://github.com/felipebarcelospro/igniter-js/wiki/06-Starter-Guides/03-Bun-React-Starter-Guide Install project dependencies using Bun for speed, then apply the Prisma schema to synchronize the database. This step ensures your database is ready for the application. ```bash bun install bunx prisma db push ``` -------------------------------- ### Scaffold a New Igniter.js Project Source: https://github.com/felipebarcelospro/igniter-js/wiki/05-CLI-and-Tooling/01-igniter-init Run this command in your terminal to create a new project directory and start the interactive setup process. ```bash npx @igniter-js/cli init my-awesome-api ``` -------------------------------- ### AI Command to Start Development Server Source: https://github.com/felipebarcelospro/igniter-js/blob/main/apps/www/content/blog/announcing-igniter-mcp-server.mdx This example shows how an AI can trigger the Igniter.js development server with live reloading and client generation. ```typescript // AI can execute: start the dev server // Runs: igniter dev --watch ``` -------------------------------- ### Run Development Server Source: https://github.com/felipebarcelospro/igniter-js/blob/main/apps/starter-deno-rest-api/README.md Start the Deno development server with file watching enabled. ```bash deno task dev ``` -------------------------------- ### Initialize Bun API Project Source: https://github.com/felipebarcelospro/igniter-js/blob/main/apps/www/content/blog/introducing-igniter-templates.mdx Use this command to create a new project with the Bun API template. ```bash npx @igniter-js/cli init my-api --template bun-api ``` -------------------------------- ### Basic `curl` Endpoint Test Source: https://github.com/felipebarcelospro/igniter-js/blob/main/apps/starter-tanstack-start/AGENTS.md Construct and execute `curl` commands to test API endpoints. This example demonstrates a basic GET request. ```bash curl http://localhost:3000/api/users ``` -------------------------------- ### Start Development Server Source: https://github.com/felipebarcelospro/igniter-js/blob/main/apps/www/content/learn/01-creating-your-project.mdx Starts the development server with hot-reloading, framework server, interactive dashboard, and auto-generated OpenAPI docs. ```bash npx igniter dev ``` -------------------------------- ### Basic Command Definition Source: https://github.com/felipebarcelospro/igniter-js/blob/main/apps/www/content/docs/bots/(commands)/command-basics.mdx Defines a simple 'start' command that sends a welcome message. This is a fundamental example of how to integrate commands into your bot's configuration. ```typescript import { Bot, telegram } from '@igniter-js/bot' const bot = Bot.create({ adapters: { telegram: telegram({ /* ... */ }) }, commands: { start: { name: 'start', aliases: [], description: 'Start the bot', help: 'Use /start to begin', async handle(ctx) { await ctx.bot.send({ provider: ctx.provider, channel: ctx.channel.id, content: { type: 'text', content: '👋 Welcome!' } }) } } } }) ``` -------------------------------- ### Interacting with Deno KV Source: https://github.com/felipebarcelospro/igniter-js/blob/main/apps/www/content/docs/core/(installation)/deno.mdx Examples of reading and writing data to Deno KV using the `get` and `set` methods on the `kv` object obtained from `Deno.openKv()`. ```typescript const result = await context.db.get(['users', userId]) await context.db.set(['users', userId], userData) ``` -------------------------------- ### Configure Telegram Adapter Source: https://github.com/felipebarcelospro/igniter-js/blob/main/packages/bot/README.md Provides examples for configuring the Telegram adapter, including minimal setup, webhook support, and overriding the global bot handle. ```typescript import { telegram } from '@igniter-js/bot/adapters' // Minimal (uses global bot handle) .addAdapter('telegram', telegram({ token: 'your_bot_token' })) // With webhook .addAdapter('telegram', telegram({ token: 'your_bot_token', webhook: { url: 'https://example.com/api/telegram', secret: 'webhook_secret' } })) // Override global handle for this platform .addAdapter('telegram', telegram({ token: 'your_bot_token', handle: '@custom_telegram_bot' // ← Override })) ``` -------------------------------- ### Bot Testing with Vitest Source: https://github.com/felipebarcelospro/igniter-js/blob/main/packages/bot/README.md Demonstrates how to test a bot's command handling using Vitest. This example sets up a simple bot with a '/start' command and asserts its existence. ```typescript import { describe, it, expect } from 'vitest' import { IgniterBot, telegram } from '@igniter-js/bot' describe('My Bot', () => { it('should respond to /start', async () => { const bot = IgniterBot .create() .withId('test-bot') .withName('Test') .addAdapter('telegram', telegram({ token: 'test', handle: '@test' })) .addCommand('start', { name: 'start', async handle(ctx) { await ctx.reply('Started!') } }) .build() expect(bot).toBeDefined() }) }) ``` -------------------------------- ### Example: Use Store in an Action Source: https://github.com/felipebarcelospro/igniter-js/blob/main/packages/adapter-redis/README.md Demonstrates how to use the store's set and get methods within an action handler to cache user data with a specified TTL. ```typescript handler: async ({ context, response }) => { // Set a value in the cache with a 1-hour TTL await context.store.set('user:123', { name: 'John Doe' }, { ttl: 3600 }); // Get the value const user = await context.store.get('user:123'); return response.success({ user }); } ``` -------------------------------- ### Run Development Server Source: https://github.com/felipebarcelospro/igniter-js/blob/main/apps/starter-bun-rest-api/README.md Start the Bun development server with hot-reloading enabled. ```bash bun run dev ``` -------------------------------- ### Example Controller with API Actions Source: https://github.com/felipebarcelospro/igniter-js/blob/main/apps/starter-bun-react-app/README.md Demonstrates how to implement API queries (GET) and mutations (POST), interact with the cache, and schedule background jobs within an Igniter.js controller. ```typescript import { IgniterController, Query, Mutation } from "@igniterjs/core"; import { z } from "zod"; export const exampleController = new IgniterController({ prefix: "example", actions: { get: Query({ schema: z.object({ id: z.string() }), handler: async ({ ctx, schema }) => { const { id } = schema.parse(ctx.request.query); const cachedData = await ctx.cache.get(id); if (cachedData) { return { data: JSON.parse(cachedData), fromCache: true }; } const data = { id, message: "Hello from Igniter.js!" }; await ctx.cache.set(id, JSON.stringify(data), { ttl: 60 }); return { data, fromCache: false }; }, }), post: Mutation({ schema: z.object({ name: z.string() }), handler: async ({ ctx, schema }) => { const { name } = schema.parse(ctx.request.body); await ctx.jobs.add("welcome_email", { name, email: `${name.toLowerCase()}@example.com`, }); return { message: `Welcome, ${name}! An email will be sent shortly.` }; }, }), }, }); ``` -------------------------------- ### Create Example Controller Source: https://github.com/felipebarcelospro/igniter-js/blob/main/apps/www/content/docs/core/(installation)/deno.mdx Defines a controller for the 'Example' resource with a 'hello' query action. This demonstrates creating a basic API endpoint in Deno using Igniter.js. ```typescript import { igniter } from '@/igniter.ts' export const exampleController = igniter.controller({ name: 'Example', path: '/example', actions: { hello: igniter.query({ path: '/hello', handler: async ({ response }) => { return response.success({ message: 'Hello from Igniter.js with Deno! 🦕', timestamp: new Date().toISOString(), runtime: 'Deno', version: Deno.version.deno }) }, }), }, }) ``` -------------------------------- ### Basic API Endpoint Testing with curl Source: https://github.com/felipebarcelospro/igniter-js/blob/main/rules/instructions.md Construct and execute curl commands to test API endpoints. This example shows testing a GET endpoint for a list and a POST endpoint for creation. ```bash # GET for list curl http://localhost:3000/api/items # POST for create curl -X POST -H "Content-Type: application/json" -d '{"name": "New Item"}' http://localhost:3000/api/items ``` -------------------------------- ### Deno Deploy Installation and Deployment Source: https://github.com/felipebarcelospro/igniter-js/blob/main/apps/www/content/docs/core/(installation)/deno.mdx Instructions for installing the Deno Deploy CLI and deploying a project to Deno's edge network. Ensure you have the necessary permissions. ```bash # Install Deno Deploy CLI deno install --allow-all --no-check -r -f https://deno.land/x/deploy/deployctl.ts # Deploy your project deployctl deploy --project=my-api src/index.ts ``` -------------------------------- ### Interactive Framework Selection Source: https://github.com/felipebarcelospro/igniter-js/wiki/05-CLI-and-Tooling/01-igniter-init During the init process, you will be prompted to select your preferred framework. This choice configures the project's adapters and entry points. ```bash ? Which framework are you using? ❯ Next.js Express Hono Standalone ``` -------------------------------- ### Interactive Feature Selection Source: https://github.com/felipebarcelospro/igniter-js/wiki/05-CLI-and-Tooling/01-igniter-init You can enable optional Igniter.js features like caching or background jobs during setup. Use the spacebar to select features, which will automatically install dependencies and create service files. ```bash ? Which Igniter.js features would you like to enable? ❯ ◯ Igniter.js Store (for Caching, Sessions, Pub/Sub via Redis) ◯ Igniter.js Queues (for Background Jobs via BullMQ) ``` -------------------------------- ### Initialize Pub/Sub Subscriptions on Application Startup Source: https://github.com/felipebarcelospro/igniter-js/blob/main/apps/www/content/docs/store/pubsub.mdx Initialize all necessary Pub/Sub subscriptions when your application starts. This ensures that your system is ready to receive messages immediately. Centralize this setup in a dedicated function for better organization. ```typescript // src/services/subscriptions.ts export const initializeSubscriptions = async (context: AppContext) => { // User events await igniter.store.subscribe('user:created', handleUserCreated); await igniter.store.subscribe('user:updated', handleUserUpdated); await igniter.store.subscribe('user:deleted', handleUserDeleted); // Order events await igniter.store.subscribe('order:created', handleOrderCreated); await igniter.store.subscribe('order:status:changed', handleOrderStatusChanged); // Notifications await igniter.store.subscribe('notifications', handleNotification); console.log('✅ All subscriptions initialized'); }; ``` -------------------------------- ### Set Up Bun Server Source: https://github.com/felipebarcelospro/igniter-js/blob/main/apps/www/content/docs/core/(installation)/bun.mdx Configure and start the Bun HTTP server, mounting the Igniter.js router to handle incoming API requests. ```typescript import { serve } from 'bun' import { AppRouter } from './igniter.router' const IGNITER_API_BASE_PATH = process.env.IGNITER_API_BASE_PATH || '/api/v1/' const server = serve({ routes: { // Mount Igniter.js router [IGNITER_API_BASE_PATH + '*']: AppRouter.handler, }, }) console.log(`🚀 Server running at ${server.url}`) ``` -------------------------------- ### Next.js API Route Handler with Igniter.js Source: https://github.com/felipebarcelospro/igniter-js/blob/main/apps/sample-realtime-chat/README.md Adapter to expose Igniter.js API routes via Next.js API route handlers. This setup allows GET, POST, PUT, and DELETE requests to be handled by the Igniter.js router. ```typescript // src/app/api/[[...all]]/route.ts import { AppRouter } from '@/igniter.router' import { nextRouteHandlerAdapter } from '@igniter-js/core/adapters' // The adapter creates GET, POST, etc. handlers from your Igniter.js router. export const { GET, POST, PUT, DELETE } = nextRouteHandlerAdapter(AppRouter) ``` -------------------------------- ### Start bot adapters Source: https://github.com/felipebarcelospro/igniter-js/blob/main/apps/www/content/docs/bots/api-reference.mdx Call `bot.start()` to initialize all bot adapters, including webhooks and command synchronization. ```typescript await bot.start() ``` -------------------------------- ### Igniter.js API Definition and Client Usage Source: https://github.com/felipebarcelospro/igniter-js/blob/main/apps/www/content/docs/core/comparison.mdx Define a RESTful API with standard HTTP methods and actions using Igniter.js. This example demonstrates creating a user controller with GET and POST endpoints and shows how to use the generated client. It also highlights compatibility with standard HTTP clients like curl. ```typescript const userController = igniter.controller({ name: 'Users', description: 'Manage user accounts and profiles', path: '/users', actions: { getById: igniter.query({ name: 'Get User by ID', description: 'Retrieve a specific user by their ID', path: '/:id' as const, handler: async ({ request, response }) => { const user = await db.users.findUnique({ where: { id: request.params.id } }); return response.success({ user }); } }), create: igniter.mutation({ name: 'Create User', description: 'Create a new user account', path: '/', method: 'POST', body: z.object({ name: z.string(), email: z.string().email() }), handler: async ({ request, response }) => { const user = await db.users.create({ data: request.body }); return response.created({ user }); } }) } }); // Client usage const { data } = await client.users.getById.query({ params: { id: '123' } }); // ✅ Also works with curl, Postman, etc. // GET /api/v1/users/123 ``` -------------------------------- ### Install, Build, and Test Dependencies Source: https://github.com/felipebarcelospro/igniter-js/blob/main/AGENTS.md Standard npm commands for managing project dependencies, building packages, and running tests. ```bash # Install all dependencies npm install # Build all packages npm run build # Run tests npm run test ``` -------------------------------- ### Define an Audit Log Plugin Source: https://github.com/felipebarcelospro/igniter-js/wiki/03-Advanced-Features/04-Igniter-js-Plugins This TypeScript code defines an audit log plugin using `createIgniterPlugin`. It includes an internal action to log events, a public controller to view log history, a hook to log after each request, and extends the application context with a service to get the total log count. Logs are stored in memory for this example. ```typescript // src/plugins/audit-log.plugin.ts import { createIgniterPlugin, createIgniterPluginAction } from '@igniter-js/core'; import { z } from 'zod'; // For this example, we'll store logs in memory. // In a real application, this would be a database or a log file. const auditLogs: string[] = []; export const auditLogPlugin = createIgniterPlugin({ name: 'audit-log', /** * Internal actions are not exposed as API endpoints. They can only be * called from this plugin's controllers or hooks via the `self` object. */ actions: { logEvent: createIgniterPluginAction({ input: z.object({ path: z.string(), status: z.number() }), handler: async ({ input }) => { const logMessage = `[AUDIT] ${new Date().toISOString()}: Request to ${input.path} completed with status ${input.status}`; auditLogs.push(logMessage); console.log(logMessage); }, }), }, /** * Public API endpoints exposed by this plugin. * They will be available under the path `/plugins/audit-log/...` */ controllers: { history: { path: '/history', method: 'GET', handler: async ({ response }) => { // Return the last 10 logs. return response.success({ logs: auditLogs.slice(-10).reverse() }); }, }, }, /** * Lifecycle hooks allow the plugin to tap into the request lifecycle. */ hooks: { // This hook runs after a successful request has been processed. afterRequest: async (ctx, req, res, self) => { // The `self` parameter provides type-safe access to this plugin's own actions. await self.actions.logEvent({ path: req.path, status: res.status, }); }, }, /** * The `extendContext` function adds properties to the global application context. * The returned object will be available on `context` in all actions and procedures. */ extendContext: () => { return { auditService: { getLogCount: () => auditLogs.length, }, }; }, }); ``` -------------------------------- ### Install Dependencies and Sync Database Source: https://github.com/felipebarcelospro/igniter-js/wiki/06-Starter-Guides/01-Nextjs-Starter-Guide Install npm packages and push the Prisma schema to create database tables. This command configures your database based on the prisma/schema.prisma file. ```bash # Install all required npm packages npm install # Push the Prisma schema to the newly created database npx prisma db push ``` -------------------------------- ### Token Verification: JWT Example Source: https://github.com/felipebarcelospro/igniter-js/blob/main/apps/www/content/docs/mcp-server/oauth.mdx Example of verifying a JWT token. Ensure `process.env.JWT_SECRET` is set. This example includes checks for token expiration. ```typescript import jwt from 'jsonwebtoken'; withOAuth({ issuer: 'https://auth.example.com', verifyToken: async ({ bearerToken, context }) => { if (!bearerToken) { return undefined; } try { const decoded = jwt.verify(bearerToken, process.env.JWT_SECRET); // Additional validation if (decoded.exp < Date.now() / 1000) { return undefined; // Token expired } return { valid: true, user: { id: decoded.userId, email: decoded.email, roles: decoded.roles, }, scopes: decoded.scopes || [], }; } catch (error) { return undefined; // Invalid token } } }) ``` -------------------------------- ### Install Authentication Dependencies Source: https://github.com/felipebarcelospro/igniter-js/blob/main/apps/www/content/learn/04-authentication.mdx Install bcryptjs for password hashing and jsonwebtoken for JWT creation and verification. Also install their corresponding TypeScript types. ```bash npm install bcryptjs jsonwebtoken npm install -D @types/bcryptjs @types/jsonwebtoken ``` -------------------------------- ### Initialize Igniter.js Project with Deno (yarn) Source: https://github.com/felipebarcelospro/igniter-js/blob/main/apps/www/content/docs/core/(installation)/deno.mdx Use the Igniter.js CLI with yarn to quickly set up a new project for Deno. ```bash yarn dlx @igniter-js/cli@latest init ``` -------------------------------- ### Create Example Controller Source: https://github.com/felipebarcelospro/igniter-js/blob/main/apps/www/content/docs/core/(installation)/vite.mdx Define a controller to group related API endpoints. This example creates a simple 'hello' query action within the 'Example' controller. ```typescript import { igniter } from '@/igniter' export const exampleController = igniter.controller({ name: 'Example', path: '/example', actions: { hello: igniter.query({ path: '/hello', handler: async ({ response }) => { return response.success({ message: 'Hello from Igniter.js with Vite!', timestamp: new Date().toISOString() }) }, }), }, }) ``` -------------------------------- ### Install Lia for Claude Desktop Source: https://github.com/felipebarcelospro/igniter-js/blob/main/apps/www/content/docs/core/index.mdx Installs Lia for Claude Desktop, enabling it to scaffold features, debug issues, and analyze codebases. Restart Claude after installation. ```bash npx @igniter-js/cli@latest lia --claude ```