chimpbase-server
v0.3.13
Published
The fastest way to create production-ready APIs from YAML schemas with full TypeScript support
Downloads
35
Maintainers
Readme
ChimpBase Server
The fastest way to create production-ready APIs from YAML schemas
Transform YAML schema definitions into complete RESTful APIs with automatic persistence, validation, and documentation. Built for developers who want to ship fast without sacrificing quality or type safety.
✨ Why ChimpBase?
- 📝 Schema-First - Your YAML schema defines your entire API
- 🎯 Production Ready - HTTP client with complete REST API
- ⚡ Zero Boilerplate - Define once in YAML, get everything
- 🗄️ Multi-Database - SQLite, PostgreSQL support
- 🔧 TypeScript Ready - Generate types from your schema for IntelliSense
Quick Start
1. Install ChimpBase
npm install chimpbase-server2. Define Your Schema
Create a schema.yaml file:
version: "1.0.0"
collections:
posts:
fields:
title:
type: string
required: true
content:
type: string
status:
type: string
defaultValue: "draft"
tags:
type: array
items:
type: string
singles:
site-settings:
fields:
siteName:
type: string
defaultValue: "My Site"
theme:
type: string
defaultValue: "light"3. Generate TypeScript Types
# Generate full Supabase-style types from your schema
npx chimpbase-server schema.yaml --generate-types --types-mode full --types-output ./types/api.ts
# Or generate from a running server
npx chimpbase-server --generate-from-server --host localhost --port 3000 --api-key your-key --types-output ./types/api.tsNote: Type generation temporarily starts a server on port 3000 to introspect your schema. Make sure this port is available during type generation.
4. Use with Full Type Safety
import { createClient } from 'chimpbase-server';
import type { Database } from './types/api';
// Create a type-safe HTTP client with your Database type
const client = createClient<Database>({
baseURL: 'http://localhost:3000',
apiKey: 'your-api-key'
});
// Full IntelliSense and type checking!
const posts = await client.from('posts')
.filter({ status_eq: 'published' })
.orderBy('createdAt', 'DESC')
.limit(10)
.find();
// posts.data is fully typed as Database['public']['Tables']['posts']['Row'][]
posts.data.forEach(post => {
console.log(post.title); // ✅ Full IntelliSense
console.log(post.status); // ✅ Type checking
// console.log(post.invalid); // ❌ TypeScript error!
});
// Type-safe creation
const newPost = await client.from('posts').create({
title: 'Hello ChimpBase',
content: 'Modern TypeScript client!',
status: 'published', // ✅ IDE suggests: 'draft' | 'published'
tags: ['typescript', 'chimpbase']
});
// newPost.data is typed as Database['public']['Tables']['posts']['Row']
// Singles with full type safety
const settings = await client.single('site-settings').get();
console.log(settings.data.theme); // ✅ TypeScript knows this is 'light' | 'dark'🎯 HTTP Client Interface
Connect to your ChimpBase server with a fully typed HTTP client:
// HTTP client - Connect to remote server
const client = createClient<Database>({
baseURL: 'http://localhost:3000',
apiKey: 'your-api-key' // Minimum 16 characters required
});
// Full type safety with the HTTP client!
async function getPosts(client: TypedBaasClient<Database>) {
return await client.from('posts')
.filter({ status_eq: 'published' })
.orderBy('createdAt', 'DESC')
.find();
}
// Works with full type safety!
const posts = await getPosts(client);🔥 Type Safety & IntelliSense
Automatic Type Generation
ChimpBase generates complete TypeScript types from your schema:
# Generate full Supabase-style types
npx chimpbase-server schema.yaml --generate-types --types-mode fullThis creates a Database interface with:
- Complete type definitions for all collections and singles
Tables<T>helper type for row typesTablesInsert<T>helper type for insertsTablesUpdate<T>helper type for updates- Full compatibility with Supabase patterns
Type-Safe Client Usage
import { createClient } from 'chimpbase-server';
import type { Database, Tables, TablesInsert, TablesUpdate } from './types/api';
// Create a fully typed client
const client = createClient<Database>({
baseURL: 'http://localhost:3000',
apiKey: 'your-api-key'
});
// Use helper types for cleaner code
type Post = Tables<'posts'>;
type NewPost = TablesInsert<'posts'>;
type PostUpdate = TablesUpdate<'posts'>;
// Everything is type-safe!
const post: Post = await client.from('posts').findOne('123').then(r => r.data);
const newPost: NewPost = { title: 'New', content: 'Post', status: 'draft' };
const update: PostUpdate = { status: 'published' };Note: The client API doesn't currently support generics, so you'll need to use type assertions (as shown above) to get full IntelliSense.
// Import the GENERATED types from your output file (NOT from 'chimpbase-server')
import type { Database, Tables, TablesInsert, TablesUpdate } from './types/api';
import { createClient } from 'chimpbase-server';
// Type-safe database interface (like Supabase)
type PostRow = Database['public']['Tables']['posts']['Row'];
type PostInsert = Database['public']['Tables']['posts']['Insert'];
type PostUpdate = Database['public']['Tables']['posts']['Update'];
// Or use the generated helper types
type Post = Tables<'posts'>;
type NewPost = TablesInsert<'posts'>;
type UpdatePost = TablesUpdate<'posts'>;
// Create typed wrapper for better ergonomics
async function createPost(data: TablesInsert<'posts'>): Promise<Tables<'posts'>> {
const client = createClient<Database>({ /* config */ });
// No type assertion needed - fully typed!
const result = await client.from('posts').create(data);
return result.data;
}📝 Schema Definition
Define your API structure in YAML:
# schema.yaml
version: "1.0.0"
collections:
posts:
fields:
title:
type: string
required: true
maxLength: 200
content:
type: string
required: false
status:
type: string
required: true
defaultValue: "draft"
validators:
- type: isIn
value: ["draft", "published", "archived"]
tags:
type: array
required: false
items:
type: string
users:
fields:
name:
type: string
required: true
email:
type: string
required: true
unique: true
validators:
- type: isEmail
singles:
site-settings:
fields:
siteName:
type: string
required: true
theme:
type: string
defaultValue: "light"
validators:
- type: isIn
value: ["light", "dark", "auto"]🚀 Production Features
Advanced Error Handling
import {
BaasNetworkError,
BaasValidationError,
withRetry
} from 'chimpbase-server';
try {
const posts = await withRetry(
() => client.from('posts').find(),
{ maxAttempts: 3 }
);
} catch (error) {
if (error instanceof BaasNetworkError) {
console.log('Network error:', error.message);
} else if (error instanceof BaasValidationError) {
console.log('Validation errors:', error.details);
}
}JWT Authentication with Auto-Refresh
const client = createClient<Database>({
baseURL: 'http://localhost:3000',
accessToken: 'jwt-token',
onTokenRefresh: async () => {
const response = await fetch('/auth/refresh');
const { token } = await response.json();
return token;
}
});
// Client automatically refreshes tokens when they expire
const posts = await client.from('posts').find(); // Fully typed!🔧 CLI Commands
ChimpBase provides two main CLI commands for development:
Server CLI
# Start HTTP server
npx chimpbase-server schema.yaml --port 3000
# With custom database
npx chimpbase-server schema.yaml \
--db postgres \
--db-host localhost \
--db-user myuser \
--db-password mypass \
--db-name myapp \
--api-key your-secure-api-key # Minimum 16 charactersType Generator CLI
# Generate full Supabase-style types from schema
npx chimpbase-server schema.yaml --generate-types --types-mode full
# Generate basic types (interfaces only)
npx chimpbase-server schema.yaml --generate-types --types-mode basic
# Custom output path
npx chimpbase-server schema.yaml --generate-types --types-mode full --types-output ./src/types/api.ts
# Generate from running server
npx chimpbase-server --generate-from-server --host localhost --port 3000 --api-key your-key
# Watch mode for development
npx chimpbase-server schema.yaml --generate-types --types-watchHTTP Server Mode
# Basic server start
npx chimpbase-server schema.yaml --port 3000
# With PostgreSQL
npx chimpbase-server schema.yaml \
--db postgres \
--db-host localhost \
--db-user myuser \
--db-password mypass \
--db-name myapp \
--api-key your-secure-api-key # Minimum 16 charactersYour schema becomes a REST API:
# List posts
curl "http://localhost:3000/posts"
# Create a post
curl -X POST "http://localhost:3000/posts" \
-H "Content-Type: application/json" \
-d '{"title": "My Post", "status": "published"}'
# Get site settings
curl "http://localhost:3000/site-settings"🗄️ Database Support
SQLite
Perfect for development, testing, and small to medium applications.
PostgreSQL (Default)
Production-ready with advanced features, connection pooling, and transactions. PostgreSQL is the default database when environment variables are configured.
MySQL (Coming Soon)
Enterprise database support.
📖 Documentation
- Getting Started - Installation and first steps
- Client Guide - Master the unified client API
- Schema Guide - Design your data structure
- Validation Guide - Data validation and error handling
- Configuration - Environment variables and deployment
- HTTP Server Guide - REST API and production deployment
- TypeScript Guide - Full type safety setup
- Examples - Real-world usage patterns
🎯 Use Cases
Serverless Functions
// AWS Lambda / Vercel Function
import type { Database } from './types/api';
export default async function handler(req, res) {
const client = createClient<Database>({
baseURL: process.env.CHIMPBASE_API_URL,
apiKey: process.env.CHIMPBASE_API_KEY
});
const posts = await client.from('posts').find();
res.json(posts.data); // Fully typed response!
}Testing
describe('My API Tests', () => {
let client: TypedBaasClient<Database>;
beforeEach(async () => {
// Connect to test server
client = createClient<Database>({
baseURL: 'http://localhost:3001',
apiKey: 'test-api-key'
});
});
it('creates posts', async () => {
const result = await client.from('posts').create({
title: 'Test Post',
status: 'draft' // Type-safe!
});
expect(result.data.title).toBe('Test Post');
});
});🧪 Testing
ChimpBase is thoroughly tested with 330+ tests covering:
- Unit Tests (313) - Core functionality
- Integration Tests (17) - Full API workflows
- TestContainers - Isolated PostgreSQL testing
npm test # All tests
npm run test:unit # Unit tests only
npm run test:integration # Integration tests🤝 Community
- GitHub Issues - Report bugs or request features
- Discussions - Community Q&A
- Examples - Real-world implementation patterns
📄 License
MIT © ChimpBase
Ready to build something amazing? Get started in 2 minutes →
