UNPKG

@powersync/react-native

Version:

PowerSync React Native SDK. Sync Postgres, MongoDB or MySQL with SQLite in your React Native app

43 lines (42 loc) 1.31 kB
import { AbstractStreamingSyncImplementation, LockType } from '@powersync/common'; import Lock from 'async-lock'; /** * Global locks which prevent multiple instances from syncing * concurrently. */ const LOCKS = new Map(); export class ReactNativeStreamingSyncImplementation extends AbstractStreamingSyncImplementation { locks; constructor(options) { super(options); this.initLocks(); } /** * Configures global locks on sync process */ initLocks() { const { identifier } = this.options; if (identifier && LOCKS.has(identifier)) { this.locks = LOCKS.get(identifier); return; } this.locks = new Map(); this.locks.set(LockType.CRUD, new Lock()); this.locks.set(LockType.SYNC, new Lock()); if (identifier) { LOCKS.set(identifier, this.locks); } } obtainLock(lockOptions) { const lock = this.locks.get(lockOptions.type); if (!lock) { throw new Error(`Lock type ${lockOptions.type} not found`); } return lock.acquire(lockOptions.type, async () => { if (lockOptions.signal?.aborted) { throw new Error('Aborted'); } return lockOptions.callback(); }); } }