syncflow-engine
Version:
A flexible and robust data synchronization library for JavaScript applications
221 lines (171 loc) • 5.23 kB
Markdown
# SyncFlow
[](https://opensource.org/licenses/MIT)
[](https://badge.fury.io/js/syncflow)
[](https://github.com/ellerbrock/typescript-badges/)
A flexible and robust data synchronization library for JavaScript/TypeScript applications, with first-class React/Next.js support.
## Features
- 🔄 Robust synchronization engine
- 💾 Built-in memory store with customizable storage adapters
- ⚛️ React hooks and context provider
- 📱 Offline-first capabilities
- 🔍 Debug mode for development
- 📦 TypeScript support
- ⚡ Automatic retries with configurable limits
- 🎯 Event-driven architecture
## Installation
```bash
npm install syncflow
# or
yarn add syncflow
# or
pnpm add syncflow
```
## Quick Start
### Basic Usage (JavaScript/TypeScript)
```typescript
import { SyncEngine, MemorySyncStore } from 'syncflow';
const store = new MemorySyncStore();
const syncEngine = new SyncEngine(store, {
retryLimit: 3,
retryDelay: 2000,
batchSize: 5,
autoStart: true,
debug: true,
});
// Add sync operation
await store.addOperation({
type: "create",
entity: "user",
data: { name: "John Doe" },
status: "pending",
retryCount: 0,
});
// Start syncing
await syncEngine.start();
```
### React/Next.js Usage
1. Wrap your application with `SyncProvider`:
```typescript
// _app.tsx or layout.tsx
import { SyncProvider } from 'syncflow';
function App({ Component, pageProps }) {
return (
<SyncProvider
config={{
retryLimit: 3,
retryDelay: 2000,
batchSize: 5,
autoStart: true,
debug: true,
}}
>
<Component {...pageProps} />
</SyncProvider>
);
}
```
2. Use hooks in your components:
```typescript
import { useSync, useSyncOperation, useSyncListener } from 'syncflow';
function MyComponent() {
const { status } = useSync();
const { sync, isLoading } = useSyncOperation();
useSyncListener("syncComplete", () => {
console.log("Sync completed!");
});
const handleCreateUser = async () => {
await sync("create", "user", {
name: "John Doe",
email: "john@example.com",
});
};
return (
<div>
<p>Sync Status: {status}</p>
<button onClick={handleCreateUser} disabled={isLoading}>
{isLoading ? "Syncing..." : "Create User"}
</button>
</div>
);
}
```
## API Reference
### Core Types
```typescript
type SyncStatus = "idle" | "syncing" | "error" | "offline";
type SyncOperation = {
id: string;
timestamp: number;
type: "create" | "update" | "delete";
entity: string;
data: unknown;
status: "pending" | "completed" | "error";
retryCount: number;
};
type SyncConfig = {
retryLimit: number;
retryDelay: number;
batchSize: number;
autoStart?: boolean;
debug?: boolean;
};
```
### SyncEngine
The main synchronization engine that handles operations.
```typescript
class SyncEngine {
constructor(store: ISyncStore, config?: SyncConfig);
start(): Promise<void>;
stop(): Promise<void>;
sync(): Promise<void>;
getStatus(): SyncStatus;
addListener(event: SyncEventType, callback: SyncEventCallback): void;
removeListener(event: SyncEventType, callback: SyncEventCallback): void;
}
```
### React Hooks
- `useSync()`: Access sync context
- `useSyncOperation()`: Perform sync operations
- `useSyncListener(event, callback)`: Listen to sync events
## Configuration Options
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| retryLimit | number | 3 | Maximum number of retry attempts |
| retryDelay | number | 1000 | Delay between retries (ms) |
| batchSize | number | 10 | Number of operations to process at once |
| autoStart | boolean | true | Start sync engine automatically |
| debug | boolean | false | Enable debug logging |
## Events
- `syncStart`: Emitted when sync starts
- `syncComplete`: Emitted when sync completes
- `syncError`: Emitted on sync error
- `statusChange`: Emitted when sync status changes
- `operationComplete`: Emitted when an operation completes
## Custom Storage Implementation
Implement the `ISyncStore` interface to create your own storage adapter:
```typescript
interface ISyncStore {
getOperations(): Promise<SyncOperation[]>;
addOperation(operation: Omit<SyncOperation, "id" | "timestamp">): Promise<void>;
updateOperation(id: string, updates: Partial<SyncOperation>): Promise<void>;
removeOperation(id: string): Promise<void>;
}
```
## Contributing
1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request
## License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
## Author
Caio Theodoro
## Support
- Star this repo
- Create an issue
- Submit a PR
## Acknowledgments
- Inspired by offline-first architecture
- Built with TypeScript
- React hooks implementation inspired by modern React patterns