chimpbase-sdk
v0.2.4
Published
TypeScript SDK for ChimpBase Server
Maintainers
Readme
ChimpBase SDK
TypeScript SDK for ChimpBase Server. Provides a type-safe, fluent interface for managing collections and singles with full schema support.
Note: This SDK is designed to work with ChimpBase Server, the fastest way to create production-ready APIs from YAML schemas.
Features
- 🚀 Type-safe API with full TypeScript support and generics
- 🔗 Fluent Query Builder for complex queries with method chaining
- 🔐 Multiple Auth Methods (API Key & JWT with auto-refresh)
- 📦 Collections & Singles Complete CRUD operations
- 🔍 Advanced Filtering with rich operators (eq, gt, like, in, etc.)
- 📄 Pagination & Sorting Built-in pagination and ordering
- 🎯 Schema Discovery Runtime schema introspection
- ⚡ Error Handling Structured error responses with context
- 🛠️ Schema Management Local schema validation and sync
Installation
npm install chimpbase-sdk chimpbase-serverGetting Started
Step 1: Create a Schema File
ChimpBase Server requires a YAML schema file that defines your data structure. Create a file called schema.yaml:
# schema.yaml
version: '1.0.0'
collections:
posts:
fields:
title:
type: string
required: true
maxLength: 200
content:
type: string
required: true
status:
type: string
validators:
- type: isIn
value: ['draft', 'published', 'archived']
defaultValue: 'draft'
publishedAt:
type: date
tags:
type: array
items:
type: string
users:
fields:
name:
type: string
required: true
validators:
- type: minLength
value: 2
email:
type: string
required: true
unique: true
validators:
- type: isEmail
isActive:
type: boolean
defaultValue: true
singles:
site-settings:
fields:
siteName:
type: string
required: true
defaultValue: 'My Website'
theme:
type: string
validators:
- type: isIn
value: ['light', 'dark']
defaultValue: 'light'
maintenanceMode:
type: boolean
defaultValue: false
contactEmail:
type: string
validators:
- type: isEmailStep 2: Start ChimpBase Server
Start the server with your schema file:
# Start with your schema file and API key
npx chimpbase-server --schema ./schema.yaml --api-key my-secure-api-key
# Or with custom port
npx chimpbase-server --schema ./schema.yaml --api-key my-secure-api-key --port 4000You should see output like:
🚀 Starting ChimpBase Server...
📋 Schema: ./schema.yaml
🗄️ Database: Using environment variables
🔐 Auth: API Key enabled
Database connected and synchronized
Server running on http://localhost:3000Step 3: Use the SDK
Create a TypeScript/JavaScript file to interact with your API:
// app.ts
import { createClient } from 'chimpbase-sdk';
// Initialize the client
const client = createClient({
baseURL: 'http://localhost:3000',
apiKey: 'my-secure-api-key',
});
async function main() {
try {
// Create a new post
const post = await client.from('posts').create({
title: 'My First Post',
content: 'This is the content of my first post!',
status: 'published',
tags: ['getting-started', 'tutorial'],
});
console.log('Created post:', post);
// Get all published posts
const publishedPosts = await client
.from('posts')
.filter({ status_eq: 'published' })
.orderBy('publishedAt', 'DESC')
.find();
console.log('Published posts:', publishedPosts);
// Update site settings
await client.single('site-settings').update({
siteName: 'My Awesome Website',
theme: 'dark',
contactEmail: '[email protected]',
});
// Get current settings
const settings = await client.single('site-settings').get();
console.log('Site settings:', settings);
} catch (error) {
console.error('Error:', error);
}
}
main();Step 4: Run Your Application
# For TypeScript (with ts-node)
npx ts-node app.ts
# For JavaScript
node app.jsHow It Works
This SDK provides a TypeScript client for ChimpBase Server APIs. ChimpBase Server transforms YAML schema definitions into complete RESTful APIs with automatic persistence, validation, and documentation. The SDK gives you a fluent, type-safe interface to interact with these auto-generated APIs.
Workflow:
- Define your data structure in a YAML schema file
- Start ChimpBase Server with your schema
- Use this SDK to interact with the generated API endpoints
- Get automatic CRUD operations, validation, and TypeScript support
Common Issues
"Schema path is required" Error
If you see this error when starting ChimpBase Server:
❌ Failed to start BaaS server: Schema path is required. Please provide a schema file using --schema or -s option.Make sure to provide a schema file:
npx chimpbase-server --schema ./schema.yaml --api-key your-api-keySchema File Format
Your schema.yaml must include:
- A
versionfield - At least one
collectionsorsinglesdefinition - Valid field types and validators
See the example schema above for proper formatting.
Quick Start
Once you have ChimpBase Server running with a schema:
import { createClient } from 'chimpbase-sdk';
// Initialize client
const client = createClient({
apiKey: 'your-api-key',
baseURL: 'http://localhost:3000',
});
// Query collections with fluent interface
const posts = await client
.from('posts')
.filter({ status_eq: 'published' })
.orderBy('created_at', 'DESC')
.limit(10)
.find();
// Work with singles (unique records)
const settings = await client.single('site-settings').get();
await client.single('site-settings').patch({ theme: 'dark' });Core Concepts
Collections
Collections are lists of records with the same schema (like database tables):
// Create a new post
const post = await baas.from('posts').create({
title: 'Hello World',
content: 'This is my first post...',
status: 'published',
tags: ['intro', 'welcome'],
});
// Get a post by ID
const foundPost = await baas.from('posts').findOneById(post.id);
// Update a post (partial update)
await baas.from('posts').patch(post.id, {
status: 'archived',
updatedAt: new Date().toISOString(),
});
// Delete a post
await baas.from('posts').delete(post.id);
// List posts with pagination
const { data, total, page } = await baas.from('posts').page(1).limit(20).find();Singles
Singles are unique records (settings, configurations, etc.):
// Get current settings
const settings = await baas.single('site-settings').get();
// Update settings (creates if doesn't exist)
await baas.single('site-settings').update({
siteName: 'My Website',
maintenanceMode: false,
contactEmail: '[email protected]',
});
// Partial update
await baas.single('site-settings').patch({
maintenanceMode: true,
});Advanced Filtering
The SDK provides a fluent interface for complex queries:
// Multiple filter methods
const products = await baas
.from('products')
.filter({ category_eq: 'electronics' })
.between('price', 100, 1000)
.gte('rating', 4.0)
.like('name', '%phone%')
.in('brand', ['Apple', 'Samsung'])
.isNotNull('description')
.find();
// Filter with complex conditions
const recentPosts = await baas
.from('posts')
.filter({
status_eq: 'published',
views_gte: 1000,
})
.gte('publishedAt', '2024-01-01')
.orderBy('publishedAt', 'DESC')
.limit(50)
.find();Available Filter Operators
| Operator | Method | Description | Example |
| -------------- | ------------- | --------------------- | --------------------------------- |
| _eq | filter() | Equals | filter({ status_eq: 'active' }) |
| _ne | neq() | Not equals | neq('status', 'deleted') |
| _gt | gt() | Greater than | gt('price', 100) |
| _gte | gte() | Greater than or equal | gte('rating', 4.0) |
| _lt | lt() | Less than | lt('age', 18) |
| _lte | lte() | Less than or equal | lte('stock', 10) |
| _like | like() | SQL LIKE pattern | like('name', '%test%') |
| _in | in() | In array | in('category', ['A', 'B']) |
| _nin | notIn() | Not in array | notIn('status', ['deleted']) |
| _between | between() | Between values | between('price', 10, 100) |
| _is_null | isNull() | Is null | isNull('deletedAt') |
| _is_not_null | isNotNull() | Is not null | isNotNull('email') |
TypeScript Support
Full type safety with generic interfaces:
interface Post {
id: string;
title: string;
content: string;
status: 'draft' | 'published' | 'archived';
publishedAt?: string;
tags: string[];
}
interface User {
id: string;
name: string;
email: string;
isActive: boolean;
}
// Typed queries
const posts = await baas.from<Post>('posts').find();
// posts is typed as PaginatedResponse<Post>
const user = await baas.from<User>('users').findOneById('123');
// user is typed as User
// Type-safe creation
const newPost = await baas.from<Post>('posts').create({
title: 'New Post', // ✅ Required field
content: 'Content...', // ✅ Required field
status: 'draft', // ✅ Valid enum value
tags: ['typescript'], // ✅ Correct type
// publishedAt: ..., // ✅ Optional field
});Authentication
API Key Authentication
const baas = createClient({
apiKey: process.env.BAAS_API_KEY,
baseURL: process.env.BAAS_URL,
});JWT Authentication (OAuth2 Client Credentials)
const baas = createClient({
jwtClientId: process.env.JWT_CLIENT_ID,
jwtClientSecret: process.env.JWT_CLIENT_SECRET,
jwtTokenUrl: process.env.JWT_TOKEN_URL,
baseURL: process.env.BAAS_URL,
});Custom Token Refresh
const baas = createClient({
accessToken: getStoredToken(),
onTokenRefresh: async () => {
const newToken = await refreshTokenFromAPI();
storeToken(newToken);
return newToken;
},
baseURL: process.env.BAAS_URL,
});Schema Management
The SDK includes powerful schema management capabilities:
// Get schema information
const postSchema = await baas.schema('posts');
console.log(postSchema.fields);
// List all available schemas
const schemas = await baas.schemas();
console.log(schemas.collections); // All collection schemas
console.log(schemas.singles); // All single schemas
// Schema validation
const manager = baas.getSchemaManager();
const validator = baas.getSchemaValidator();
const result = validator.validate(userData, userSchema);
if (!result.valid) {
console.log('Validation errors:', result.errors);
}Error Handling
Comprehensive error handling with structured responses:
import { BaasApiError } from 'chimpbase-sdk';
try {
const post = await baas.from('posts').findOneById('invalid-id');
} catch (error) {
if (error instanceof BaasApiError) {
console.error(`API Error ${error.status}: ${error.message}`);
console.error('Details:', error.errorBody);
// Handle specific error types
switch (error.status) {
case 404:
console.log('Resource not found');
break;
case 400:
console.log('Validation failed:', error.errorBody.errors);
break;
case 401:
console.log('Authentication required');
break;
default:
console.log('Unexpected error:', error.message);
}
} else {
console.error('Network or other error:', error);
}
}Advanced Usage
Field Selection
// Select only specific fields
const posts = await baas
.from('posts')
.select(['id', 'title', 'publishedAt'])
.find();Pagination
// Manual pagination
const page1 = await baas.from('posts').page(1).limit(10).find();
const page2 = await baas.from('posts').page(2).limit(10).find();
// Get total count
console.log(`Total posts: ${page1.total}`);
console.log(`Total pages: ${Math.ceil(page1.total / 10)}`);Complex Queries
// Combine multiple conditions
const results = await baas
.from('products')
.filter({
category_eq: 'electronics',
inStock_eq: true,
})
.between('price', 50, 500)
.gte('rating', 4.0)
.like('name', '%wireless%')
.orderBy('popularity', 'DESC')
.orderBy('price', 'ASC') // Secondary sort
.page(1)
.limit(20)
.find();Configuration Options
const baas = createClient({
// Authentication
apiKey?: string;
accessToken?: string;
jwtClientId?: string;
jwtClientSecret?: string;
jwtTokenUrl?: string;
onTokenRefresh?: () => Promise<string>;
// Connection
baseURL?: string; // Default: '/'
timeout?: number; // Default: 30000ms
// Schema management
schemaOptions?: {
persistence?: SchemaPersistenceAdapter;
validateOnSave?: boolean;
autoGenerateTypes?: boolean;
};
});Testing
# Install dependencies
npm install
# Run unit tests
npm test
# Run integration tests (requires running API)
npm run test:integration
# Run tests in watch mode
npm run test:watch
# Generate coverage report
npm run test:coverage
# Type checking
npm run typecheckAPI Compatibility
✅ Fully Supported
- Complete CRUD operations for collections and singles
- Authentication (API Key & JWT with auto-refresh)
- Pagination and field selection
- Schema discovery and validation
- Structured error handling
- TypeScript support with full type safety
⚠️ Partially Supported
- Filtering (some operators pending API implementation)
- Sorting (basic support, advanced sorting planned)
📋 Planned Features
- Relations and eager loading (
?include=parameter) - Real-time subscriptions via WebSocket
- Advanced caching strategies
- Offline support with sync capabilities
Development
# Install dependencies
npm install
# Build the SDK
npm run build
# Development build (watch mode)
npm run dev
# Run linting
npm run lint
# Type checking
npm run typecheckExamples
Check out the comprehensive examples demonstrating ChimpBase SDK across different JavaScript runtimes:
🚀 Todo Applications
Complete command-line todo applications showcasing all SDK features:
- Node.js Todo App - Traditional & reliable with Commander.js and Inquirer
- Bun Todo App - High-performance with native TypeScript support
- Deno Todo App - Secure by default with built-in tools
Each example includes:
- ✅ Complete CRUD operations
- 🎯 Priority management and due dates
- 🏷️ Tag-based organization
- 📊 Statistics and search functionality
- 🎨 Rich CLI interface
- 📖 Comprehensive documentation
Quick Start:
# Choose your runtime
cd examples/nodejs/todo && npm install && npm run app init
cd examples/bun/todo && bun install && bun run app init
cd examples/deno/todo && deno task app init🧪 Integration Tests
For additional usage patterns, see the Integration Tests directory.
Contributing
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Add tests for new functionality
- Ensure all tests pass (
npm test) - Run type checking (
npm run typecheck) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
MIT - See LICENSE for details.
Made with ❤️ by the Catalisa team
