@smartsamurai/krapi-sdk
v0.6.1
Published
KRAPI TypeScript SDK - Easy-to-use client SDK for connecting to self-hosted KRAPI servers (like Appwrite SDK)
Downloads
4,282
Maintainers
Readme
@smartsamurai/krapi-sdk
TypeScript SDK for KRAPI - self-hosted backend-as-a-service platform.
Installation
npm install @smartsamurai/krapi-sdkRequirements: Node.js 18+, TypeScript 5.0+ (recommended)
Quick Start
import { krapi } from '@smartsamurai/krapi-sdk';
// Connect to KRAPI server (Client Mode)
await krapi.connect({
endpoint: 'http://localhost:3470/krapi/k1',
apiKey: 'your-api-key'
});
// Use SDK methods - same API works everywhere!
const projects = await krapi.projects.getAll();
const project = await krapi.projects.create({ name: 'My Project' });
const collection = await krapi.collections.create(project.id, {
name: 'tasks',
fields: [
{ name: 'title', type: 'string', required: true },
{ name: 'completed', type: 'boolean', default: false }
]
});Table of Contents
- Installation
- Quick Start
- Architecture Overview
- Core Concepts
- Authentication Service
- Services Reference
- Error Handling
- Advanced Topics
- Examples
- Configuration
- Support
Architecture Overview
The KRAPI SDK uses a "plug and socket" architecture that provides perfect API parity between client and server environments. The same code works identically in both modes, automatically switching between HTTP requests (client) and direct database access (server).
graph TB
subgraph ClientMode["Client Mode (HTTP)"]
Frontend[Frontend App] --> SDK1[KRAPI SDK]
NextJS[Next.js Route] --> SDK2[KRAPI SDK]
External[External Service] --> SDK3[KRAPI SDK]
SDK1 --> HTTP[HTTP Client]
SDK2 --> HTTP
SDK3 --> HTTP
HTTP --> Server[KRAPI Server]
Server --> DB[(Database)]
end
subgraph ServerMode["Server Mode (Database)"]
Express[Express Route] --> SDK4[KRAPI SDK]
Backend[Backend Service] --> SDK5[KRAPI SDK]
SDK4 --> DirectDB[Direct DB Access]
SDK5 --> DirectDB
DirectDB --> DB
end
style ClientMode fill:#e1f5ff
style ServerMode fill:#fff4e1
style SDK1 fill:#4CAF50
style SDK2 fill:#4CAF50
style SDK3 fill:#4CAF50
style SDK4 fill:#4CAF50
style SDK5 fill:#4CAF50Core Concepts
Modes Explained
The SDK operates in two distinct modes, automatically determined by your connection configuration:
Client Mode (HTTP)
When to use: Frontend applications, Next.js API routes, external services, microservices
How it works: Makes HTTP requests to your KRAPI server via REST API
Configuration:
await krapi.connect({
endpoint: 'http://localhost:3470/krapi/k1', // Required: Server URL
apiKey: 'your-api-key', // Optional: For API key auth
sessionToken: 'token', // Optional: For session auth
timeout: 30000, // Optional: Request timeout (ms)
retry: { // Optional: Retry configuration
attempts: 3,
delay: 1000
},
initializeClients: false // Optional: Lazy client init
});Benefits:
- Works from any environment (browser, Node.js, edge functions)
- No direct database access required
- Secure - credentials never exposed to client
- Works across network boundaries
Server Mode (Database)
When to use: Backend services, Express routes, internal services, serverless functions with DB access
How it works: Directly queries the database for maximum performance
Configuration:
await krapi.connect({
database: databaseConnection, // Required: Database connection
logger: console // Optional: Custom logger
});Benefits:
- Maximum performance - no HTTP overhead
- Lower latency - direct database access
- Reduced network traffic
- Full transaction support
Important: Both modes provide identical APIs. The same code works in both environments without modification!
Connection Management
The SDK supports flexible connection management:
Reconnection:
// Connect to first endpoint
await krapi.connect({ endpoint: 'http://server1:3470/krapi/k1', apiKey: 'key1' });
// Reconnect to different endpoint (all HTTP clients are recreated)
await krapi.connect({ endpoint: 'http://server2:3470/krapi/k1', apiKey: 'key2' });Connection Status:
// Check if connected
if (krapi.isConnected()) {
// SDK is ready to use
}
// Get current mode
const mode = krapi.getMode(); // 'client' | 'server' | null
// Get current configuration
const config = krapi.getConfig();Cleanup:
// Close connection and cleanup resources
await krapi.close();Multiple SDK Instances
For applications that need to connect to multiple endpoints simultaneously (like frontend applications with client and proxy routes), use createSDKInstance() to create separate isolated instances:
import { createSDKInstance } from '@smartsamurai/krapi-sdk';
// Create separate instances for different endpoints
const clientSDK = createSDKInstance();
await clientSDK.connect({
endpoint: 'http://127.0.0.1:3498/krapi/k1',
apiKey: 'key'
});
const proxySDK = createSDKInstance();
await proxySDK.connect({
endpoint: 'http://127.0.0.1:3470/krapi/k1',
apiKey: 'key'
});
// Both can be used simultaneously without conflicts
await clientSDK.auth.login(username, password);
await proxySDK.projects.getAll();Each instance maintains its own HTTP clients, authentication state, and connection configuration, preventing conflicts when you need to connect to different endpoints simultaneously.
Authentication Service
The Authentication service (krapi.auth) provides comprehensive user authentication, session management, and API key operations. All methods work identically in both client and server modes.
Overview
The authentication service supports:
- API Key Authentication - For service-to-service communication
- Session-based Authentication - For user login sessions
- Admin Authentication - For administrative operations
- User Registration - For creating new user accounts
- Session Management - Token validation, refresh, and logout
Authentication Methods
createSession(apiKey: string)
Create a session from an API key. Returns a session token that can be used for subsequent requests.
Parameters:
apiKey(required) - API key string
Returns:
{
session_token: string;
expires_at: string;
user_type: 'admin' | 'project';
scopes: string[];
}Example (Client Mode):
await krapi.connect({ endpoint: 'http://localhost:3470/krapi/k1' });
const session = await krapi.auth.createSession('your-api-key');
console.log('Session token:', session.session_token);
console.log('Expires at:', session.expires_at);Example (Server Mode):
await krapi.connect({ database: dbConnection });
// Same API works identically
const session = await krapi.auth.createSession('your-api-key');login(username: string, password: string, remember_me?: boolean)
Authenticate a user with username and password credentials.
Parameters:
username(required) - Usernamepassword(required) - Passwordremember_me(optional) - Whether to create a long-lived session
Returns:
{
session_token: string;
expires_at: string;
user: AdminUser | ProjectUser;
scopes: string[];
}Example:
// Login
const result = await krapi.auth.login('admin', 'password123', true);
// Session token is automatically used for subsequent requests
// Or set it explicitly:
await krapi.auth.setSessionToken(result.session_token);
// Get current user
const user = await krapi.auth.getCurrentUser();setSessionToken(token: string)
Set the session token for subsequent requests. In client mode, this configures all HTTP clients to include the token in headers.
Parameters:
token(required) - Session token string
Example:
// Set session token after login
await krapi.auth.setSessionToken('session-token-here');
// All subsequent requests will use this token
const projects = await krapi.projects.getAll();setApiKey(apiKey: string)
Set the API key for subsequent requests. In client mode, this configures all HTTP clients to include the API key in headers.
Parameters:
apiKey(required) - API key string
Example:
// Set API key
krapi.auth.setApiKey('your-api-key');
// All subsequent requests will use this API key
const projects = await krapi.projects.getAll();logout()
Logout the current session, invalidating the session token.
Returns:
{ success: boolean }Example:
const result = await krapi.auth.logout();
if (result.success) {
console.log('Logged out successfully');
}getCurrentUser()
Get the currently authenticated user. In client mode, retrieves user from session. In server mode, requires session context.
Returns:
{
success: boolean;
data?: AdminUser | ProjectUser;
error?: string;
}Example:
const result = await krapi.auth.getCurrentUser();
if (result.success && result.data) {
console.log('Current user:', result.data.username);
console.log('User role:', result.data.role);
} else {
console.error('Not authenticated:', result.error);
}refreshSession()
Refresh the current session, extending its expiration time.
Returns:
{
session_token: string;
expires_at: string;
}Example:
const refreshed = await krapi.auth.refreshSession();
console.log('New expiration:', refreshed.expires_at);validateSession(token: string)
Validate a session token and retrieve the associated user.
Parameters:
token(required) - Session token to validate
Returns:
{
valid: boolean;
session?: AdminUser | ProjectUser;
}Example:
const validation = await krapi.auth.validateSession('token-here');
if (validation.valid && validation.session) {
console.log('Valid session for user:', validation.session.username);
}changePassword(oldPassword: string, newPassword: string)
Change the password for the current user. Requires user context.
Parameters:
oldPassword(required) - Current passwordnewPassword(required) - New password
Returns:
{ success: boolean }Example:
const result = await krapi.auth.changePassword('oldpass', 'newpass');
if (result.success) {
console.log('Password changed successfully');
}regenerateApiKey(req: unknown)
Regenerate an API key for the current user or context.
Parameters:
req(required) - Request context (varies by implementation)
Returns:
{
success: boolean;
data?: { apiKey: string };
error?: string;
}Advanced Authentication Methods
adminLogin(credentials: { username: string; password: string; remember_me?: boolean })
Admin-level login with enhanced response format.
Parameters:
credentials.username(required) - Admin usernamecredentials.password(required) - Admin passwordcredentials.remember_me(optional) - Long-lived session
Returns:
{
success: boolean;
data?: {
session_token: string;
expires_at: string;
user: AdminUser | ProjectUser;
scopes: string[];
};
error?: string;
}Example:
const result = await krapi.auth.adminLogin({
username: 'admin',
password: 'password',
remember_me: true
});
if (result.success && result.data) {
await krapi.auth.setSessionToken(result.data.session_token);
}adminApiLogin(apiKey: string | { api_key?: string })
Admin-level authentication using API key.
Parameters:
apiKey(required) - API key string or object withapi_keyproperty
Returns:
{
success: boolean;
data?: {
user: AdminUser & { scopes: string[] };
session_token: string;
expires_at: string;
};
error?: string;
}Example:
const result = await krapi.auth.adminApiLogin('admin-api-key');
if (result.success && result.data) {
console.log('Admin user:', result.data.user.username);
await krapi.auth.setSessionToken(result.data.session_token);
}register(registerData: { username: string; email: string; password: string; role?: string; access_level?: string; permissions?: string[] })
Register a new user account.
Parameters:
registerData.username(required) - UsernameregisterData.email(required) - Email addressregisterData.password(required) - PasswordregisterData.role(optional) - User roleregisterData.access_level(optional) - Access levelregisterData.permissions(optional) - Array of permissions
Returns:
{
success: boolean;
user: Record<string, unknown>;
}Example:
const result = await krapi.auth.register({
username: 'newuser',
email: '[email protected]',
password: 'securepassword',
role: 'user',
access_level: 'standard'
});
if (result.success) {
console.log('User registered:', result.user);
}validateApiKey(apiKey: string)
Validate an API key and retrieve its information.
Parameters:
apiKey(required) - API key to validate
Returns:
{
valid: boolean;
key_info?: {
id: string;
name: string;
type: string;
scopes: string[];
project_id?: string;
};
}Example:
const validation = await krapi.auth.validateApiKey('api-key-here');
if (validation.valid && validation.key_info) {
console.log('Key name:', validation.key_info.name);
console.log('Scopes:', validation.key_info.scopes);
}Authentication Flow Examples
Complete Login Flow:
// 1. Connect to server
await krapi.connect({
endpoint: 'http://localhost:3470/krapi/k1',
apiKey: 'initial-api-key' // Optional initial auth
});
// 2. Login with credentials
const loginResult = await krapi.auth.login('username', 'password');
// 3. Set session token (automatically used, but can set explicitly)
await krapi.auth.setSessionToken(loginResult.session_token);
// 4. Verify authentication
const user = await krapi.auth.getCurrentUser();
console.log('Authenticated as:', user.data?.username);
// 5. Use authenticated session
const projects = await krapi.projects.getAll();
// 6. Refresh session before expiration
const refreshed = await krapi.auth.refreshSession();
// 7. Logout when done
await krapi.auth.logout();API Key Authentication Flow:
// Connect with API key
await krapi.connect({
endpoint: 'http://localhost:3470/krapi/k1',
apiKey: 'your-api-key'
});
// Or set API key after connection
krapi.auth.setApiKey('your-api-key');
// Validate the API key
const validation = await krapi.auth.validateApiKey('your-api-key');
if (validation.valid) {
console.log('API key is valid');
}
// Create session from API key
const session = await krapi.auth.createSession('your-api-key');
await krapi.auth.setSessionToken(session.session_token);Error Handling:
import { KrapiError } from '@smartsamurai/krapi-sdk';
try {
await krapi.auth.login('username', 'wrong-password');
} catch (error) {
if (error instanceof KrapiError) {
if (error.isAuthError()) {
console.error('Authentication failed:', error.message);
} else {
console.error('Error:', error.getDetailedMessage());
}
}
}Services Reference
Complete documentation for all KRAPI SDK services. Each service works identically in both client and server modes.
Projects Service
The Projects service (krapi.projects) manages project creation, configuration, and statistics. Projects are top-level containers that organize collections, documents, users, and other resources.
Overview
Projects provide:
- Isolation - Each project has its own collections, documents, and users
- Configuration - Project-specific settings and metadata
- Statistics - Usage metrics and activity tracking
- Access Control - Project-level permissions and API keys
Methods
create(projectData: { name: string; description?: string; settings?: Record<string, unknown> })
Create a new project.
Parameters:
projectData.name(required) - Project name (must be unique)projectData.description(optional) - Project descriptionprojectData.settings(optional) - Project settings object
Returns: Promise<Project>
Example:
// Client Mode
await krapi.connect({ endpoint: 'http://localhost:3470/krapi/k1', apiKey: 'key' });
const project = await krapi.projects.create({
name: 'My Application',
description: 'Main application project',
settings: {
theme: 'dark',
language: 'en'
}
});
console.log('Created project:', project.id);Example (Server Mode):
// Server Mode - same API!
await krapi.connect({ database: dbConnection });
const project = await krapi.projects.create({
name: 'My Application',
description: 'Main application project'
});get(projectId: string)
Get a project by its ID.
Parameters:
projectId(required) - Project UUID
Returns: Promise<Project>
Example:
const project = await krapi.projects.get('project-uuid-here');
console.log('Project name:', project.name);
console.log('Created at:', project.created_at);getAll(options?: { limit?: number; offset?: number; search?: string; status?: string })
List all projects with optional filtering and pagination.
Parameters:
options.limit(optional) - Maximum number of results (default: unlimited)options.offset(optional) - Number of results to skip (default: 0)options.search(optional) - Search query to filter by name/descriptionoptions.status(optional) - Filter by status ('active', 'inactive', etc.)
Returns: Promise<Project[]>
Example:
// Get all projects
const allProjects = await krapi.projects.getAll();
// Paginated results
const page1 = await krapi.projects.getAll({ limit: 10, offset: 0 });
const page2 = await krapi.projects.getAll({ limit: 10, offset: 10 });
// Search projects
const searchResults = await krapi.projects.getAll({
search: 'application',
limit: 20
});update(projectId: string, updates: Record<string, unknown>)
Update project properties.
Parameters:
projectId(required) - Project UUIDupdates(required) - Object with fields to update
Returns: Promise<Project>
Example:
const updated = await krapi.projects.update('project-id', {
name: 'Updated Project Name',
description: 'New description'
});delete(projectId: string)
Delete a project and all its associated resources.
Parameters:
projectId(required) - Project UUID
Returns: Promise<{ success: boolean }>
Example:
const result = await krapi.projects.delete('project-id');
if (result.success) {
console.log('Project deleted successfully');
}getStatistics(projectId: string)
Get project statistics including collection count, document count, user count, and storage usage.
Parameters:
projectId(required) - Project UUID
Returns: Promise<ProjectStats>
Example:
const stats = await krapi.projects.getStatistics('project-id');
console.log('Collections:', stats.collections_count);
console.log('Documents:', stats.documents_count);
console.log('Users:', stats.users_count);
console.log('Storage used:', stats.storage_used_bytes);getSettings(projectId: string)
Get project settings.
Parameters:
projectId(required) - Project UUID
Returns: Promise<ProjectSettings>
Example:
const settings = await krapi.projects.getSettings('project-id');
console.log('Settings:', settings);updateSettings(projectId: string, settings: Record<string, unknown>)
Update project settings.
Parameters:
projectId(required) - Project UUIDsettings(required) - Settings object to merge
Returns: Promise<ProjectSettings>
Example:
const updated = await krapi.projects.updateSettings('project-id', {
theme: 'light',
notifications_enabled: true
});getActivity(projectId: string, options?: { limit?: number; offset?: number; action_type?: string; start_date?: string; end_date?: string })
Get project activity log.
Parameters:
projectId(required) - Project UUIDoptions.limit(optional) - Maximum number of resultsoptions.offset(optional) - Number of results to skipoptions.action_type(optional) - Filter by action typeoptions.start_date(optional) - Start date (ISO string)options.end_date(optional) - End date (ISO string)
Returns: Promise<ActivityLog[]>
Example:
// Get recent activity
const activity = await krapi.projects.getActivity('project-id', {
limit: 50,
action_type: 'create'
});
// Get activity for date range
const rangeActivity = await krapi.projects.getActivity('project-id', {
start_date: '2024-01-01T00:00:00Z',
end_date: '2024-01-31T23:59:59Z'
});Complete Example
// Create a project
const project = await krapi.projects.create({
name: 'Task Manager',
description: 'Project management application'
});
// Get project details
const details = await krapi.projects.get(project.id);
// Update project
await krapi.projects.update(project.id, {
description: 'Updated description'
});
// Get statistics
const stats = await krapi.projects.getStatistics(project.id);
console.log(`Project has ${stats.collections_count} collections`);
// Get activity
const activity = await krapi.projects.getActivity(project.id, { limit: 10 });
// Update settings
await krapi.projects.updateSettings(project.id, {
auto_backup: true,
retention_days: 30
});Collections Service
The Collections service (krapi.collections) manages database collections (tables) within projects. Collections define the schema for documents stored in them.
Overview
Collections provide:
- Schema Definition - Field types, validation rules, and constraints
- Indexing - Performance optimization through indexes
- Validation - Schema validation for data integrity
- Statistics - Document count and storage metrics
Methods
create(projectId: string, collectionData: { name: string; description?: string; fields: Array<FieldDefinition>; indexes?: Array<IndexDefinition> })
Create a new collection with schema definition.
Parameters:
projectId(required) - Project UUIDcollectionData.name(required) - Collection name (must be unique within project)collectionData.description(optional) - Collection descriptioncollectionData.fields(required) - Array of field definitions:name(required) - Field nametype(required) - Field type ('string', 'number', 'boolean', 'date', 'json', etc.)required(optional) - Whether field is required (default: false)unique(optional) - Whether field values must be unique (default: false)indexed(optional) - Whether field is indexed (default: false)default(optional) - Default valuevalidation(optional) - Validation rules object
collectionData.indexes(optional) - Array of index definitions:name(required) - Index namefields(required) - Array of field names to indexunique(optional) - Whether index enforces uniqueness
Returns: Promise<Collection>
Example:
const collection = await krapi.collections.create('project-id', {
name: 'tasks',
description: 'Task management collection',
fields: [
{
name: 'title',
type: 'string',
required: true,
indexed: true
},
{
name: 'completed',
type: 'boolean',
default: false
},
{
name: 'due_date',
type: 'date',
required: false
},
{
name: 'priority',
type: 'number',
default: 0,
validation: { min: 0, max: 5 }
}
],
indexes: [
{
name: 'idx_completed',
fields: ['completed']
},
{
name: 'idx_title_unique',
fields: ['title'],
unique: true
}
]
});get(projectId: string, collectionName: string)
Get a collection by name.
Parameters:
projectId(required) - Project UUIDcollectionName(required) - Collection name
Returns: Promise<Collection>
Example:
const collection = await krapi.collections.get('project-id', 'tasks');
console.log('Collection fields:', collection.fields);getAll(projectId: string, options?: { limit?: number; offset?: number; search?: string })
List all collections in a project.
Parameters:
projectId(required) - Project UUIDoptions.limit(optional) - Maximum number of resultsoptions.offset(optional) - Number of results to skipoptions.search(optional) - Search query to filter by name/description
Returns: Promise<Collection[]>
Example:
// Get all collections
const collections = await krapi.collections.getAll('project-id');
// Search collections
const searchResults = await krapi.collections.getAll('project-id', {
search: 'task',
limit: 10
});update(projectId: string, collectionName: string, updates: { description?: string; fields?: Array<FieldDefinition> })
Update collection metadata or schema.
Parameters:
projectId(required) - Project UUIDcollectionName(required) - Collection nameupdates.description(optional) - New descriptionupdates.fields(optional) - Updated field definitions
Returns: Promise<Collection>
Example:
const updated = await krapi.collections.update('project-id', 'tasks', {
description: 'Updated description'
});delete(projectId: string, collectionName: string)
Delete a collection and all its documents.
Parameters:
projectId(required) - Project UUIDcollectionName(required) - Collection name
Returns: Promise<{ success: boolean }>
Example:
const result = await krapi.collections.delete('project-id', 'tasks');
if (result.success) {
console.log('Collection deleted');
}getSchema(projectId: string, collectionName: string)
Get the complete schema definition for a collection.
Parameters:
projectId(required) - Project UUIDcollectionName(required) - Collection name
Returns: Promise<Collection>
Example:
const schema = await krapi.collections.getSchema('project-id', 'tasks');
console.log('Schema:', JSON.stringify(schema, null, 2));validateSchema(projectId: string, collectionName: string)
Validate a collection's schema for issues.
Parameters:
projectId(required) - Project UUIDcollectionName(required) - Collection name
Returns: Promise<{ valid: boolean; issues: Array<{ type: string; field?: string; message: string; severity: 'error' | 'warning' | 'info' }> }>
Example:
const validation = await krapi.collections.validateSchema('project-id', 'tasks');
if (!validation.valid) {
validation.issues.forEach(issue => {
console.error(`${issue.severity}: ${issue.message}`);
});
}getStatistics(projectId: string, collectionName: string)
Get collection statistics.
Parameters:
projectId(required) - Project UUIDcollectionName(required) - Collection name
Returns: Promise<{ total_documents: number; total_size_bytes: number }>
Example:
const stats = await krapi.collections.getStatistics('project-id', 'tasks');
console.log(`Total documents: ${stats.total_documents}`);
console.log(`Size: ${stats.total_size_bytes} bytes`);Documents Service
The Documents service (krapi.documents) manages documents (records) within collections. Documents are JSON objects that conform to their collection's schema.
Overview
Documents provide:
- CRUD Operations - Create, read, update, delete documents
- Querying - Filter, search, and paginate documents
- Bulk Operations - Efficient batch processing
- Aggregation - Group and analyze document data
Methods
create(projectId: string, collectionName: string, documentData: { data: Record<string, unknown>; created_by?: string })
Create a new document in a collection.
Parameters:
projectId(required) - Project UUIDcollectionName(required) - Collection namedocumentData.data(required) - Document data object (must conform to collection schema)documentData.created_by(optional) - User ID who created the document
Returns: Promise<Document>
Example:
const document = await krapi.documents.create('project-id', 'tasks', {
data: {
title: 'Complete documentation',
completed: false,
priority: 3,
due_date: '2024-12-31'
},
created_by: 'user-id'
});
console.log('Created document:', document.id);get(projectId: string, collectionName: string, documentId: string)
Get a document by ID.
Parameters:
projectId(required) - Project UUIDcollectionName(required) - Collection namedocumentId(required) - Document UUID
Returns: Promise<Document>
Example:
const document = await krapi.documents.get('project-id', 'tasks', 'doc-id');
console.log('Document:', document.data);getAll(projectId: string, collectionName: string, options?: { filter?: Record<string, unknown>; limit?: number; offset?: number; orderBy?: string; order?: 'asc' | 'desc'; search?: string })
List documents with filtering, sorting, and pagination.
Parameters:
projectId(required) - Project UUIDcollectionName(required) - Collection nameoptions.filter(optional) - Filter criteria object (e.g.,{ completed: false })options.limit(optional) - Maximum number of resultsoptions.offset(optional) - Number of results to skipoptions.orderBy(optional) - Field name to sort byoptions.order(optional) - Sort order ('asc' or 'desc')options.search(optional) - Text search query
Returns: Promise<Document[]>
Example:
// Get all documents
const all = await krapi.documents.getAll('project-id', 'tasks');
// Filter and paginate
const incomplete = await krapi.documents.getAll('project-id', 'tasks', {
filter: { completed: false },
limit: 10,
offset: 0,
orderBy: 'due_date',
order: 'asc'
});
// Search
const searchResults = await krapi.documents.getAll('project-id', 'tasks', {
search: 'documentation',
limit: 20
});update(projectId: string, collectionName: string, documentId: string, updateData: { data: Record<string, unknown>; updated_by?: string })
Update a document.
Parameters:
projectId(required) - Project UUIDcollectionName(required) - Collection namedocumentId(required) - Document UUIDupdateData.data(required) - Updated data object (partial updates supported)updateData.updated_by(optional) - User ID who updated the document
Returns: Promise<Document>
Example:
const updated = await krapi.documents.update('project-id', 'tasks', 'doc-id', {
data: {
completed: true,
completed_at: new Date().toISOString()
},
updated_by: 'user-id'
});delete(projectId: string, collectionName: string, documentId: string, deletedBy?: string)
Delete a document.
Parameters:
projectId(required) - Project UUIDcollectionName(required) - Collection namedocumentId(required) - Document UUIDdeletedBy(optional) - User ID who deleted the document
Returns: Promise<{ success: boolean }>
Example:
const result = await krapi.documents.delete('project-id', 'tasks', 'doc-id', 'user-id');
if (result.success) {
console.log('Document deleted');
}search(projectId: string, collectionName: string, query: { text?: string; fields?: string[]; filters?: Record<string, unknown>; limit?: number; offset?: number })
Search documents with full-text search.
Parameters:
projectId(required) - Project UUIDcollectionName(required) - Collection namequery.text(optional) - Text to search forquery.fields(optional) - Fields to search in (default: all text fields)query.filters(optional) - Additional filter criteriaquery.limit(optional) - Maximum number of resultsquery.offset(optional) - Number of results to skip
Returns: Promise<Document[]>
Example:
const results = await krapi.documents.search('project-id', 'tasks', {
text: 'documentation',
fields: ['title', 'description'],
filters: { completed: false },
limit: 10
});bulkCreate(projectId: string, collectionName: string, documents: Array<{ data: Record<string, unknown>; created_by?: string }>)
Create multiple documents in a single operation.
Parameters:
projectId(required) - Project UUIDcollectionName(required) - Collection namedocuments(required) - Array of document data objects
Returns: Promise<{ created: Document[]; errors: Array<{ index: number; error: string }> }>
Example:
const result = await krapi.documents.bulkCreate('project-id', 'tasks', [
{ data: { title: 'Task 1', completed: false } },
{ data: { title: 'Task 2', completed: false } },
{ data: { title: 'Task 3', completed: true } }
]);
console.log(`Created ${result.created.length} documents`);
if (result.errors.length > 0) {
console.error('Errors:', result.errors);
}bulkUpdate(projectId: string, collectionName: string, updates: Array<{ id: string; data: Record<string, unknown>; updated_by?: string }>)
Update multiple documents in a single operation.
Parameters:
projectId(required) - Project UUIDcollectionName(required) - Collection nameupdates(required) - Array of update objects with document ID and data
Returns: Promise<{ updated: Document[]; errors: Array<{ id: string; error: string }> }>
Example:
const result = await krapi.documents.bulkUpdate('project-id', 'tasks', [
{ id: 'doc-1', data: { completed: true } },
{ id: 'doc-2', data: { priority: 5 } }
]);
console.log(`Updated ${result.updated.length} documents`);bulkDelete(projectId: string, collectionName: string, documentIds: string[], deletedBy?: string)
Delete multiple documents in a single operation.
Parameters:
projectId(required) - Project UUIDcollectionName(required) - Collection namedocumentIds(required) - Array of document UUIDsdeletedBy(optional) - User ID who deleted the documents
Returns: Promise<{ deleted_count: number; errors: Array<{ id: string; error: string }> }>
Example:
const result = await krapi.documents.bulkDelete('project-id', 'tasks', [
'doc-id-1',
'doc-id-2',
'doc-id-3'
], 'user-id');
console.log(`Deleted ${result.deleted_count} documents`);count(projectId: string, collectionName: string, filter?: Record<string, unknown>)
Count documents matching a filter.
Parameters:
projectId(required) - Project UUIDcollectionName(required) - Collection namefilter(optional) - Filter criteria
Returns: Promise<{ count: number }>
Example:
// Count all documents
const total = await krapi.documents.count('project-id', 'tasks');
// Count with filter
const incomplete = await krapi.documents.count('project-id', 'tasks', {
completed: false
});aggregate(projectId: string, collectionName: string, aggregation: { group_by?: string[]; aggregations: Record<string, { type: 'count' | 'sum' | 'avg' | 'min' | 'max'; field?: string }>; filters?: Record<string, unknown> })
Aggregate document data with grouping and calculations.
Parameters:
projectId(required) - Project UUIDcollectionName(required) - Collection nameaggregation.group_by(optional) - Fields to group byaggregation.aggregations(required) - Aggregation operations:type- Operation type ('count', 'sum', 'avg', 'min', 'max')field- Field name to aggregate (required for sum/avg/min/max)
aggregation.filters(optional) - Filter criteria
Returns: Promise<{ groups: Record<string, Record<string, number>>; total_groups: number }>
Example:
// Group by status and count
const result = await krapi.documents.aggregate('project-id', 'tasks', {
group_by: ['status'],
aggregations: {
count: { type: 'count' },
avg_priority: { type: 'avg', field: 'priority' }
},
filters: { completed: false }
});
console.log('Groups:', result.groups);
console.log('Total groups:', result.total_groups);Users Service
The Users service (krapi.users) manages project users, roles, permissions, and user activity within a project.
Overview
Users provide:
- User Management - Create, update, and delete project users
- Role Management - Assign and update user roles
- Permissions - Fine-grained permission control
- Activity Tracking - User activity logs and statistics
Methods
getAll(projectId: string, options?: { limit?: number; offset?: number; search?: string; role?: string; status?: string })
List all users in a project with optional filtering.
Parameters:
projectId(required) - Project UUIDoptions.limit(optional) - Maximum number of resultsoptions.offset(optional) - Number of results to skipoptions.search(optional) - Search query (searches username, email, first_name, last_name)options.role(optional) - Filter by roleoptions.status(optional) - Filter by status ('active', 'inactive', etc.)
Returns: Promise<ProjectUser[]>
Example:
// Get all users
const users = await krapi.users.getAll('project-id');
// Filter by role
const admins = await krapi.users.getAll('project-id', {
role: 'admin',
limit: 10
});
// Search users
const searchResults = await krapi.users.getAll('project-id', {
search: 'john',
status: 'active'
});get(projectId: string, userId: string)
Get a user by ID.
Parameters:
projectId(required) - Project UUIDuserId(required) - User UUID
Returns: Promise<ProjectUser>
Example:
const user = await krapi.users.get('project-id', 'user-id');
console.log('User:', user.username, user.email);create(projectId: string, userData: { username: string; email: string; password: string; first_name?: string; last_name?: string; role?: string; permissions?: string[]; metadata?: Record<string, unknown> })
Create a new project user.
Parameters:
projectId(required) - Project UUIDuserData.username(required) - Username (must be unique within project)userData.email(required) - Email address (must be unique within project)userData.password(required) - Password (will be hashed)userData.first_name(optional) - First nameuserData.last_name(optional) - Last nameuserData.role(optional) - User role (default: 'user')userData.permissions(optional) - Array of permission stringsuserData.metadata(optional) - Additional metadata object
Returns: Promise<ProjectUser>
Example:
const user = await krapi.users.create('project-id', {
username: 'johndoe',
email: '[email protected]',
password: 'securepassword123',
first_name: 'John',
last_name: 'Doe',
role: 'editor',
permissions: ['read', 'write'],
metadata: {
department: 'Engineering',
location: 'Remote'
}
});
console.log('Created user:', user.id);update(projectId: string, userId: string, updates: { username?: string; email?: string; first_name?: string; last_name?: string; role?: string; permissions?: string[]; is_active?: boolean; metadata?: Record<string, unknown> })
Update user properties.
Parameters:
projectId(required) - Project UUIDuserId(required) - User UUIDupdates(required) - Object with fields to update (all fields optional)
Returns: Promise<ProjectUser>
Example:
const updated = await krapi.users.update('project-id', 'user-id', {
first_name: 'Jane',
role: 'admin',
is_active: true
});delete(projectId: string, userId: string)
Delete a user from the project.
Parameters:
projectId(required) - Project UUIDuserId(required) - User UUID
Returns: Promise<{ success: boolean }>
Example:
const result = await krapi.users.delete('project-id', 'user-id');
if (result.success) {
console.log('User deleted');
}updateRole(projectId: string, userId: string, role: string)
Update a user's role.
Parameters:
projectId(required) - Project UUIDuserId(required) - User UUIDrole(required) - New role name
Returns: Promise<ProjectUser>
Example:
const user = await krapi.users.updateRole('project-id', 'user-id', 'admin');
console.log('Updated role:', user.role);updatePermissions(projectId: string, userId: string, permissions: string[])
Update a user's permissions.
Parameters:
projectId(required) - Project UUIDuserId(required) - User UUIDpermissions(required) - Array of permission strings
Returns: Promise<ProjectUser>
Example:
const user = await krapi.users.updatePermissions('project-id', 'user-id', [
'read',
'write',
'delete',
'admin'
]);
console.log('Updated permissions:', user.permissions);getActivity(projectId: string, userId: string, options?: { limit?: number; offset?: number; start_date?: string; end_date?: string })
Get user activity log.
Parameters:
projectId(required) - Project UUIDuserId(required) - User UUIDoptions.limit(optional) - Maximum number of resultsoptions.offset(optional) - Number of results to skipoptions.start_date(optional) - Start date (ISO string)options.end_date(optional) - End date (ISO string)
Returns: Promise<Array<{ id: string; action: string; timestamp: string; details: Record<string, unknown> }>>
Example:
// Get recent activity
const activity = await krapi.users.getActivity('project-id', 'user-id', {
limit: 50
});
// Get activity for date range
const rangeActivity = await krapi.users.getActivity('project-id', 'user-id', {
start_date: '2024-01-01T00:00:00Z',
end_date: '2024-01-31T23:59:59Z',
limit: 100
});getStatistics(projectId: string)
Get user statistics for the project.
Parameters:
projectId(required) - Project UUID
Returns: Promise<{ total_users: number; active_users: number; users_by_role: Record<string, number>; recent_logins: number }>
Example:
const stats = await krapi.users.getStatistics('project-id');
console.log(`Total users: ${stats.total_users}`);
console.log(`Active users: ${stats.active_users}`);
console.log('Users by role:', stats.users_by_role);
console.log(`Recent logins: ${stats.recent_logins}`);Storage Service
The Storage service (krapi.storage) manages file uploads, downloads, folder organization, and storage statistics within projects.
Overview
Storage provides:
- File Management - Upload, download, and delete files
- Folder Organization - Hierarchical folder structure
- Metadata - File and folder metadata
- Statistics - Storage usage and quota information
- URL Generation - Temporary signed URLs for file access
Methods
uploadFile(projectId: string, file: File | Blob, options?: { folder?: string; filename?: string; metadata?: Record<string, unknown>; public?: boolean })
Upload a file to project storage.
Parameters:
projectId(required) - Project UUIDfile(required) - File or Blob object to uploadoptions.folder(optional) - Target folder path or folder IDoptions.filename(optional) - Custom filename (default: original filename)options.metadata(optional) - File metadata objectoptions.public(optional) - Whether file is publicly accessible (default: false)
Returns: Promise<FileInfo>
Example:
// Upload from File input
const fileInput = document.querySelector('input[type="file"]');
const file = fileInput.files[0];
const fileInfo = await krapi.storage.uploadFile('project-id', file, {
folder: 'uploads',
filename: 'custom-name.jpg',
metadata: {
uploaded_by: 'user-id',
category: 'images'
},
public: true
});
console.log('Uploaded file:', fileInfo.id);downloadFile(projectId: string, fileId: string)
Download a file as a Blob.
Parameters:
projectId(required) - Project UUIDfileId(required) - File UUID
Returns: Promise<Blob>
Example:
const blob = await krapi.storage.downloadFile('project-id', 'file-id');
// Use the blob
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'filename.ext';
a.click();getFile(projectId: string, fileId: string)
Get file information and metadata.
Parameters:
projectId(required) - Project UUIDfileId(required) - File UUID
Returns: Promise<FileInfo>
Example:
const fileInfo = await krapi.storage.getFile('project-id', 'file-id');
console.log('File name:', fileInfo.filename);
console.log('Size:', fileInfo.size_bytes);
console.log('Type:', fileInfo.content_type);
console.log('Metadata:', fileInfo.metadata);deleteFile(projectId: string, fileId: string)
Delete a file.
Parameters:
projectId(required) - Project UUIDfileId(required) - File UUID
Returns: Promise<{ success: boolean }>
Example:
const result = await krapi.storage.deleteFile('project-id', 'file-id');
if (result.success) {
console.log('File deleted');
}getFiles(projectId: string, options?: { folder?: string; limit?: number; offset?: number; search?: string; type?: string })
List files with filtering and pagination.
Parameters:
projectId(required) - Project UUIDoptions.folder(optional) - Filter by folder path or IDoptions.limit(optional) - Maximum number of resultsoptions.offset(optional) - Number of results to skipoptions.search(optional) - Search query (searches filename)options.type(optional) - Filter by file type/MIME type
Returns: Promise<FileInfo[]>
Example:
// Get all files
const allFiles = await krapi.storage.getFiles('project-id');
// Get files in folder
const folderFiles = await krapi.storage.getFiles('project-id', {
folder: 'uploads/images',
limit: 20
});
// Search files
const searchResults = await krapi.storage.getFiles('project-id', {
search: 'photo',
type: 'image/jpeg'
});createFolder(projectId: string, folderData: { name: string; parent_folder_id?: string; metadata?: Record<string, unknown> })
Create a folder.
Parameters:
projectId(required) - Project UUIDfolderData.name(required) - Folder namefolderData.parent_folder_id(optional) - Parent folder ID (for nested folders)folderData.metadata(optional) - Folder metadata object
Returns: Promise<{ id: string; name: string; parent_folder_id?: string; metadata?: Record<string, unknown> }>
Example:
// Create root folder
const folder = await krapi.storage.createFolder('project-id', {
name: 'documents'
});
// Create nested folder
const subfolder = await krapi.storage.createFolder('project-id', {
name: 'images',
parent_folder_id: folder.id,
metadata: { category: 'photos' }
});getFolders(projectId: string, parentFolderId?: string)
List folders, optionally filtered by parent folder.
Parameters:
projectId(required) - Project UUIDparentFolderId(optional) - Parent folder ID (to get subfolders)
Returns: Promise<Array<{ id: string; name: string; parent_folder_id?: string; metadata?: Record<string, unknown> }>>
Example:
// Get root folders
const rootFolders = await krapi.storage.getFolders('project-id');
// Get subfolders
const subfolders = await krapi.storage.getFolders('project-id', 'parent-folder-id');deleteFolder(projectId: string, folderId: string)
Delete a folder and all its contents.
Parameters:
projectId(required) - Project UUIDfolderId(required) - Folder UUID
Returns: Promise<{ success: boolean }>
Example:
const result = await krapi.storage.deleteFolder('project-id', 'folder-id');
if (result.success) {
console.log('Folder deleted');
}getStatistics(projectId: string)
Get storage statistics for the project.
Parameters:
projectId(required) - Project UUID
Returns: Promise<{ total_files: number; total_size_bytes: number; files_by_type: Record<string, number>; storage_quota: { used: number; limit: number; percentage: number } }>
Example:
const stats = await krapi.storage.getStatistics('project-id');
console.log(`Total files: ${stats.total_files}`);
console.log(`Total size: ${stats.total_size_bytes} bytes`);
console.log(`Quota used: ${stats.storage_quota.percentage}%`);
console.log('Files by type:', stats.files_by_type);getFileUrl(projectId: string, fileId: string, options?: { expires_in?: number; download?: boolean })
Get a temporary signed URL for file access.
Parameters:
projectId(required) - Project UUIDfileId(required) - File UUIDoptions.expires_in(optional) - URL expiration time in seconds (default: 3600)options.download(optional) - Whether to force download (default: false)
Returns: Promise<{ url: string; expires_at?: string }>
Example:
// Get temporary URL (expires in 1 hour)
const urlResult = await krapi.storage.getFileUrl('project-id', 'file-id', {
expires_in: 3600
});
console.log('File URL:', urlResult.url);
console.log('Expires at:', urlResult.expires_at);
// Get download URL
const downloadUrl = await krapi.storage.getFileUrl('project-id', 'file-id', {
expires_in: 1800,
download: true
});Email Service
The Email service (krapi.email) manages email configuration, templates, and sending emails within projects.
Overview
Email provides:
- Configuration - Email provider setup (SMTP, SendGrid, etc.)
- Templates - Reusable email templates with variables
- Sending - Send emails with or without templates
- History - Email sending history and status tracking
Methods
getConfig(projectId: string)
Get email configuration for the project.
Parameters:
projectId(required) - Project UUID
Returns: Promise<EmailConfig>
Example:
const config = await krapi.email.getConfig('project-id');
console.log('Provider:', config.provider);
console.log('Settings:', config.settings);updateConfig(projectId: string, config: { provider: string; settings: Record<string, unknown> })
Update email configuration.
Parameters:
projectId(required) - Project UUIDconfig.provider(required) - Email provider name ('smtp', 'sendgrid', 'ses', etc.)config.settings(required) - Provider-specific settings object
Returns: Promise<EmailConfig>
Example:
// SMTP configuration
const updated = await krapi.email.updateConfig('project-id', {
provider: 'smtp',
settings: {
host: 'smtp.example.com',
port: 587,
secure: false,
auth: {
user: '[email protected]',
pass: 'password'
}
}
});testConfig(projectId: string, testEmail: string)
Test email configuration by sending a test email.
Parameters:
projectId(required) - Project UUIDtestEmail(required) - Email address to send test to
Returns: Promise<{ success: boolean; message?: string }>
Example:
const result = await krapi.email.testConfig('project-id', '[email protected]');
if (result.success) {
console.log('Email configuration is working');
} else {
console.error('Test failed:', result.message);
}getTemplates(projectId: string, options?: { limit?: number; offset?: number; search?: string })
List email templates.
Parameters:
projectId(required) - Project UUIDoptions.limit(optional) - Maximum number of resultsoptions.offset(optional) - Number of results to skipoptions.search(optional) - Search query
Returns: Promise<EmailTemplate[]>
Example:
const templates = await krapi.email.getTemplates('project-id', {
search: 'welcome',
limit: 10
});getTemplate(projectId: string, templateId: string)
Get an email template by ID.
Parameters:
projectId(required) - Project UUIDtemplateId(required) - Template UUID
Returns: Promise<EmailTemplate>
Example:
const template = await krapi.email.getTemplate('project-id', 'template-id');
console.log('Template:', template.name);
console.log('Subject:', template.subject);createTemplate(projectId: string, template: { name: string; subject: string; body: string; variables: string[]; type?: string })
Create an email template.
Parameters:
projectId(required) - Project UUIDtemplate.name(required) - Template nametemplate.subject(required) - Email subject (can include variables like {{name}})template.body(required) - Email body (can include variables like {{name}})template.variables(required) - Array of variable names used in templatetemplate.type(optional) - Template type ('html', 'text', etc.)
Returns: Promise<EmailTemplate>
Example:
const template = await krapi.email.createTemplate('project-id', {
name: 'welcome-email',
subject: 'Welcome to {{app_name}}, {{user_name}}!',
body: '<h1>Welcome {{user_name}}!</h1><p>Thanks for joining {{app_name}}.</p>',
variables: ['app_name', 'user_name'],
type: 'html'
});updateTemplate(projectId: string, templateId: string, updates: Partial<EmailTemplate>)
Update an email template.
Parameters:
projectId(required) - Project UUIDtemplateId(required) - Template UUIDupdates(required) - Partial template object with fields to update
Returns: Promise<EmailTemplate>
Example:
const updated = await krapi.email.updateTemplate('project-id', 'template-id', {
subject: 'Updated subject',
body: 'Updated body'
});deleteTemplate(projectId: string, templateId: string)
Delete an email template.
Parameters:
projectId(required) - Project UUIDtemplateId(required) - Template UUID
Returns: Promise<{ success: boolean }>
Example:
const result = await krapi.email.deleteTemplate('project-id', 'template-id');
if (result.success) {
console.log('Template deleted');
}send(projectId: string, emailData: { to: string | string[]; cc?: string | string[]; bcc?: string | string[]; subject: string; body: string; template_id?: string; template_variables?: Record<string, unknown>; attachments?: Array<{ filename: string; content: string | Buffer; content_type?: string }> })
Send an email.
Parameters:
projectId(required) - Project UUIDemailData.to(required) - Recipient email(s) - string or arrayemailData.cc(optional) - CC recipient(s)emailData.bcc(optional) - BCC recipient(s)emailData.subject(required) - Email subjectemailData.body(required) - Email bodyemailData.template_id(optional) - Template ID to useemailData.template_variables(optional) - Variables for templateemailData.attachments(optional) - Array of attachment objects
Returns: Promise<{ success: boolean; message_id?: string; error?: string }>
Example:
// Send simple email
const result = await krapi.email.send('project-id', {
to: '[email protected]',
subject: 'Hello',
body: 'This is a test email'
});
// Send with template
const templateResult = await krapi.email.send('project-id', {
to: '[email protected]',
template_id: 'welcome-email',
template_variables: {
app_name: 'My App',
user_name: 'John Doe'
}
});
// Send with attachments
const attachmentResult = await krapi.email.send('project-id', {
to: ['[email protected]', '[email protected]'],
subject: 'Report',
body: 'Please find attached report',
attachments: [
{
filename: 'report.pdf',
content: pdfBuffer,
content_type: 'application/pdf'
}
]
});getHistory(projectId: string, options?: { limit?: number; offset?: number; status?: string; start_date?: string; end_date?: string })
Get email sending history.
Parameters:
projectId(required) - Project UUIDoptions.limit(optional) - Maximum number of resultsoptions.offset(optional) - Number of results to skipoptions.status(optional) - Filter by status ('sent', 'failed', 'pending')options.start_date(optional) - Start date (ISO string)options.end_date(optional) - End date (ISO string)
Returns: Promise<Array<{ id: string; to: string; subject: string; status: string; sent_at: string }>>
Example:
// Get recent emails
const history = await krapi.email.getHistory('project-id', {
limit: 50,
status: 'sent'
});
// Get emails for date range
const rangeHistory = await krapi.email.getHistory('project-id', {
start_date: '2024-01-01T00:00:00Z',
end_date: '2024-01-31T23:59:59Z'
});Admin Service
The Admin service (krapi.admin) provides administrative operations for managing admin users, project API keys, and system maintenance. Most operations are available in server mode only.
Overview
Admin provides:
- User Management - Create, update, and delete admin users
- API Key Management - Manage project API keys
- System Maintenance - Database repair and default admin creation
Methods
getAllUsers(options?: { limit?: number; offset?: number; search?: string; role?: string; status?: string; project_id?: string })
List all admin users.
Returns: Promise<AdminUser[]>
Example:
const users = await krapi.admin.getAllUsers({
role: 'admin',
limit: 10
});getUser(userId: string)
Get an admin user by ID.
Returns: Promise<AdminUser>
createUser(userData: { username: string; email: string; password: string; first_name?: string; last_name?: string; role: 'admin' | 'user'; project_id?: string; permissions?: string[]; metadata?: Record<string, unknown> })
Create a new admin user.
Returns: Promise<AdminUser>
Example:
const admin = await krapi.admin.createUser({
username: 'newadmin',
email: '[email protected]',
password: 'securepassword',
role: 'admin',
permissions: ['all']
});updateUser(userId: string, updates: Partial<AdminUser>)
Update an admin user.
Returns: Promise<AdminUser>
deleteUser(userId: string)
Delete an admin user.
Returns: Promise<{ success: boolean }>
getProjectApiKeys(projectId: string)
Get all API keys for a project.
Returns: Promise<ApiKey[]>
getProjectApiKey(keyId: string, projectId: string)
Get a specific API key.
Returns: Promise<ApiKey | null>
createProjectApiKey(projectId: string, keyData: Partial<ApiKey>)
Create a new API key for a project.
Returns: Promise<ApiKey>
updateProjectApiKey(keyId: string, projectId: string, updates: Partial<ApiKey>)
Update a project API key.
Returns: Promise<ApiKey>
deleteProjectApiKey(keyId: string, projectId: string)
Delete a project API key.
Returns: Promise<boolean>
regenerateProjectApiKey(keyId: string, projectId: string)
Regenerate a project API key.
Returns: Promise<ApiKey>
createDefaultAdmin()
Create the default admin user (server mode only).
Returns: Promise<void>
repairDatabase()
Repair database issues (server mode only).
Returns: Promise<{ success: boolean; actions: string[] }>
Example:
const result = await krapi.admin.repairDatabase();
console.log('Repair actions:', result.actions);API Keys Service
The API Keys service (krapi.apiKeys) manages project API keys for authentication and authorization. Note: API Keys operations are primarily available in server mode through the admin service.
Methods
getAll(projectId: string, options?: { limit?: number; offset?: number; type?: string; status?: string })
List all API keys for a project (server mode only).
get(projectId: string, keyId: string)
Get an API key by ID (server mode only).
create(projectId: string, keyData: { name: string; scopes: string[]; expires_at?: string; rate_limit?: number; metadata?: Record<string, unknown> })
Create a new API key (server mode only).
update(projectId: string, keyId: string, updates: Partial<ApiKey>)
Update an API key (server mode only).
delete(projectId: string, keyId: string)
Delete an API key (server mode only).
regenerate(projectId: string, keyId: string)
Regenerate an API key, invalidating the old one (server mode only).
validateKey(apiKey: string)
Validate an API key and get its information.
Example:
const validation = await krapi.apiKeys.validateKey('api-key-here');
if (validation.valid) {
console.log('Key info:', validation.key_info);
}Database Service
The Database service (krapi.database) provides database initialization and health monitoring operations.
Methods
initialize()
Initialize the database schema (server mode only). Creates all required tables and default data.
Returns: Promise<{ success: boolean; message: string; tablesCreated: string[]; defaultDataInserted: boolean }>
Example:
// Server mode only
await krapi.connect({ database: dbConnection });
const result = await krapi.database.initialize();
console.log('Tables created:', result.tablesCreated);getHealth()
Get database health status.
Returns: Promise<{ database: boolean; storage: boolean; email: boolean; overall: boolean; details: Record<string, unknown> }>
Example:
const health = await krapi.database.getHealth();
console.log('Database healthy:', health.database);createDefaultAdmin()
Create the default admin user (server mode only).
Returns: Promise<{ success: boolean; message: string; adminUser?: { username: string; email: string } }>
Example:
const result = await krapi.database.createDefaultAdmin();
if (result.success) {
console.log('Default admin created:', result.adminUser);
}getQueueMetrics()
Get queue metrics (client mode only).
Returns: Promise<{ queueSize: number; processingCount: number; totalProcessed: number; totalErrors: number; averageWaitTime: number; averageProcessTime: number; queueItems: Array<{ id: string; priority: number; timestamp: number }> }>
Health Service
The Health service (krapi.health) provides system health monitoring, diagnostics, and database maintenance.
Methods
check()
Check overall system health.
Returns: Promise<{ healthy: boolean; message: string; details?: Record<string, unknown>; version: string }>
Example:
const health = await krapi.health.check();
console.log('System healthy:', health.healthy);
console.log('Version:', health.version);checkDatabase()
Check database health specifically.
Returns: Promise<{ healthy: boolean; message: string; details?: Record<string, unknown> }>
runDiagnostics()
Run comprehensive health diagnostics.
Returns: Promise<{ tests: Array<{ name: string; passed: boolean; message: string; duration: number }>; summary: { total: number; passed: number; failed: number; duration: number } }>
Example:
const diagnostics = await krapi.health.runDiagnostics();
console.log(`Passed: