# TypeScript Usage Guide

Complete guide for using package-database with TypeScript.

## Installation

```bash
npm install nerodb
```

The package includes full TypeScript definitions out of the box!

## Basic Usage

### JOSH-Style API (Recommended)

```typescript
import {josh} from 'nerodb';

// Create a database instance
const db = josh('mydb', {
  providerOptions: {
    dataDir: './database-storage/mydb',
    autoSave: true,
    prettify: true,
  },
});

// Use it!
db.set('user', {name: 'Alice', age: 30});
const user = db.get<{name: string; age: number}>('user');
```

### Classic API

```typescript
import {Database, JSONProvider} from 'nerodb';

const provider = new JSONProvider('mydb', {
  dataDir: './database-storage',
  autoSave: true,
});

const db = new Database({
  name: 'mydb',
  provider,
});
```

## Type-Safe Operations

### Strongly Typed Gets

```typescript
interface User {
  id: number;
  name: string;
  email: string;
  role: 'admin' | 'user';
}

db.set('user:1', {
  id: 1,
  name: 'Alice',
  email: 'alice@example.com',
  role: 'admin',
});

// Type-safe retrieval
const user = db.get<User>('user:1');
if (user) {
  console.log(user.name); // TypeScript knows this is a string
  console.log(user.role); // TypeScript knows this is 'admin' | 'user'
}
```

### Typed Collections

```typescript
interface Product {
  id: string;
  name: string;
  price: number;
  inStock: boolean;
}

// Store products
db.set('product:1', {id: '1', name: 'Laptop', price: 999, inStock: true});
db.set('product:2', {id: '2', name: 'Mouse', price: 29, inStock: true});

// Type-safe query
const products = db.entries<Product>();
const inStockProducts = products.filter(([_key, product]) => product.inStock);
```

## Advanced Features

### Transactions

```typescript
await db.transaction(async (txDb) => {
  txDb.set('account:1:balance', 1000);
  txDb.set('account:2:balance', 500);
  txDb.inc('account:1:balance', -100);
  txDb.inc('account:2:balance', 100);
});
```

### Middleware

```typescript
import {Middleware, DatabaseValue} from 'nerodb';

// Create a logging middleware
const loggingMiddleware: Middleware = (operation, key, value) => {
  console.log(`[${operation}] ${key}:`, value);
  return value; // Pass through
};

// Add middleware
db.use(loggingMiddleware);

// Create a validation middleware
const validationMiddleware: Middleware = (operation, key, value) => {
  if (operation === 'set' && typeof value === 'string' && value.length === 0) {
    throw new Error('Empty strings are not allowed');
  }
  return value;
};

db.use(validationMiddleware);
```

### Query and Filter

```typescript
interface Task {
  id: number;
  title: string;
  completed: boolean;
  priority: 'high' | 'medium' | 'low';
}

// Query with filter
const highPriorityTasks = db.query<Task>((task, key) => {
  return task.priority === 'high' && !task.completed;
});

// Find single item
const firstIncomplete = db.find<Task>((task) => !task.completed);

// Map over items
const taskTitles = db.map<Task, string>((task) => task.title);
```

### Events

```typescript
// Listen to events
db.on('set', (data) => {
  console.log('Value set:', data);
});

db.on('delete', (data) => {
  console.log('Value deleted:', data);
});

db.on('clear', () => {
  console.log('Database cleared!');
});
```

### Backup and Restore

```typescript
// Create backup
const backup = db.backup();

// Save backup to file
import * as fs from 'fs';
fs.writeFileSync(
  'backup.json',
  JSON.stringify(backup, null, 2)
);

// Restore from backup
const savedBackup = JSON.parse(fs.readFileSync('backup.json', 'utf8'));
db.restore(savedBackup);
```

### Array Operations

```typescript
// Initialize array
db.set('tags', []);

// Push items
db.push('tags', 'typescript', 'javascript', 'nodejs');

// Get array
const tags = db.get<string[]>('tags');
console.log(tags); // ['typescript', 'javascript', 'nodejs']

// Remove item
db.remove('tags', 'javascript');
```

### Increment/Decrement

```typescript
// Counter
db.set('views', 0);
db.inc('views'); // 1
db.inc('views', 5); // 6
db.dec('views', 2); // 4
```

### Ensure Default Value

```typescript
// Set default if not exists
const theme = db.ensure<string>('settings.theme', 'dark');
console.log(theme); // 'dark' (or existing value)
```

## Provider Options

### JSON Provider

```typescript
import {JSONProvider} from 'nerodb';

const provider = new JSONProvider('mydb', {
  // Directory for database files
  dataDir: './database-storage/mydb',
  
  // Auto-save on changes (default: true)
  autoSave: true,
  
  // Pretty-print JSON (default: true)
  prettify: true,
  
  // Synchronous writes (default: true)
  syncOnWrite: true,
  
  // Enable encryption (default: false)
  encryption: false,
  
  // Encryption key (required if encryption is enabled)
  encryptionKey: 'your-secret-key',
});
```

### Encrypted Storage

```typescript
const secureDb = josh('secure', {
  providerOptions: {
    dataDir: './secure-storage',
    encryption: true,
    encryptionKey: process.env.DB_ENCRYPTION_KEY!,
  },
});

// Data is automatically encrypted on disk
secureDb.set('api_key', 'super-secret-key');
```

## Best Practices

### 1. Define Interfaces

```typescript
// Define your data structures
interface UserProfile {
  id: string;
  username: string;
  email: string;
  preferences: {
    theme: 'light' | 'dark';
    language: string;
  };
}

// Use them consistently
const profile = db.get<UserProfile>('profile:user123');
```

### 2. Use Nested Keys

```typescript
// Organize data with dot notation
db.set('app.config.database.host', 'localhost');
db.set('app.config.database.port', 5432);
db.set('app.config.api.timeout', 30000);
```

### 3. Handle Errors

```typescript
try {
  db.set('key', value);
} catch (error) {
  console.error('Failed to set value:', error);
}
```

### 4. Close Connections

```typescript
// Always close when done
process.on('SIGINT', () => {
  db.close();
  process.exit(0);
});
```

### 5. Use Transactions for Atomic Operations

```typescript
try {
  await db.transaction(async (txDb) => {
    // Multiple operations in one transaction
    txDb.set('user:1:balance', 1000);
    txDb.set('user:2:balance', 2000);
  });
} catch (error) {
  // All changes rolled back on error
  console.error('Transaction failed:', error);
}
```

## Code Style

This package follows the [Google TypeScript Style Guide](https://google.github.io/styleguide/tsguide.html).

## Examples

Check out the `examples/` directory for more:

- `josh-style.ts` - JOSH-style API examples
- `basic.js` - Basic usage examples
- `advanced.js` - Advanced features

## Type Definitions

All types are exported from the main module:

```typescript
import {
  Database,
  JSONProvider,
  DatabaseValue,
  DatabaseOptions,
  ProviderOptions,
  Provider,
  DatabaseEvent,
  QueryFilter,
  Middleware,
  BackupMetadata,
} from 'nerodb';
```

## Support

For issues, questions, or contributions, visit:
https://github.com/Tanmayop9/package-database
