### Igniter.js Core Setup
Source: https://igniterjs.com/docs/core/quick-start
This section demonstrates the basic setup of the Igniter.js instance, including context configuration and API base settings.
```APIDOC
## Core Igniter.js Setup
### Description
Initializes the Igniter.js core instance, defining application context and base configuration for API endpoints.
### Method
N/A (Configuration)
### Endpoint
N/A (Configuration)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```typescript
import { Igniter } from '@igniter-js/core';
export interface AppContext {
db: {
users: Array<{ id: string; name: string; email: string }>;
};
}
export function createIgniterAppContext(): AppContext {
return {
db: {
users: []
}
};
}
export const igniter = Igniter
.context(createIgniterAppContext())
.config({
baseURL: 'http://localhost:3000',
basePATH: '/api/v1'
})
.create();
```
### Response
#### Success Response (200)
N/A (Configuration)
#### Response Example
N/A (Configuration)
```
--------------------------------
### Clone TanStack Start App Repository
Source: https://igniterjs.com/templates/starter-tanstack-start
Instructions to clone the TanStack Start App repository using Git. This is the initial step to get the project locally.
```bash
git clone https://github.com/felipebarcelospro/igniter-js.git
cd igniter-js/apps/starter-tanstack-start
```
--------------------------------
### Install and Start Redis on Linux (Ubuntu/Debian)
Source: https://igniterjs.com/docs/installation
APT commands to install and start a Redis server on Ubuntu/Debian-based Linux distributions.
```bash
sudo apt-get install redis-server
sudo systemctl start redis
```
--------------------------------
### Install and Start Redis on macOS
Source: https://igniterjs.com/docs/installation
Homebrew commands to install and start a Redis server on macOS.
```bash
brew install redis
brew services start redis
```
--------------------------------
### User Controller and Actions
Source: https://igniterjs.com/docs/core/quick-start
Defines a user controller and demonstrates how to implement Query (GET) and Mutation (POST) actions for managing user data.
```APIDOC
## User Management API Endpoints
### Description
This section details the controllers and actions for managing user accounts, including listing users and creating new ones with type-safe validation.
### Method
GET, POST
### Endpoint
/users
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **name** (string) - Required - The name of the user.
- **email** (string) - Required - The email address of the user.
### Request Example
```json
{
"name": "John Doe",
"email": "john.doe@example.com"
}
```
### Response
#### Success Response (200)
- **users** (array) - A list of user objects.
- **id** (string) - The unique identifier of the user.
- **name** (string) - The name of the user.
- **email** (string) - The email address of the user.
#### Success Response (201 Created)
- **user** (object) - The newly created user object.
- **id** (string) - The unique identifier of the user.
- **name** (string) - The name of the user.
- **email** (string) - The email address of the user.
#### Response Example (List Users)
```json
{
"users": [
{
"id": "a1b2c3d4-e5f6-7890-1234-567890abcdef",
"name": "Jane Doe",
"email": "jane.doe@example.com"
}
]
}
```
#### Response Example (Create User)
```json
{
"user": {
"id": "f0e9d8c7-b6a5-4321-fedc-ba9876543210",
"name": "John Doe",
"email": "john.doe@example.com"
}
}
```
```
--------------------------------
### Complete IgniterJS Bot Example in JavaScript
Source: https://igniterjs.com/docs/bots/command-basics
This is a full example of an IgniterJS bot with multiple commands ('start', 'info', 'echo'). It demonstrates bot creation, adapter configuration (Telegram), command registration, and the bot's startup process. It includes asynchronous operations for sending messages.
```javascript
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()
```
--------------------------------
### IgniterJS: API Client Setup
Source: https://igniterjs.com/docs/core/quick-start
Sets up a type-safe client for making API requests from the frontend. It uses `createIgniterClient` to infer types automatically from the router definition.
```typescript
import { createIgniterClient } from '@igniter-js/core/client';
import { AppRouter } from '@/igniter.router';
export const client = createIgniterClient({
baseURL: 'http://localhost:3000',
basePATH: '/api/v1',
router: AppRouter
});
```
--------------------------------
### Create a Telegram Bot Instance with a 'start' Command
Source: https://igniterjs.com/docs/bots
Example demonstrating how to create a new bot instance using the `Bot.create` method. It configures a Telegram adapter and defines a basic 'start' command that sends a welcome message to the user.
```typescript
import { Bot, telegram } from '@igniter-js/bot'
const bot = Bot.create({
id: 'demo-bot',
name: 'Demo Bot',
adapters: {
telegram: telegram({
token: process.env.TELEGRAM_TOKEN!,
handle: '@demo_bot',
webhook: {
url: process.env.TELEGRAM_WEBHOOK_URL!,
secret: process.env.TELEGRAM_SECRET
}
})
},
commands: {
start: Bot.command({
name: 'start',
aliases: ['hello'],
description: 'Greets the user',
help: 'Use /start to receive a welcome message.',
async handle(ctx) {
await ctx.bot.send({
provider: ctx.provider,
channel: ctx.channel.id,
content: {
type: 'text',
content: '👋 Welcome, friend!'
}
})
}
})
}
})
await bot.start()
```
--------------------------------
### Multi-Tenant Architecture: Complete Example
Source: https://igniterjs.com/docs/jobs/multi-tenancy
A comprehensive example demonstrating the setup of a multi-tenant job system. It includes creating an adapter with a global prefix, a factory for tenant job routers, merging routers, and scheduling tenant-specific jobs.
```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' },
});
```
--------------------------------
### Client Component Usage Example (React)
Source: https://igniterjs.com/templates/starter-tanstack-start
Example of how to use the auto-generated type-safe client and React hooks to fetch data in a client component. It demonstrates fetching the API health status.
```tsx
// src/routes/index.tsx
'use client';
import { api } from '@/igniter.client';
export function Component() {
const { data, isLoading } = api.example.health.useQuery();
if (isLoading) return (
Loading...
);
return (
Welcome to TanStack Start!
==========================
API Status: {data?.status}
);
}
```
--------------------------------
### Install Bun on Linux/macOS
Source: https://bun.sh/
This command downloads and executes the Bun installation script for Linux and macOS. It's a convenient way to get the latest version of Bun onto your system.
```shell
curl -fsSL https://bun.sh/install | bash
```
--------------------------------
### Configure ioredis Client Options
Source: https://igniterjs.com/docs/installation
Example configuration object for the ioredis client, showcasing basic connection, pool, and retry strategy options.
```javascript
const redis = new Redis({
// Basic connection
host: 'localhost',
port: 6379,
password: 'your-password',
db: 0,
// Connection pool
connectTimeout: 10000,
lazyConnect: false,
// Retry strategy
retryStrategy: (times) => {
if (times > 3) {
return null; // Stop retrying
}
return Math.min(times * 50, 2000);
},
maxRetriesPerRequest: 3,
// Keep alive
keepAlive: 30000,
// TLS/SSL (for production)
tls: {
// TLS options if using secure connection
},
});
```
--------------------------------
### IgniterJS: Client-Side API Call (React Hook)
Source: https://igniterjs.com/docs/core/quick-start
Provides an example of making client-side API calls using React hooks generated by the IgniterJS client. This includes automatic caching and state management for loading and error states.
```typescript
'use client';
import { client } from '@/lib/api-client';
export function UsersListClient() {
// Fully typed hook with loading states
const { data, isLoading, error } = client.users.list.useQuery();
if (isLoading) return Loading...
;
if (error) return Error: {error.message}
;
return (
{data.users.map(user => (
{user.name}
))}
);
}
```
--------------------------------
### GET /users/search
Source: https://igniterjs.com/docs/core/quick-start
Search users by name with an optional limit. This endpoint accepts query parameters for searching and pagination.
```APIDOC
## GET /users/search
### Description
Search users by name with optional limit. Supports filtering by name and limiting the number of results.
### Method
GET
### Endpoint
/search
#### Query Parameters
- **q** (string) - Required - The search query string to match against user names.
- **limit** (number) - Optional - The maximum number of users to return. Defaults to 10.
### Response
#### Success Response (200)
- **users** (array) - An array of user objects matching the search criteria.
- **query** (string) - The search query that was used.
### Response Example
```json
{
"users": [
{
"id": "some-user-id",
"name": "John Doe",
"email": "john.doe@example.com"
}
],
"query": "john"
}
```
```
--------------------------------
### Install Dependencies and Build (npm)
Source: https://code.visualstudio.com/
This command sequence first installs all project dependencies using npm and then runs the build process. This is a common step before running or deploying the application.
```bash
npm install && npm run build
```
--------------------------------
### Install Bun on Windows
Source: https://bun.sh/
This command uses PowerShell to download and execute the Bun installation script for Windows. It ensures a smooth installation process for Windows users.
```powershell
powershell -c "irm bun.sh/install.ps1 | iex"
```
--------------------------------
### Run Redis Locally with Docker
Source: https://igniterjs.com/docs/installation
Docker command to start a Redis server instance in detached mode, accessible on the default port.
```bash
docker run -d -p 6379:6379 redis:7-alpine
```
--------------------------------
### Share Redis Connection Between Store and Jobs Adapters (TypeScript)
Source: https://igniterjs.com/docs/installation
TypeScript example showing how to create a single Redis client instance and use it for both the Store adapter and potentially other adapters like BullMQ for jobs.
```typescript
// src/services/store.ts
import { createRedisStoreAdapter } from '@igniter-js/adapter-redis';
import { Redis } from 'ioredis';
// Create a single Redis client
export const redis = new Redis(process.env.REDIS_URL);
// Create store adapter
export const store = createRedisStoreAdapter(redis);
```
--------------------------------
### Install Deno Runtime
Source: https://deno.land/
This code snippet provides the command to install Deno on macOS and Linux systems. It uses curl to download and execute the official installation script.
```bash
curl -fsSL https://deno.land/install.sh | sh
```
--------------------------------
### Generate Documentation Command
Source: https://igniterjs.com/docs/core/quick-start
Command to update API documentation and the playground. This command should be run after modifying API controllers or actions.
```bash
npx @igniter-js/cli@latest generate docs
```
```bash
pnpm dlx @igniter-js/cli@latest generate docs
```
```bash
yarn dlx @igniter-js/cli@latest generate docs
```
```bash
bunx @igniter-js/cli@latest generate docs
```
--------------------------------
### Install Packages with Bun
Source: https://bun.sh/
Illustrates the command to install npm packages using Bun as a package manager. Bun's `install` command is noted for its speed, often outperforming traditional package managers like npm, pnpm, and yarn.
```bash
$ bun install
```
--------------------------------
### Start HTTP Server with Bun and PostgreSQL Integration
Source: https://bun.sh/
Starts an HTTP server using Bun's `serve` API and demonstrates querying a PostgreSQL database within the route handlers. It includes a route for the root path and an API endpoint to fetch users.
```typescript
import { sql, serve } from "bun";
const server = serve({
port: 3000,
routes: {
"/": () => new Response("Welcome to Bun!"),
"/api/users": async (req) => {
const users = await sql`SELECT * FROM users LIMIT 10`;
return Response.json({ users });
},
},
});
console.log(`Listening on localhost:${server.port}`);
```
--------------------------------
### Redis Client and Store Setup
Source: https://igniterjs.com/docs/store/installation
Demonstrates how to create a shared Redis client and a store adapter using `@igniter-js/adapter-redis`.
```APIDOC
## Redis Client and Store Setup
### Description
This section shows how to initialize a single Redis client and configure the store adapter. Sharing a single Redis client is recommended for efficiency.
### Method
Initialization
### Endpoint
N/A
### Parameters
None
### Request Body
None
### Request Example
```javascript
import { createRedisStoreAdapter } from '@igniter-js/adapter-redis';
import { Redis } from 'ioredis';
// Create a single Redis client
export const redis = new Redis(process.env.REDIS_URL);
// Create store adapter
export const store = createRedisStoreAdapter(redis);
```
### Response
None
```
--------------------------------
### Example: Application Configuration Resource
Source: https://igniterjs.com/docs/mcp-server/prompts-resources
An example of adding a resource for application settings. It dynamically reads environment variables to configure version, environment, features, and limits, serving them as JSON.
```javascript
.addResource({
uri: 'config://app/settings',
name: 'Application Settings',
description: 'Current application configuration',
mimeType: 'application/json',
handler: async (context) => {
const settings = {
version: process.env.APP_VERSION,
environment: process.env.NODE_ENV,
features: {
enableFeatureX: process.env.FEATURE_X === 'true',
enableFeatureY: process.env.FEATURE_Y === 'true',
},
limits: {
maxUsers: parseInt(process.env.MAX_USERS || '1000'),
maxRequestsPerMinute: parseInt(process.env.MAX_RPM || '100'),
}
};
return {
contents: [
{
uri: 'config://app/settings',
mimeType: 'application/json',
text: JSON.stringify(settings, null, 2)
}
]
};
}
})
```
--------------------------------
### POST /users
Source: https://igniterjs.com/docs/core/quick-start
Create a new user. This endpoint accepts user details in the request body.
```APIDOC
## POST /users
### Description
Create a new user with the provided name and email.
### Method
POST
### Endpoint
/
#### Request Body
- **name** (string) - Required - The name of the user to create.
- **email** (string) - Required - The email address of the user.
### Request Example
```json
{
"name": "Jane Doe",
"email": "jane.doe@example.com"
}
```
### Response
#### Success Response (200 or 201)
- **user** (object) - The newly created user object, including its ID.
### Response Example
```json
{
"user": {
"id": "new-user-id",
"name": "Jane Doe",
"email": "jane.doe@example.com"
}
}
```
```
--------------------------------
### Install Redis Adapter with npm, pnpm, yarn, bun
Source: https://igniterjs.com/docs/installation
Commands to install the @igniter-js/adapter-redis and its peer dependency ioredis using different package managers.
```bash
npm install @igniter-js/adapter-redis ioredis
```
```bash
pnpm add @igniter-js/adapter-redis ioredis
```
```bash
yarn add @igniter-js/adapter-redis ioredis
```
```bash
bun add @igniter-js/adapter-redis ioredis
```
--------------------------------
### Run Development Server with Bun
Source: https://igniterjs.com/templates/starter-bun-react-app
Command to start the development server for the Bun and React full-stack application. This requires Bun (v1.0 or higher) to be installed and a running Redis instance.
```shell
bun run dev
```
--------------------------------
### Install Project Dependencies with Various Package Managers
Source: https://igniterjs.com/templates/starter-express-rest-api
Installs project dependencies using different Node.js package managers like npm, pnpm, yarn, and bun. Ensure you have the respective package manager installed.
```bash
npm install
```
```bash
pnpm install
```
```bash
yarn install
```
```bash
bun install
```
--------------------------------
### Example Prompt: Multi-Step User Activity Analysis - Igniter.js MCP Server
Source: https://igniterjs.com/docs/mcp-server/prompts-resources
This example demonstrates a prompt for performing a multi-step user activity analysis within an Igniter.js MCP Server. It accepts a user ID and a date range, then constructs a detailed user message guiding the AI through steps like fetching data, calculating metrics, identifying patterns, and generating a summary report.
```typescript
.addPrompt({
name: 'analyzeUserActivity',
description: 'Perform comprehensive user activity analysis',
args: {
userId: z.string().uuid(),
dateRange: z.object({
start: z.coerce.date(),
end: z.coerce.date(),
}),
},
handler: async (args, context) => {
return {
messages: [{
role: 'user',
content: {
type: 'text',
text: `Analyze user ${args.userId}'s activity from ` +
`${args.dateRange.start.toISOString()} to ` +
`${args.dateRange.end.toISOString()}\n\n` +
`Steps:\n` +
`1. Get user details with users.getById\n` +
`2. Get activity logs with logs.getByUser for the date range\n` +
`3. Get orders with orders.getByUser for the date range\n` +
`4. Calculate metrics: total orders, total spent, most active day\n` +
`5. Identify patterns or anomalies\n` +
`6. Provide a summary report`
}
}]
};
},
})
```
--------------------------------
### Install Dependencies with Multiple Package Managers
Source: https://igniterjs.com/templates/starter-bun-react-app
Provides commands to install project dependencies using various popular package managers like Bun, npm, pnpm, and yarn. Ensure you have the respective package manager installed before execution.
```shell
bun install
```
```shell
npm install
```
```shell
pnpm install
```
```shell
yarn install
```
--------------------------------
### Install BullMQ and Redis Dependencies (npm)
Source: https://igniterjs.com/docs/jobs/getting-started
Installs the necessary BullMQ adapter, Redis adapter, BullMQ library, and ioredis client for Node.js using npm. Ensure Node.js 18.0+ is installed.
```bash
npm install @igniter-js/adapter-bullmq @igniter-js/adapter-redis bullmq ioredis
```
--------------------------------
### Start Frontend Development Server with Bun
Source: https://bun.sh/
Starts a development server for a frontend application using Bun. This command enables features like instant hot-reloading and supports TypeScript, JSX, React, and CSS imports out of the box with zero configuration.
```bash
bun run ./index.html
```
--------------------------------
### Install Redis Adapter with bun
Source: https://igniterjs.com/docs/store
Installs the Redis adapter and its peer dependency, ioredis, using bun. This command is an alternative for package management in JavaScript projects.
```bash
bun add @igniter-js/adapter-redis ioredis
```
--------------------------------
### Complete IgniterJS MCP Server Example with Multiple Features
Source: https://igniterjs.com/docs/mcp-server/builder-pattern
A comprehensive example demonstrating the integration of multiple IgniterJS MCP Server features, including server information, instructions, tool definitions, OAuth, and event handling.
```javascript
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()
}
})
// ... other configurations like withOAuth(), withEvents(), etc.
.build();
```
--------------------------------
### Install BullMQ and Redis Dependencies (bun)
Source: https://igniterjs.com/docs/jobs/getting-started
Installs the necessary BullMQ adapter, Redis adapter, BullMQ library, and ioredis client for Node.js using bun. Ensure Node.js 18.0+ is installed.
```bash
bun add @igniter-js/adapter-bullmq @igniter-js/adapter-redis bullmq ioredis
```
--------------------------------
### Install Dependencies with Bun Package Manager
Source: https://bun.sh/
Installs project dependencies using Bun, which is compatible with npm and offers significantly faster installation times compared to other package managers like pnpm, npm, and Yarn. It can also install dependencies from cache.
```bash
bun install
```
--------------------------------
### Example Controller with Cache and Jobs (TypeScript)
Source: https://igniterjs.com/templates/starter-bun-react-app
Demonstrates an example controller in Igniter.js, showcasing interactions with caching (Redis) and scheduling background jobs (BullMQ). This illustrates common backend operations.
```typescript
import { Controller, Query, Mutation } from "@igniter-js/core";
import { AppIgniter } from "../igniter";
import { z } from "zod";
export class ExampleController extends Controller {
@Query({
input: z.string(),
output: z.string().nullable(),
})
async getMessage(message: string) {
return await this.igniter.store.get(message);
}
@Mutation({
input: z.string(),
output: z.boolean(),
})
async setMessage(message: string) {
await this.igniter.store.set(message, message, { ex: 60 }); // Expires in 60 seconds
return true;
}
@Mutation({
input: z.string(),
output: z.string(),
})
async scheduleJob(data: string) {
const job = await this.igniter.jobs.add("my_job", { data });
return job.id;
}
}
```
--------------------------------
### Install Redis Adapter with npm
Source: https://igniterjs.com/docs/store
Installs the Redis adapter and its peer dependency, ioredis, using npm. This is the first step to integrating Redis caching and Pub/Sub into your Igniter.js application.
```bash
npm install @igniter-js/adapter-redis ioredis
```
--------------------------------
### Install BullMQ and Redis Dependencies (pnpm)
Source: https://igniterjs.com/docs/jobs/getting-started
Installs the necessary BullMQ adapter, Redis adapter, BullMQ library, and ioredis client for Node.js using pnpm. Ensure Node.js 18.0+ is installed.
```bash
pnpm add @igniter-js/adapter-bullmq @igniter-js/adapter-redis bullmq ioredis
```
--------------------------------
### Install Redis Adapter with pnpm
Source: https://igniterjs.com/docs/store
Installs the Redis adapter and its peer dependency, ioredis, using pnpm. This command ensures all necessary packages are correctly managed for your project.
```bash
pnpm add @igniter-js/adapter-redis ioredis
```
--------------------------------
### Example: Database Schema Resource
Source: https://igniterjs.com/docs/mcp-server/prompts-resources
Shows how to add a database schema resource. This example defines the schema for a 'users' table, including columns, types, and indexes, served as JSON.
```javascript
.addResource({
uri: 'db://schema/users',
name: 'Users Table Schema',
description: 'Database schema for users table',
mimeType: 'application/json',
handler: async (context) => {
const schema = {
table: 'users',
columns: [
{ name: 'id', type: 'uuid', primaryKey: true },
{ name: 'email', type: 'varchar(255)', unique: true, nullable: false },
{ name: 'name', type: 'varchar(255)', nullable: false },
{ name: 'created_at', type: 'timestamp', default: 'now()' },
{ name: 'updated_at', type: 'timestamp', default: 'now()' },
],
indexes: [
{ columns: ['email'], unique: true },
{ columns: ['created_at'] },
]
};
return {
contents: [
{
uri: 'db://schema/users',
mimeType: 'application/json',
text: JSON.stringify(schema, null, 2)
}
]
};
}
})
```
--------------------------------
### Create Igniter Instance and Context
Source: https://igniterjs.com/docs/core/quick-start
This snippet shows how to create the core Igniter instance, defining the application's context and configuration settings like baseURL and basePath.
```typescript
import { Igniter } from '@igniter-js/core';
// Define your application context type
export interface AppContext {
db: {
users: Array<{ id: string; name: string; email: string }>;
};
}
// Create context factory function
export function createIgniterAppContext(): AppContext {
return {
db: {
users: [] // In a real app, this would be your database connection
}
};
}
// Create and configure your Igniter instance
export const igniter = Igniter
.context(createIgniterAppContext())
.config({
baseURL: 'http://localhost:3000',
basePATH: '/api/v1'
})
.create();
```
--------------------------------
### Clone Bun REST API Starter Project
Source: https://igniterjs.com/templates/starter-bun-rest-api
This command clones the starter project for the Bun REST API from GitHub. It assumes you have Git installed.
```bash
git clone https://github.com/felipebarcelospro/igniter-js.git
cd igniter-js/apps/starter-bun-rest-api
```
--------------------------------
### Define Igniter.js Router for MCP Server
Source: https://igniterjs.com/docs/mcp-server/getting-started
This snippet shows how to define an Igniter.js router with controllers and actions, which will be exposed as an MCP server. It includes examples for listing users, getting a user by ID, and creating a user using Zod for validation. Ensure you have Igniter.js and Zod installed.
```typescript
import { igniter } from '@/igniter';
import { z } from 'zod';
export const usersController = igniter.controller({
path: '/users',
actions: {
list: igniter.query({
path: '/',
handler: async ({ context, response }) => {
const users = await context.db.users.findMany();
return response.success({ users });
},
}),
getById: igniter.query({
path: '/:id',
handler: async ({ request, response }) => {
const user = await context.db.users.findUnique({
where: { id: request.params.id },
});
return response.success({ user });
},
}),
create: igniter.mutation({
path: '/',
method: 'POST',
body: z.object({
email: z.string().email(),
name: z.string(),
}),
handler: async ({ request, response }) => {
const user = await context.db.users.create({
data: request.body,
});
return response.created({ user });
},
}),
},
});
export const AppRouter = igniter.merge({
users: usersController,
});
```
--------------------------------
### TypeScript User Balance Example
Source: https://deno.land/
An example demonstrating Deno's native TypeScript support. It defines a User type and a function to display the user's balance, showcasing type safety and basic console output.
```typescript
type User = {
name: string;
balance: number;
};
function getBalance(user: User): string {
return `Balance: ${user.balance.toFixed(2)}`;
}
console.log(getBalance({ name: "Alice", balance: 42 }));
```
--------------------------------
### Deno Execution Example
Source: https://deno.land/
This snippet shows how to execute a TypeScript file named 'account.ts' using the Deno runtime. It uses the 'deno run' command.
```bash
$ deno run account.ts
```
--------------------------------
### Key-Value Operations: Get and Set with Examples
Source: https://igniterjs.com/docs/store/api-reference
Demonstrates how to retrieve ('get') and store ('set') data using the Store adapter. The 'get' method automatically deserializes JSON, while 'set' automatically serializes JSON-serializable values. Supports optional TTL for expiration.
```javascript
const user = await igniter.store.get('user:123');
if (user) {
console.log(user.name);
}
```
```javascript
// Store without TTL
await igniter.store.set('user:123', { name: 'John', email: 'john@example.com' });
// Store with TTL (expires in 1 hour)
await igniter.store.set('user:123', userData, { ttl: 3600 });
```
```javascript
const data = {
nested: { value: 123 },
array: [1, 2, 3],
date: new Date(), // Will be serialized as ISO string
};
await igniter.store.set('complex:data', data);
```
--------------------------------
### MCP Server Authentication Header and Request Examples
Source: https://igniterjs.com/docs/mcp-server/oauth
Demonstrates the required 'Authorization: Bearer' header for protected MCP requests and shows examples of unprotected and protected GET requests to the /api/mcp/sse endpoint.
```http
GET /api/mcp/sse // Returns 401 Unauthorized
```
```http
GET /api/mcp/sse \
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... // Returns 200 OK with MCP response
```
--------------------------------
### GET /users/:id
Source: https://igniterjs.com/docs/core/quick-start
Retrieve a specific user by their ID. This endpoint uses a path parameter to identify the user.
```APIDOC
## GET /users/:id
### Description
Retrieve a specific user by their ID.
### Method
GET
### Endpoint
/:id
#### Path Parameters
- **id** (string) - Required - The unique identifier of the user to retrieve.
### Response
#### Success Response (200)
- **user** (object) - The retrieved user object.
#### Error Response (404)
- **message** (string) - Indicates that the user was not found.
### Response Example
```json
{
"user": {
"id": "some-user-id",
"name": "John Doe",
"email": "john.doe@example.com"
}
}
```
```
--------------------------------
### Implement List Users Query Action
Source: https://igniterjs.com/docs/core/quick-start
This snippet implements a 'list' query action within the user controller to retrieve all users. It demonstrates accessing the application context and returning a success response.
```typescript
export const userController = igniter.controller({
path: '/users',
actions: {
list: igniter.query({
name: 'List Users',
description: 'Retrieve a list of all users',
path: '/',
handler: async ({ context, response }) => {
// Access your context (typed automatically!)
const users = context.db.users;
// Return a success response
return response.success({ users });
}
}),
}
});
```
--------------------------------
### Create WebSocket Server with Bun
Source: https://bun.sh/
Illustrates how to set up a WebSocket server using `Bun.serve()`. Bun's WebSocket server includes features like Pub/Sub and backpressure handling, designed for high-performance real-time applications.
```javascript
Bun.serve({
fetch(req) {
if (req.headers.get("upgrade") === "websocket") {
return new WebSocket(req)
}
return new Response("Hello!")
},
websocket: {
message(ws, message) { /* ... */ },
open(ws) { /* ... */ },
close(ws, code, reason) { /* ... */ },
},
})
```
--------------------------------
### Igniter.js MCP Server Complete OAuth Example with JWT Verification
Source: https://igniterjs.com/docs/mcp-server/oauth
A comprehensive example of setting up an Igniter.js MCP Server with OAuth, including router configuration, JWT verification logic for tokens, and defining handlers for GET, POST, and OPTIONS requests. It uses the '@igniter-js/adapter-mcp-server' and 'jsonwebtoken' libraries.
```javascript
import { IgniterMcpServer } from '@igniter-js/adapter-mcp-server';
import jwt from 'jsonwebtoken';
const { handler, auth } = IgniterMcpServer
.create()
.router(AppRouter)
.withOAuth({
issuer: 'https://auth.example.com',
resourceMetadataPath: '/.well-known/oauth-protected-resource',
scopes: ['mcp:read', 'mcp:write'],
verifyToken: async ({ bearerToken, context }) => {
if (!bearerToken) {
return undefined;
}
try {
const decoded = jwt.verify(bearerToken, process.env.JWT_SECRET) as any;
// You can inject the user into the router context
// This requires modifying createMcpContext to include the user
return {
valid: true,
user: {
id: decoded.userId,
email: decoded.email,
},
scopes: decoded.scopes || ['mcp:read'],
};
} catch (error) {
return undefined;
}
}
})
.build();
export const GET = handler;
export const POST = handler;
export const OPTIONS = auth.cors;
```
--------------------------------
### Create Redis Client and Store Adapter (JavaScript)
Source: https://igniterjs.com/docs/store/installation
This snippet demonstrates how to create a single Redis client instance and then initialize a store adapter using that client. Sharing a single Redis client is recommended for efficiency, as the adapter manages internal connections for operations like Pub/Sub.
```javascript
import { createRedisStoreAdapter } from '@igniter-js/adapter-redis';
import { Redis } from 'ioredis';
// Create a single Redis client
export const redis = new Redis(process.env.REDIS_URL);
// Create store adapter
export const store = createRedisStoreAdapter(redis);
```
--------------------------------
### Clone and Navigate Deno REST API Project
Source: https://igniterjs.com/templates/starter-deno-rest-api
This code snippet demonstrates how to clone the Igniter.js repository and navigate into the Deno REST API starter project directory using git.
```bash
git clone https://github.com/felipebarcelospro/igniter-js.git
cd igniter-js/apps/starter-deno-rest-api
```
--------------------------------
### IgniterJS: Get User by ID Endpoint
Source: https://igniterjs.com/docs/core/quick-start
Defines an API endpoint to retrieve a single user by their ID. It uses path parameters for the user ID and handles cases where the user is not found.
```typescript
getById: igniter.query({
name: 'Get User by ID',
description: 'Retrieve a specific user by their ID',
path: '/:id' as const,
// ← Path parameter with 'as const' for proper type inference
handler: async ({ request, context, response }) => {
// request.params.id is automatically typed as string
const user = context.db.users.find(u => u.id === request.params.id);
if (!user) {
return response.notFound({ message: 'User not found' });
}
return response.success({ user });
}
}),
```
--------------------------------
### Comprehensive Error Handling Example (TypeScript)
Source: https://igniterjs.com/docs/bots/error-handling
This example demonstrates a complete error handling setup for an Igniter.js bot. It includes global error event handling, command-specific error recovery within the 'risky' command, and a middleware for global error interception. Dependencies include `@igniter-js/bot`. It handles 'COMMAND_NOT_FOUND' errors specifically and provides a general error message for other exceptions.
```typescript
import { Bot, telegram, type Middleware } from '@igniter-js/bot'
// Error recovery middleware
const errorRecoveryMiddleware: Middleware = async (ctx, next) => {
try {
await next()
} catch (error) {
console.error('Middleware caught error:', error)
// Re-throw to let error handlers catch it
throw error
}
}
const bot = Bot.create({
id: 'error-bot',
name: 'Error Bot',
adapters: {
telegram: telegram({
token: process.env.TELEGRAM_TOKEN!,
handle: '@error_bot',
webhook: {
url: process.env.TELEGRAM_WEBHOOK_URL!
}
})
},
middlewares: [errorRecoveryMiddleware],
commands: {
risky: {
name: 'risky',
async handle(ctx, params) {
try {
// Risky operation that might fail
const result = await riskyOperation(params[0])
await ctx.bot.send({
provider: ctx.provider,
channel: ctx.channel.id,
content: {
type: 'text',
content: `✅ Success: ${result}`
}
})
} catch (error) {
// Command-specific error handling
await ctx.bot.send({
provider: ctx.provider,
channel: ctx.channel.id,
content: {
type: 'text',
content: `❌ Command failed: ${error.message}`
}
})
}
}
}
}
})
// Global error handler
bot.on('error', async (ctx) => {
// @ts-expect-error - error injected internally
const err = ctx.error
// Log error with context
console.error('Bot error:', {
code: err.code,
message: err.message,
userId: ctx.message.author.id,
channel: ctx.channel.id
})
// Send user-friendly error message
switch (err.code) {
case 'COMMAND_NOT_FOUND':
await ctx.bot.send({
provider: ctx.provider,
channel: ctx.channel.id,
content: {
type: 'text',
content: '❌ Command not found. Use /help to see available commands.'
}
})
break
default:
await ctx.bot.send({
provider: ctx.provider,
channel: ctx.channel.id,
content: {
type: 'text',
content: '❌ Something went wrong. Please try again later.'
}
})
}
})
await bot.start()
```
--------------------------------
### Example: API Documentation Resource
Source: https://igniterjs.com/docs/mcp-server/prompts-resources
Demonstrates adding an API documentation resource. It serves Markdown content that outlines available API endpoints for users and products.
```javascript
.addResource({
uri: 'docs://api/reference',
name: 'API Reference',
description: 'API endpoint documentation',
mimeType: 'text/markdown',
handler: async (context) => {
const docs = `# API Reference
## Users Endpoints
### GET /users List all users
### GET /users/:id Get user by ID
### POST /users Create a new user
## Products Endpoints
### GET /products List all products
### GET /products/:id Get product by ID
`;
return {
contents: [
{
uri: 'docs://api/reference',
mimeType: 'text/markdown',
text: docs
}
]
};
}
})
```
--------------------------------
### Define User Controller with Zod Schemas
Source: https://igniterjs.com/docs/core/quick-start
This code defines a user controller for managing user accounts, including validation schemas for user data using Zod. It sets up the controller's name, description, and base path.
```typescript
import { igniter } from '@/igniter';
import { z } from 'zod';
// Define validation schemas
const UserSchema = z.object({
id: z.string(),
name: z.string().min(2),
email: z.string().email()
});
const CreateUserSchema = z.object({
name: z.string().min(2),
email: z.string().email()
});
// Create the controller
export const userController = igniter.controller({
name: 'Users',
description: 'Manage user accounts and profiles',
path: '/users',
actions: {
// We'll add actions in the next step
}
});
```
--------------------------------
### Initialize React App with Bun
Source: https://bun.sh/
Initializes a new React project using Bun's built-in tooling. This command sets up a basic React application structure, ready for development with Bun's fast development server and bundler.
```bash
bun init --react
```
--------------------------------
### OAuth Metadata Endpoint Exposure (Express)
Source: https://igniterjs.com/docs/mcp-server/oauth
Shows how to expose the OAuth protected resource metadata endpoint in an Express.js application. This setup involves defining a GET route for the metadata endpoint using the `auth.resource` handler from the Igniter.js adapter.
```javascript
// Express example
app.get('/.well-known/oauth-protected-resource', auth.resource);
app.options('/.well-known/oauth-protected-resource', auth.cors);
```
--------------------------------
### List Background Jobs in Deno REST API
Source: https://igniterjs.com/templates/starter-deno-rest-api
This cURL command retrieves a list of all scheduled background jobs currently managed by the Deno REST API. It sends a GET request to the `/jobs` endpoint within the example controller.
```bash
curl http://localhost:8000/api/v1/example/jobs
```
--------------------------------
### Initialize Bot Adapters - JavaScript
Source: https://igniterjs.com/docs/bots/api-reference
Initializes all configured adapters, including webhooks and command synchronization, using the bot.start() instance method. This method returns a Promise that resolves once initialization is complete.
```javascript
await bot.start()
```
--------------------------------
### Create HTTP Server with Bun
Source: https://bun.sh/
Example of creating a basic HTTP server using `Bun.serve()`. This built-in functionality provides a fast HTTP server and router, simplifying backend development.
```javascript
Bun.serve({
fetch(req) {
return new Response("Welcome to Bun!")
}
})
```
--------------------------------
### Next.js API Route Handler with Igniter.js Adapter
Source: https://igniterjs.com/templates/starter-nextjs
This snippet demonstrates how to integrate the Igniter.js API router with the Next.js App Router using the `nextRouteHandlerAdapter`. It exposes HTTP methods (GET, POST, PUT, DELETE) for the backend API defined in `AppRouter`. Ensure `@igniter-js/core/adapters` is installed.
```typescript
// src/app/api/[[...all]]/route.ts
import { AppRouter } from '@/igniter.router'
import { nextRouteHandlerAdapter } from '@igniter-js/core/adapters'
export const { GET, POST, PUT, DELETE } = nextRouteHandlerAdapter(AppRouter)
```
--------------------------------
### Updating Instructions with withInstructions Function
Source: https://igniterjs.com/docs/mcp-server/best-practices
This code example shows how to update the instructions for an API using the `withInstructions` function. It provides a concise summary of the available tools and their functionalities, guiding users on how to interact with the server effectively. Keeping instructions updated is crucial as the API evolves.
```javascript
// ✅ Good - Updated instructions
withInstructions(
"This server provides tools for managing users, products, and orders. " +
"Use users.list to get all users, users.create to add new users, " +
"products.search to find products, and orders.process to process orders."
)
```