shruti-ai-sdk
v1.1.3
Published
JavaScript SDK for interacting with shrutiAI API
Maintainers
Readme
shrutiAI JavaScript SDK
A comprehensive JavaScript/TypeScript SDK for interacting with the shrutiAI API through the /chat-tool endpoint. This SDK provides a simple and intuitive interface for managing users, posts, analytics, and more using a unified chat-tool interface.
Features
- 🚀 Full TypeScript Support - Complete type definitions for better development experience
- 🔧 Easy to Use - Simple and intuitive API design
- 🛡️ Error Handling - Comprehensive error handling with custom exception classes
- 📊 Analytics Support - Built-in analytics and reporting capabilities
- 🧪 Well Tested - Comprehensive test suite with high coverage
- 📦 Modern Build - ES2020+ support with CommonJS output
Installation
npm install shruti-ai-sdkQuick Start
import { ShrutiAIClient } from 'shruti-ai-sdk';
// Initialize the client
const client = new ShrutiAIClient({
apiKey: 'your-api-key-here',
baseUrl: 'https://api.shrutiai.com/v1', // optional
timeout: 30000 // optional, default: 30000ms
});
// Get users
const users = await client.getUsers(10, 0);
// Create a new user
const newUser = await client.createUser('John Doe', '[email protected]');
// Get posts
const posts = await client.getPosts();
// Check API health
const health = await client.healthCheck();API Reference
Chat-Tool Endpoint
This SDK uses a unified /chat-tool endpoint where different functionalities are accessed through different tool names and payloads:
- User Management:
get_users,get_user,create_user,update_user,delete_user - Post Management:
get_posts,create_post - Analytics:
get_analytics - Utility:
health_check,get_api_info
Each request follows this structure:
{
"tool": "tool_name",
"payload": {
// tool-specific data
}
}Client Initialization
const client = new ShrutiAIClient({
apiKey: string, // Required: Your API key
baseUrl?: string, // Optional: Base URL (default: https://api.shrutiai.com/v1)
timeout?: number // Optional: Request timeout in ms (default: 30000)
});User Management
Get Users
// Get users with pagination
const users = await client.getUsers(limit, offset);
// Example
const users = await client.getUsers(10, 0); // Get first 10 usersGet User by ID
const user = await client.getUser('user-id');Create User
const user = await client.createUser(name, email, additionalData);
// Example
const user = await client.createUser('John Doe', '[email protected]', {
role: 'admin',
department: 'Engineering'
});Update User
const updatedUser = await client.updateUser('user-id', updateData);
// Example
const user = await client.updateUser('user-id', {
name: 'John Updated',
role: 'manager'
});Delete User
const success = await client.deleteUser('user-id');Posts Management
Get Posts
// Get all posts
const posts = await client.getPosts();
// Get posts with limit
const posts = await client.getPosts(undefined, 20);
// Get posts by user
const userPosts = await client.getPosts('user-id', 10);Create Post
const post = await client.createPost(title, content, userId);
// Example
const post = await client.createPost(
'My First Post',
'This is the content of my post',
'user-id'
);Analytics
Get Analytics
const analytics = await client.getAnalytics(startDate, endDate);
// Example
const analytics = await client.getAnalytics('2023-01-01', '2023-01-31');Utility Methods
Health Check
const health = await client.healthCheck();
// Returns: { status: 'healthy', timestamp: '2023-01-01T00:00:00Z' }API Info
const info = await client.getApiInfo();
// Returns: { name: 'shrutiAI API', version: '1.0.0', description: '...' }Error Handling
The SDK provides comprehensive error handling with custom exception classes:
import {
ShrutiAIError,
AuthenticationError,
RateLimitError,
NotFoundError,
ValidationError
} from 'shruti-ai-sdk';
try {
const users = await client.getUsers();
} catch (error) {
if (error instanceof AuthenticationError) {
console.log('Invalid API key');
} else if (error instanceof RateLimitError) {
console.log('Rate limit exceeded');
} else if (error instanceof NotFoundError) {
console.log('Resource not found');
} else if (error instanceof ValidationError) {
console.log('Invalid request data');
} else if (error instanceof ShrutiAIError) {
console.log('API error:', error.message);
} else {
console.log('Unexpected error:', error.message);
}
}TypeScript Support
The SDK is written in TypeScript and provides complete type definitions:
import { ShrutiAIClient, User, Post, AnalyticsData } from 'shruti-ai-sdk';
const client = new ShrutiAIClient({ apiKey: 'your-key' });
// All methods are fully typed
const users: User[] = await client.getUsers();
const posts: Post[] = await client.getPosts();
const analytics: AnalyticsData = await client.getAnalytics('2023-01-01', '2023-01-31');Development
Prerequisites
- Node.js 14.0.0 or higher
- npm or yarn
Setup
Clone the repository
Install dependencies:
npm installBuild the project:
npm run buildRun tests:
npm testRun tests with coverage:
npm run test:coverage
Available Scripts
npm run build- Compile TypeScript to JavaScriptnpm test- Run the test suitenpm run test:watch- Run tests in watch modenpm run test:coverage- Run tests with coverage reportnpm run dev- Compile TypeScript in watch mode
Project Structure
Javascript/
├── src/
│ ├── index.ts # Main entry point
│ ├── client.ts # Main client class
│ └── exceptions.ts # Exception classes
├── tests/
│ ├── setup.ts # Test setup
│ ├── exceptions.test.ts # Exception tests
│ ├── client.test.ts # Client tests
│ ├── integration.test.ts # Integration tests
│ └── complete-test.js # Complete test runner
├── dist/ # Compiled JavaScript (generated)
├── package.json
├── tsconfig.json
├── jest.config.js
└── README.mdTesting
The SDK includes a comprehensive test suite:
Run All Tests
npm testRun Specific Test Files
# Test exceptions
npm test exceptions.test.ts
# Test client
npm test client.test.ts
# Test integration
npm test integration.test.tsRun Complete Test Suite
node tests/complete-test.jsTest Coverage
npm run test:coverageExamples
Basic Usage
import { ShrutiAIClient } from 'shruti-ai-sdk';
const client = new ShrutiAIClient({ apiKey: 'your-api-key' });
async function main() {
try {
// Get all users
const users = await client.getUsers();
console.log('Users:', users);
// Create a new user
const newUser = await client.createUser('Jane Doe', '[email protected]');
console.log('Created user:', newUser);
// Get posts
const posts = await client.getPosts();
console.log('Posts:', posts);
// Check API health
const health = await client.healthCheck();
console.log('API Health:', health);
} catch (error) {
console.error('Error:', error.message);
}
}
main();Advanced Usage with Error Handling
import {
ShrutiAIClient,
AuthenticationError,
RateLimitError
} from 'shruti-ai-sdk';
const client = new ShrutiAIClient({ apiKey: 'your-api-key' });
async function handleUsers() {
try {
const users = await client.getUsers(50, 0);
return users;
} catch (error) {
if (error instanceof AuthenticationError) {
console.error('Authentication failed. Please check your API key.');
} else if (error instanceof RateLimitError) {
console.error('Rate limit exceeded. Please try again later.');
} else {
console.error('Unexpected error:', error.message);
}
throw error;
}
}Contributing
- Fork the repository
- Create a feature branch:
git checkout -b feature-name - Make your changes
- Add tests for your changes
- Run the test suite:
npm test - Commit your changes:
git commit -am 'Add feature' - Push to the branch:
git push origin feature-name - Submit a pull request
License
This project is licensed under the MIT License - see the LICENSE file for details.
Support
For support and questions:
- Create an issue on GitHub
- Check the documentation
- Review the test files for usage examples
Changelog
v1.1.1
- IMPROVEMENT: Fixed test files to work with real SDK
- Removed hardcoded mocks from test files
- Added proper installation test files
- Improved error handling in test scenarios
- Better documentation for package users
v1.1.0
- BREAKING CHANGE: Updated to use
/chat-toolendpoint - All API calls now use unified chat-tool interface
- Updated request/response structure
- Added new payload interfaces for better type safety
- Updated base URL to
https://api.shrutiai.com/v1
v1.0.1
- Initial release
- Complete TypeScript support
- Comprehensive test suite
- Full API coverage
- Error handling
- Documentation
