UNPKG

@smartsamurai/krapi-sdk

Version:

KRAPI TypeScript SDK - Easy-to-use client SDK for connecting to self-hosted KRAPI servers (like Appwrite SDK)

284 lines (218 loc) 8.6 kB
# @smartsamurai/krapi-sdk TypeScript SDK for KRAPI - self-hosted backend-as-a-service platform. [![npm version](https://img.shields.io/npm/v/@smartsamurai/krapi-sdk.svg)](https://www.npmjs.com/package/@smartsamurai/krapi-sdk) [![License: Proprietary](https://img.shields.io/badge/License-Proprietary-red.svg)](LICENSE) ## Installation ```bash npm install @smartsamurai/krapi-sdk ``` **Requirements:** Node.js 18+, TypeScript 5.0+ (recommended) ## Quick Start ```typescript import { krapi } from '@smartsamurai/krapi-sdk'; // Connect to KRAPI server await krapi.connect({ endpoint: 'http://localhost:3470', apiKey: 'your-api-key' }); // Use SDK methods const projects = await krapi.projects.getAll(); const project = await krapi.projects.create({ name: 'My Project' }); ``` ## Modes ### Client Mode (HTTP) For frontend apps, Next.js routes, external services. Makes HTTP requests. ```typescript await krapi.connect({ endpoint: 'http://localhost:3470', apiKey: 'your-api-key' }); ``` ### Server Mode (Database) For backend services, Express routes. Direct database access. ```typescript await krapi.connect({ database: databaseConnection, logger: console }); ``` **Same API works in both modes.** ## Authentication ```typescript // API Key await krapi.connect({ endpoint: '...', apiKey: 'key' }); // Session Token const session = await krapi.auth.login('username', 'password'); krapi.auth.setSessionToken(session.session_token); // Get current user const user = await krapi.auth.getCurrentUser(); ``` ## API Reference ### Projects - `getAll(options?)` - List projects - `get(projectId)` - Get project - `create(data)` - Create project - `update(projectId, updates)` - Update project - `delete(projectId)` - Delete project - `getStatistics(projectId)` - Get project stats - `getActivity(projectId, options?)` - Get activity log **Routes:** `GET/POST/PUT/DELETE /krapi/k1/projects` ### Collections - `getAll(projectId, options?)` - List collections - `get(projectId, collectionName)` - Get collection - `create(projectId, data)` - Create collection - `update(projectId, collectionName, updates)` - Update collection - `delete(projectId, collectionName)` - Delete collection - `getSchema(projectId, collectionName)` - Get schema - `validateSchema(projectId, collectionName)` - Validate schema **Routes:** `GET/POST/PUT/DELETE /krapi/k1/projects/:projectId/collections` ### Documents - `getAll(projectId, collectionName, options?)` - List documents - `get(projectId, collectionName, documentId)` - Get document - `create(projectId, collectionName, data)` - Create document - `update(projectId, collectionName, documentId, updates)` - Update document - `delete(projectId, collectionName, documentId)` - Delete document - `search(projectId, collectionName, query)` - Search documents - `bulkCreate(projectId, collectionName, items)` - Bulk create - `bulkUpdate(projectId, collectionName, items)` - Bulk update - `bulkDelete(projectId, collectionName, ids)` - Bulk delete - `count(projectId, collectionName, filter?)` - Count documents - `aggregate(projectId, collectionName, pipeline)` - Aggregate **Routes:** `GET/POST/PUT/DELETE /krapi/k1/projects/:projectId/collections/:collectionName/documents` ### Users - `getAll(projectId, options?)` - List users - `get(projectId, userId)` - Get user - `create(projectId, userData)` - Create user - `update(projectId, userId, updates)` - Update user - `delete(projectId, userId)` - Delete user - `updateRole(projectId, userId, role)` - Update role - `updatePermissions(projectId, userId, permissions)` - Update permissions - `getActivity(projectId, userId, options?)` - Get user activity - `getStatistics(projectId)` - Get user statistics **Routes:** `GET/POST/PUT/DELETE /krapi/k1/projects/:projectId/users` ### Storage - `uploadFile(projectId, file, options?)` - Upload file - `downloadFile(projectId, fileId)` - Download file - `getFile(projectId, fileId)` - Get file info - `deleteFile(projectId, fileId)` - Delete file - `getFiles(projectId, options?)` - List files - `getFileUrl(projectId, fileId, options?)` - Get file URL - `createFolder(projectId, path)` - Create folder - `deleteFolder(projectId, path)` - Delete folder - `getStatistics(projectId)` - Get storage stats **Routes:** `GET/POST/DELETE /krapi/k1/projects/:projectId/storage` ### Email - `send(projectId, emailData)` - Send email - `sendTemplate(projectId, templateId, data)` - Send template email - `getTemplates(projectId)` - List templates - `createTemplate(projectId, templateData)` - Create template - `updateTemplate(projectId, templateId, updates)` - Update template - `deleteTemplate(projectId, templateId)` - Delete template - `getStatus(projectId, emailId)` - Get email status - `getHistory(projectId, options?)` - Get email history - `getAnalytics(projectId, options?)` - Get analytics **Routes:** `GET/POST/PUT/DELETE /krapi/k1/projects/:projectId/email` ### API Keys - `getAll(projectId, options?)` - List API keys - `get(projectId, keyId)` - Get API key - `create(projectId, keyData)` - Create API key - `update(projectId, keyId, updates)` - Update API key - `delete(projectId, keyId)` - Delete API key - `regenerate(projectId, keyId)` - Regenerate key - `validateKey(apiKey)` - Validate API key **Routes:** `GET/POST/PUT/DELETE /krapi/k1/projects/:projectId/api-keys` ### Database - `initialize()` - Initialize database (server mode only) - `getHealth()` - Get database health - `createDefaultAdmin()` - Create default admin (server mode only) - `getQueueMetrics()` - Get queue metrics (client mode only) **Routes:** `GET /krapi/k1/queue/metrics` ### Health - `check()` - Check health status - `checkDatabase()` - Check database health - `autoFix()` - Auto-fix issues - `validateSchema()` - Validate schema **Routes:** `GET /krapi/k1/health` ### System - `getSettings()` - Get system settings - `updateSettings(updates)` - Update settings - `getInfo()` - Get system info **Routes:** `GET/PUT /krapi/k1/system/settings` ### Activity - `log(activityData)` - Log activity - `getActivity(projectId, options?)` - Get activity log - `getStatistics(projectId)` - Get activity stats **Routes:** `GET/POST /krapi/k1/projects/:projectId/activity` ### Backups - `create(projectId, options?)` - Create backup - `getAll(projectId)` - List backups - `get(projectId, backupId)` - Get backup - `delete(projectId, backupId)` - Delete backup - `restore(projectId, backupId, options?)` - Restore backup **Routes:** `GET/POST/DELETE /krapi/k1/projects/:projectId/backups` ### MCP (Model Context Protocol) - `getCapabilities()` - Get MCP capabilities - `chat(messages, options?)` - Chat with model - `listModels()` - List available models **Routes:** `GET/POST /krapi/k1/mcp` ## Error Handling ```typescript import { KrapiError, HttpError } from '@smartsamurai/krapi-sdk'; try { const project = await krapi.projects.get('id'); } catch (error) { if (error instanceof KrapiError) { console.error('Code:', error.code); // NOT_FOUND, UNAUTHORIZED, etc. console.error('Status:', error.status); console.error('Message:', error.message); } } ``` **Error Codes:** `UNAUTHORIZED`, `FORBIDDEN`, `NOT_FOUND`, `CONFLICT`, `VALIDATION_ERROR`, `RATE_LIMIT_EXCEEDED`, `SERVER_ERROR`, `NETWORK_ERROR` ## Examples ### React ```typescript import { krapi } from '@smartsamurai/krapi-sdk'; useEffect(() => { krapi.connect({ endpoint: 'http://localhost:3470' }) .then(() => krapi.projects.getAll()) .then(setProjects); }, []); ``` ### Next.js API Route ```typescript import { krapi } from '@smartsamurai/krapi-sdk'; export async function GET() { await krapi.connect({ endpoint: process.env.KRAPI_URL }); const projects = await krapi.projects.getAll(); return Response.json(projects); } ``` ### Express (Server Mode) ```typescript import { krapi } from '@smartsamurai/krapi-sdk'; await krapi.connect({ database: dbConnection }); app.get('/projects', async (req, res) => { const projects = await krapi.projects.getAll(); res.json(projects); }); ``` ## Configuration ```typescript await krapi.connect({ // Client mode endpoint: 'http://localhost:3470', apiKey: 'your-api-key', sessionToken: 'token', timeout: 30000, // Server mode database: databaseConnection, logger: console }); ``` ## Support - **NPM**: [@smartsamurai/krapi-sdk](https://www.npmjs.com/package/@smartsamurai/krapi-sdk) - **Repository**: [Smart-Samurai/Krapi-SDK](https://github.com/Smart-Samurai/Krapi-SDK) - **Native App**: [GenorTG/Krapi](https://github.com/GenorTG/Krapi) ## License Proprietary. All rights reserved.