Official JavaScript/TypeScript client for GitDB - GitHub-backed NoSQL database.
- 🚀 Easy to use - Familiar MongoDB-like API
- 🔗 Connection management - Automatic reconnection and health checks
- 📊 GraphQL support - Full GraphQL client with introspection
- 🔒 Type safety - Full TypeScript support with comprehensive types
- ⚡ Promise-based - Modern async/await API
- 🛡️ Error handling - Comprehensive error types and handling
- 🔧 Flexible configuration - Environment variables and custom config
npm install @gitdb/client
import GitDB from '@gitdb/client';
// Initialize client
const db = new GitDB({
token: 'ghp_your_github_token_here',
owner: 'your-username',
repo: 'your-database-repo',
host: 'localhost',
port: 7896
});
// Connect and use
await db.connect();
const users = db.collection('users');
// Insert a document
const user = await users.insert({
name: 'John Doe',
email: 'john@example.com',
age: 30
});
// Find documents
const allUsers = await users.find();
const john = await users.findOne({ name: 'John Doe' });
// Update document
await users.update(user.document.id, { age: 31 });
// Delete document
await users.delete(user.document.id);
await db.disconnect();
// Set environment variables
process.env.GITDB_TOKEN = 'ghp_your_github_token_here';
process.env.GITDB_OWNER = 'your-username';
process.env.GITDB_REPO = 'your-database-repo';
process.env.GITDB_HOST = 'localhost';
process.env.GITDB_PORT = '7896';
// Use from environment
const db = GitDB.fromEnvironment();
await db.connect();
new GitDB(config: GitDBConfig)
Config Options:
-
token
(required): GitHub personal access token -
owner
(required): GitHub username or organization -
repo
(required): GitHub repository name -
host
(optional): GitDB server host (default: 'localhost') -
port
(optional): GitDB server port (default: 7896) -
timeout
(optional): Request timeout in ms (default: 30000) -
retries
(optional): Number of retry attempts (default: 3)
// Connection management
await db.connect(): Promise<void>
await db.disconnect(): Promise<void>
db.isConnected(): boolean
await db.getStatus(): Promise<ConnectionStatus>
await db.ping(): Promise<boolean>
await db.health(): Promise<any>
// Collection management
db.collection(name: string): Collection
await db.listCollections(): Promise<string[]>
await db.createCollection(name: string): Promise<void>
await db.deleteCollection(name: string): Promise<void>
// Utility methods
await db.useCollection(name: string): Promise<Collection>
await db.insertMany(collectionName: string, documents: any[]): Promise<any[]>
await db.findMany(collectionName: string, query?: any, options?: any): Promise<any[]>
await db.updateMany(collectionName: string, query: any, update: any): Promise<any>
await db.deleteMany(collectionName: string, query: any): Promise<any>
await db.ensureConnection(): Promise<void>
await db.reconnect(): Promise<void>
// Static methods
GitDB.fromEnvironment(): GitDB
GitDB.fromConfig(config: GitDBConfig): GitDB
// Create operations
await collection.insert(document: Record<string, any>): Promise<InsertResult>
await collection.insertMany(documents: Record<string, any>[]): Promise<InsertResult[]>
// Read operations
await collection.find(query?: MongoStyleQuery, options?: QueryOptions): Promise<FindResult>
await collection.findOne(query?: MongoStyleQuery, options?: QueryOptions): Promise<Document | null>
await collection.findById(id: string): Promise<Document | null>
await collection.count(query?: MongoStyleQuery): Promise<number>
// Update operations
await collection.update(id: string, update: Record<string, any>): Promise<UpdateResult>
await collection.updateMany(query: MongoStyleQuery, update: Record<string, any>): Promise<UpdateResult>
await collection.findOneAndUpdate(query: MongoStyleQuery, update: Record<string, any>, options?: UpdateOptions): Promise<Document | null>
// Delete operations
await collection.delete(id: string): Promise<DeleteResult>
await collection.deleteMany(query: MongoStyleQuery): Promise<DeleteResult>
await collection.findOneAndDelete(query: MongoStyleQuery): Promise<Document | null>
// Utility operations
await collection.distinct(field: string, query?: MongoStyleQuery): Promise<any[]>
await collection.exists(query: MongoStyleQuery): Promise<boolean>
// Basic queries and mutations
await db.graphql.query<T>(query: string, variables?: Record<string, any>): Promise<GraphQLResult<T>>
await db.graphql.mutation<T>(mutation: string, variables?: Record<string, any>): Promise<GraphQLResult<T>>
await db.graphql.introspect(): Promise<any>
// Helper methods
await db.graphql.getCollections(): Promise<string[]>
await db.graphql.getDocuments(collection: string): Promise<any[]>
await db.graphql.createDocument(collection: string, data: Record<string, any>): Promise<any>
await db.graphql.updateDocument(collection: string, id: string, data: Record<string, any>): Promise<any>
await db.graphql.deleteDocument(collection: string, id: string): Promise<boolean>
// Find all documents
const all = await users.find();
// Find with simple filter
const admins = await users.find({ role: 'admin' });
// Find with comparison operators
const youngUsers = await users.find({ age: { $lt: 30 } });
const activeUsers = await users.find({ lastLogin: { $gte: '2024-01-01' } });
// Find with logical operators
const specificUsers = await users.find({
$or: [
{ role: 'admin' },
{ age: { $gte: 30 } }
]
});
const complexQuery = await users.find({
$and: [
{ age: { $gte: 18 } },
{ $or: [
{ role: 'admin' },
{ role: 'moderator' }
]}
]
});
// Update single document
await users.update(userId, { age: 31, updatedAt: new Date() });
// Update multiple documents
await users.updateMany(
{ role: 'user' },
{ lastLogin: new Date().toISOString() }
);
// Find and update
const updated = await users.findOneAndUpdate(
{ email: 'john@example.com' },
{ verified: true }
);
// Delete single document
await users.delete(userId);
// Delete multiple documents
await users.deleteMany({ role: 'guest' });
// Find and delete
const deleted = await users.findOneAndDelete({ email: 'john@example.com' });
// Get all collections
const collections = await db.graphql.query(`
query GetCollections {
collections
}
`);
// Get documents from a collection
const products = await db.graphql.query(`
query GetProducts {
products {
id
data
}
}
`);
// Query with variables
const userProducts = await db.graphql.query(`
query GetUserProducts($userId: String!) {
products(where: { userId: $userId }) {
id
data
}
}
`, { userId: 'user123' });
// Create document
const newProduct = await db.graphql.mutation(`
mutation CreateProduct($data: JSON!) {
createProduct(data: $data) {
id
data
}
}
`, {
data: {
name: 'Laptop',
price: 999.99,
category: 'Electronics'
}
});
// Update document
const updated = await db.graphql.mutation(`
mutation UpdateProduct($id: String!, $data: JSON!) {
updateProduct(id: $id, data: $data) {
id
data
}
}
`, {
id: 'product123',
data: { price: 899.99 }
});
// Delete document
const deleted = await db.graphql.mutation(`
mutation DeleteProduct($id: String!) {
deleteProduct(id: $id)
}
`, { id: 'product123' });
try {
const user = await users.findById('non-existent-id');
} catch (error) {
if (error instanceof GitDBQueryError) {
console.error('Query error:', error.message);
console.error('Status code:', error.statusCode);
console.error('Details:', error.details);
} else if (error instanceof GitDBConnectionError) {
console.error('Connection error:', error.message);
} else if (error instanceof GitDBValidationError) {
console.error('Validation error:', error.message);
}
}
The SDK includes comprehensive TypeScript definitions:
import GitDB, {
GitDBConfig,
Document,
Collection,
GitDBError,
GitDBConnectionError,
GitDBQueryError,
GitDBValidationError
} from '@gitdb/client';
// Type-safe configuration
const config: GitDBConfig = {
token: 'ghp_...',
owner: 'username',
repo: 'database',
host: 'localhost',
port: 7896
};
// Type-safe documents
interface User extends Document {
name: string;
email: string;
age: number;
role: 'admin' | 'user' | 'moderator';
}
const users = db.collection('users');
const user: User = await users.findById('user123');
See the examples/
directory for complete working examples:
-
basic-usage.js
- Basic CRUD operations -
graphql-usage.js
- GraphQL queries and mutations -
advanced-usage.js
- Advanced features and patterns
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests
- Submit a pull request
MIT License - see LICENSE file for details.