Package Exports
- @wowmysql/sdk
- @wowmysql/sdk/dist/index.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@wowmysql/sdk) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
WowMySQL TypeScript SDK
Official TypeScript/JavaScript SDK for WowMySQL - The powerful MySQL Backend-as-a-Service platform.
Features
- 🚀 Zero Configuration - Get started in seconds
- 🔒 Type-Safe - Full TypeScript support with generics
- 🎯 Fluent API - Intuitive query builder pattern
- ⚡ Lightweight - Minimal dependencies (only axios)
- 🛡️ Error Handling - Comprehensive error messages
- 📦 Tree-Shakeable - Import only what you need
Installation
# npm
npm install @wowmysql/sdk
# yarn
yarn add @wowmysql/sdk
# pnpm
pnpm add @wowmysql/sdk
Quick Start
import WowMySQLClient from '@wowmysql/sdk';
// Initialize client
const client = new WowMySQLClient({
projectUrl: 'myproject', // Your project subdomain
apiKey: 'your-api-key-here'
});
// Query data
const users = await client.table('users')
.select(['id', 'name', 'email'])
.filter({ column: 'age', operator: 'gt', value: 18 })
.order('created_at', 'desc')
.limit(10)
.get();
console.log(users.data); // Array of user records
Configuration
Basic Configuration
const client = new WowMySQLClient({
projectUrl: 'myproject', // Your project subdomain
apiKey: 'your-api-key' // Your API key from dashboard
});
Advanced Configuration
const client = new WowMySQLClient({
projectUrl: 'myproject',
apiKey: 'your-api-key',
baseDomain: 'wowmysql.com', // Custom domain (optional)
secure: true, // Use HTTPS (default: true)
timeout: 30000 // Request timeout in ms (default: 30000)
});
Using Full URL
const client = new WowMySQLClient({
projectUrl: 'https://myproject.wowmysql.com',
apiKey: 'your-api-key'
});
Usage Examples
TypeScript with Generics
interface User {
id: number;
name: string;
email: string;
age: number;
created_at: string;
}
const client = new WowMySQLClient({
projectUrl: 'myproject',
apiKey: 'your-api-key'
});
// Type-safe queries
const users = await client.table<User>('users').get();
users.data.forEach(user => {
console.log(user.name); // Type-safe!
});
Create Records
// Create a single user
const result = await client.table('users').create({
name: 'John Doe',
email: 'john@example.com',
age: 25
});
console.log(result.id); // New record ID
Read Records
// Get all records
const allUsers = await client.table('users').get();
// Get by ID
const user = await client.table('users').getById(1);
// Select specific columns
const users = await client.table('users')
.select(['id', 'name', 'email'])
.get();
// With filters
const adults = await client.table('users')
.filter({ column: 'age', operator: 'gte', value: 18 })
.get();
// Multiple filters
const result = await client.table('users')
.filter({ column: 'age', operator: 'gte', value: 18 })
.filter({ column: 'country', operator: 'eq', value: 'USA' })
.get();
// With sorting
const sorted = await client.table('users')
.order('created_at', 'desc')
.get();
// With pagination
const page1 = await client.table('users')
.limit(10)
.offset(0)
.get();
// Get first record
const firstUser = await client.table('users')
.filter({ column: 'email', operator: 'eq', value: 'john@example.com' })
.first();
Update Records
// Update by ID
const result = await client.table('users').update(1, {
name: 'Jane Doe',
age: 26
});
console.log(result.affected_rows); // Number of rows updated
Delete Records
// Delete by ID
const result = await client.table('users').delete(1);
console.log(result.affected_rows); // Number of rows deleted
Filter Operators
// Equal
.filter({ column: 'status', operator: 'eq', value: 'active' })
// Not equal
.filter({ column: 'status', operator: 'neq', value: 'deleted' })
// Greater than
.filter({ column: 'age', operator: 'gt', value: 18 })
// Greater than or equal
.filter({ column: 'age', operator: 'gte', value: 18 })
// Less than
.filter({ column: 'price', operator: 'lt', value: 100 })
// Less than or equal
.filter({ column: 'price', operator: 'lte', value: 100 })
// Like (pattern matching)
.filter({ column: 'name', operator: 'like', value: '%John%' })
// Is null
.filter({ column: 'deleted_at', operator: 'is', value: null })
Complex Queries
// Combine multiple operations
const result = await client.table<Product>('products')
.select(['id', 'name', 'price', 'category'])
.filter({ column: 'category', operator: 'eq', value: 'Electronics' })
.filter({ column: 'price', operator: 'lt', value: 1000 })
.filter({ column: 'in_stock', operator: 'eq', value: true })
.order('price', 'asc')
.limit(20)
.offset(0)
.get();
console.log(`Found ${result.total} products`);
console.log(`Showing ${result.count} products`);
result.data.forEach(product => {
console.log(`${product.name}: $${product.price}`);
});
Raw SQL Queries
// Execute custom SQL (read-only)
const results = await client.query<User>(`
SELECT id, name, email
FROM users
WHERE age > 18
ORDER BY created_at DESC
LIMIT 10
`);
Database Metadata
// List all tables
const tables = await client.listTables();
console.log(tables); // ['users', 'posts', 'comments']
// Get table schema
const schema = await client.getTableSchema('users');
console.log(schema.columns);
console.log(schema.primary_key);
Health Check
// Check API health
const health = await client.health();
console.log(health.status); // 'ok'
Error Handling
import { WowMySQLClient, WowMySQLError } from '@wowmysql/sdk';
try {
const user = await client.table('users').getById(999);
} catch (error) {
if (error instanceof WowMySQLError) {
console.error(`Error ${error.statusCode}: ${error.message}`);
console.error(error.response); // Full error response
} else {
console.error('Unexpected error:', error);
}
}
API Reference
WowMySQLClient
Main client class for interacting with WowMySQL API.
Methods
table<T>(tableName: string): Table<T>
- Get table interfacelistTables(): Promise<string[]>
- List all tablesgetTableSchema(tableName: string): Promise<TableSchema>
- Get table schemaquery<T>(sql: string): Promise<T[]>
- Execute raw SQLhealth(): Promise<{status: string, timestamp: string}>
- Health check
Table
Fluent interface for table operations.
Methods
select(columns: string | string[]): QueryBuilder<T>
- Select columnsfilter(filter: FilterExpression): QueryBuilder<T>
- Add filterget(options?: QueryOptions): Promise<QueryResponse<T>>
- Get recordsgetById(id: string | number): Promise<T>
- Get by IDcreate(data: Partial<T>): Promise<CreateResponse>
- Create recordupdate(id: string | number, data: Partial<T>): Promise<UpdateResponse>
- Update recorddelete(id: string | number): Promise<DeleteResponse>
- Delete record
QueryBuilder
Chainable query builder.
Methods
select(columns: string | string[]): this
- Select columnsfilter(filter: FilterExpression): this
- Add filterorder(column: string, direction?: 'asc' | 'desc'): this
- Order bylimit(limit: number): this
- Limit resultsoffset(offset: number): this
- Skip recordsget(options?: QueryOptions): Promise<QueryResponse<T>>
- Execute queryfirst(): Promise<T | null>
- Get first record
Real-World Examples
Next.js App Router
// app/api/users/route.ts
import { NextResponse } from 'next/server';
import WowMySQLClient from '@wowmysql/sdk';
const client = new WowMySQLClient({
projectUrl: process.env.WOWMYSQL_PROJECT!,
apiKey: process.env.WOWMYSQL_API_KEY!
});
export async function GET(request: Request) {
try {
const { searchParams } = new URL(request.url);
const page = parseInt(searchParams.get('page') || '1');
const limit = 20;
const users = await client.table('users')
.select(['id', 'name', 'email', 'created_at'])
.order('created_at', 'desc')
.limit(limit)
.offset((page - 1) * limit)
.get();
return NextResponse.json(users);
} catch (error) {
return NextResponse.json(
{ error: 'Failed to fetch users' },
{ status: 500 }
);
}
}
export async function POST(request: Request) {
try {
const body = await request.json();
const result = await client.table('users').create(body);
return NextResponse.json(result, { status: 201 });
} catch (error) {
return NextResponse.json(
{ error: 'Failed to create user' },
{ status: 500 }
);
}
}
React Hook
// hooks/useWowMySQL.ts
import { useState, useEffect } from 'react';
import WowMySQLClient from '@wowmysql/sdk';
const client = new WowMySQLClient({
projectUrl: process.env.NEXT_PUBLIC_WOWMYSQL_PROJECT!,
apiKey: process.env.NEXT_PUBLIC_WOWMYSQL_API_KEY!
});
export function useUsers() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
async function fetchUsers() {
try {
const result = await client.table('users').get();
setUsers(result.data);
} catch (err) {
setError(err);
} finally {
setLoading(false);
}
}
fetchUsers();
}, []);
return { users, loading, error };
}
Express.js API
// server.ts
import express from 'express';
import WowMySQLClient from '@wowmysql/sdk';
const app = express();
const client = new WowMySQLClient({
projectUrl: process.env.WOWMYSQL_PROJECT!,
apiKey: process.env.WOWMYSQL_API_KEY!
});
app.use(express.json());
// Get all posts
app.get('/api/posts', async (req, res) => {
try {
const { page = 1, limit = 10 } = req.query;
const posts = await client.table('posts')
.order('created_at', 'desc')
.limit(Number(limit))
.offset((Number(page) - 1) * Number(limit))
.get();
res.json(posts);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Create post
app.post('/api/posts', async (req, res) => {
try {
const result = await client.table('posts').create(req.body);
res.status(201).json(result);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.listen(3000, () => console.log('Server running on port 3000'));
Best Practices
1. Environment Variables
Never hardcode API keys. Use environment variables:
// .env
WOWMYSQL_PROJECT=myproject
WOWMYSQL_API_KEY=your-api-key
// app.ts
import WowMySQLClient from '@wowmysql/sdk';
const client = new WowMySQLClient({
projectUrl: process.env.WOWMYSQL_PROJECT!,
apiKey: process.env.WOWMYSQL_API_KEY!
});
2. Singleton Pattern
Create a single client instance:
// lib/wowmysql.ts
import WowMySQLClient from '@wowmysql/sdk';
export const db = new WowMySQLClient({
projectUrl: process.env.WOWMYSQL_PROJECT!,
apiKey: process.env.WOWMYSQL_API_KEY!
});
// Use in other files
import { db } from './lib/wowmysql';
const users = await db.table('users').get();
3. Type Definitions
Define interfaces for your data:
// types/database.ts
export interface User {
id: number;
name: string;
email: string;
created_at: string;
}
export interface Post {
id: number;
user_id: number;
title: string;
content: string;
published_at: string | null;
}
// Use in queries
const users = await db.table<User>('users').get();
4. Error Handling
Always wrap API calls in try-catch:
import { WowMySQLError } from '@wowmysql/sdk';
async function createUser(data: any) {
try {
const result = await db.table('users').create(data);
return { success: true, data: result };
} catch (error) {
if (error instanceof WowMySQLError) {
console.error(`Database error: ${error.message}`);
return { success: false, error: error.message };
}
throw error;
}
}
FAQ
How do I get my API key?
- Go to WowMySQL Dashboard
- Select your project
- Navigate to Settings > API Keys
- Copy your API key
Can I use this in the browser?
Yes! The SDK works in both Node.js and browser environments. However, never expose your API key in client-side code for production applications. Use a backend proxy instead.
What about rate limits?
Rate limits depend on your WowMySQL plan. The SDK will throw a WowMySQLError
with status code 429 when rate limits are exceeded.
Does it support transactions?
Currently, the SDK doesn't support transactions directly. Use raw SQL queries for complex transactional operations.
How do I upgrade?
npm update @wowmysql/sdk
Support
- 📧 Email: support@wowmysql.com
- 💬 Discord: Join our community
- 📚 Documentation: docs.wowmysql.com
- 🐛 Issues: GitHub Issues
Contributing
Contributions are welcome! Please see CONTRIBUTING.md for details.
License
MIT License - see LICENSE file for details.
Changelog
See CHANGELOG.md for version history.
Made with ❤️ by the WowMySQL Team