All files dbix.ts

1.04% Statements 3/289
0% Branches 0/135
0% Functions 0/67
1.15% Lines 3/262

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 4415x             5x                                                 5x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                
import { uniq, isArray, isDate, isObject } from 'lodash';
import { IDataChange } from './data-change';
import { IData, Indexes, IDB, ICursor, DBQuery, DBKeyRange, DBKeyArray, DBKeyValue, PeerstackDBOpts, IKVIndex } from './db';
 
// export type IDBQuery = string | number | Date | IDBKeyRange | IDBArrayKey | ArrayBuffer | ArrayBufferView;
export type IDBQuery = string | number | Date | IDBKeyRange | ArrayBuffer | ArrayBufferView;
 
export function convertDBQueryToIDBQuery(query: DBQuery): IDBQuery {
  if (isObject(query) && !isArray(query) && !isDate(query)) {
    const dbQuery = query as DBKeyRange;
    Iif (dbQuery.lower === null) {
      dbQuery.lower = undefined;
    }
    Iif (dbQuery.upper === null) {
      dbQuery.upper = undefined;
    }
    if (dbQuery.lower === undefined && dbQuery.upper === undefined) {
      return null;
    } else if (dbQuery.lower !== undefined && dbQuery.upper === undefined) {
      return IDBKeyRange.lowerBound(dbQuery.lower, dbQuery.lowerOpen);
    } else if (dbQuery.lower === undefined && dbQuery.upper !== undefined) {
      return IDBKeyRange.upperBound(dbQuery.upper, dbQuery.upperOpen);
    } else {
      return IDBKeyRange.bound(dbQuery.lower, dbQuery.upper, dbQuery.lowerOpen, dbQuery.upperOpen);
    }
  } else {
    // @ts-ignore
    return query as DBKeyValue | DBKeyArray;
    // return query as DBKeyValue;
  }
}
 
export async function init(
  { dbName = 'peerstack', dbVersion = 8, onUpgrade }: PeerstackDBOpts = {}
): Promise<IDB> {
  Iif (typeof indexedDB === 'undefined') {
    throw new Error('indexedDB is not currently available')
  }
 
  function createIndex(objectStore: IDBObjectStore, index: Indexes) {
    Iif (typeof index !== 'string') {
      throw new Error('only strings are supported')
    }
    let keyPath: string[] | string = index.split('-');
    Iif (keyPath.length == 1) {
      keyPath = keyPath[0];
    }
    objectStore.createIndex(index as string, keyPath, { unique: false });
  }
 
  const db: IDBDatabase = await new Promise(async (resolve, reject) => {
    const request = indexedDB.open(dbName, dbVersion);
    request.onerror = evt => reject(new Error('failed to open db: ' + String(evt)));
    request.onsuccess = evt => resolve((evt.target as any).result as IDBDatabase)
    request.onupgradeneeded = async evt => {
      const db = (evt.target as any).result as IDBDatabase;
      const oldVersion = evt.oldVersion
      const upgradeTransaction = (evt.target as any).transaction as IDBTransaction;
      Iif (oldVersion < 1) {
        const dataStore = db.createObjectStore("data", { keyPath: 'id' });
        createIndex(dataStore, 'group');
        createIndex(dataStore, 'type');
        createIndex(dataStore, 'modified');
 
        createIndex(dataStore, 'group-modified');
        createIndex(dataStore, 'type-modified');
 
        createIndex(dataStore, 'group-type-modified');
      }
      Iif (oldVersion < 2) {
        const fileStore = db.createObjectStore("files", { keyPath: 'id' });
      }
      Iif (oldVersion < 3) {
        const dataStore = upgradeTransaction.objectStore('data');
        createIndex(dataStore, 'group-type');
      }
      Iif (oldVersion < 4) {
        const dataStore = upgradeTransaction.objectStore('data');
        createIndex(dataStore, 'subject');
        createIndex(dataStore, 'group-subject');
        createIndex(dataStore, 'group-type-subject');
      }
      Iif (oldVersion < 5) {
        const dataStore = upgradeTransaction.objectStore('data');
        createIndex(dataStore, 'type-subject');
      }
      Iif (oldVersion < 6) {
        const localStore = db.createObjectStore("local", { keyPath: 'id' });
      }
      Iif (oldVersion < 7) {
        const kvIndex = db.createObjectStore("keyValueIndex", { keyPath: ['indexId', 'dataId'] });
        // @ts-ignore
        createIndex(kvIndex, 'indexId-dataValue')
        // @ts-ignore
        createIndex(kvIndex, 'indexId')
      }
      Iif (oldVersion < 8) {
        const kvIndex = db.createObjectStore("changes", { keyPath: 'id' });
        createIndex(kvIndex, 'subject');
        // @ts-ignore
        createIndex(kvIndex, 'subject-modified');
        createIndex(kvIndex, 'group-modified');
      }
      Iif (onUpgrade) await onUpgrade(evt);
    }
  });
 
  interface IKVIndexEntry {
    indexId: string
    dataId: string
    dataValue: string
  }
 
  async function deleteIndexEntries(ix: IKVIndex) {
    await new Promise((resolve, reject) => {
      const transaction = db.transaction(['keyValueIndex'], 'readwrite');
      const kvStore = transaction.objectStore('keyValueIndex');
      const cursor = kvStore.index('indexId').openCursor(ix.id);
      cursor.onerror = reject;
      cursor.onsuccess = (evt) => {
        const ixCursor: IDBCursorWithValue = (evt.target as any).result;
        if (ixCursor) {
          ixCursor.delete();
          ixCursor.continue();
        } else {
          resolve(null);
        }
      }
    });
  }
 
  async function buildIndexEntries(ix: IKVIndex) {
    await new Promise(async (resolve, reject) => {
      // const transIX = db.transaction(['keyValueIndex'], 'readwrite');
      // const kvStore = transIX.objectStore('keyValueIndex');
      const transData = db.transaction(['data'], 'readonly');
      const dataStore = transData.objectStore('data');
 
      const cursor: IDBRequest<IDBCursorWithValue> = ix.dataType
        ? dataStore.index('group-type').openCursor([ix.group, ix.dataType])
        : dataStore.index('group').openCursor(ix.group);
      cursor.onerror = reject;
      const ixInserts: Promise<any>[] = [];
      cursor.onsuccess = (evt) => {
        const ixCursor: IDBCursorWithValue = (evt.target as any).result;
        if (ixCursor) {
          const data = ixCursor.value;
          const ixEntry: IKVIndexEntry = {
            indexId: ix.id,
            dataId: data.id,
            dataValue: data[ix.dataKey],
          }
          ixInserts.push(
            dbOp('keyValueIndex', 'put', ixEntry)
          );
          ixCursor.continue();
        } else {
          Promise.all(ixInserts).then(() => resolve(null))
        }
      }
    });
  }
 
  const save = (data: IData[]): Promise<any> => new Promise(async (resolve, reject) => {
    const indexCache = {} as { [key: string]: IKVIndex[] }
    await Promise.all(uniq(data.map(d => d.group).map(async g => {
      indexCache[g] = await find([g, 'Index'], 'group-type');
    })));
    const transaction = db.transaction(['data', 'keyValueIndex'], 'readwrite');
    transaction.onerror = evt => reject(evt);
    const dataStore = transaction.objectStore('data');
    const kvStore = transaction.objectStore('keyValueIndex');
 
    for (const d of data) {
      indexCache[d.group]
        .filter(ix => !ix.dataType || ix.dataType === d.type)
        .forEach(ix => {
          const ixEntry: IKVIndexEntry = {
            indexId: ix.id,
            dataId: d.id,
            dataValue: d[ix.dataKey],
          }
          // TODO maybe delete entries with null values
          const request = kvStore.put(ixEntry)
          request.onerror = evt => reject(evt);
        });
      const request = dataStore.put(d);
      request.onerror = evt => reject(evt);
    }
    transaction.oncomplete = async evt => {
      // when saving type of 'Index', rebuild index
      for (const d of data) {
        Iif (d.type === 'Index') {
          await deleteIndexEntries(d as IKVIndex);
          await buildIndexEntries(d as IKVIndex);
        }
      }
      resolve((evt.target as any).result);
    };
  });
 
  const find = <T = IData>(query?: DBQuery, index?: Indexes | IKVIndex): Promise<T[]> => new Promise(async (resolve, reject) => {
    const transaction = db.transaction(['data', 'keyValueIndex'], 'readonly');
    transaction.onerror = evt => reject(evt);
    const dataStore = transaction.objectStore('data');
    if (isObject(index)) {
      // prefix all query values with index id
      if (!isObject(query) || isDate(query)) {
        query = [index.id, query];  // query by index and value
      } else if (isArray(query)) {
        throw new Error('querying by index values of arrays is not supported'); // TODO this might be fine (or at least possible). needs to be tested
      } else {
        Iif (query.lower) {
          query.lower = [index.id, query.lower as DBKeyValue]
        }
        Iif (query.upper) {
          query.upper = [index.id, query.upper as DBKeyValue]
        }
      }
      const ixQuery = convertDBQueryToIDBQuery(query)
      const kvStore = transaction.objectStore('keyValueIndex');
      const request = kvStore.index('indexId-dataValue').getAll(ixQuery);
      request.onerror = evt => reject(evt);
      request.onsuccess = async evt => {
        const kvResults = (evt.target as any).result as IKVIndexEntry[];
        const ids = uniq(kvResults.map(kv => kv.dataId));
        const results = await Promise.all(ids.map(id => dbOp('data', 'get', id)))
        resolve(results);
      };
    } else {
      const ixQuery = convertDBQueryToIDBQuery(query)
      let request: IDBRequest;
      if (index) {
        request = dataStore.index(index).getAll(ixQuery);
      } else {
        request = dataStore.getAll(ixQuery);
      }
      request.onerror = evt => reject(evt);
      request.onsuccess = evt => resolve((evt.target as any).result);
    }
  });
 
  const getIXDBCursor = <T extends { id: string } = IData>(query?: DBKeyRange, index?: string, direction?: IDBCursorDirection, objectStore: 'data' | 'changes' = 'data') => {
    const cursorState = {
      reject: null as (err) => any,
      next: null as () => Promise<T>
    }
 
    let ixCursor: IDBCursorWithValue = null;
    let transactionClosed = false;
    let cursorFinished = false;
    let restartingCursor = false;
    let priorValue: T = null;
    let nextValue: T = null;
    let resolveNextValue = null;
    let nPriorResults = 0;
 
    cursorState.next = () => new Promise((resolve, _reject) => {
      cursorState.reject = _reject;
      Iif (transactionClosed && !cursorFinished) {
        restartingCursor = true;
        openTransactionRequest();
      }
      if (nextValue || cursorFinished) {
        resolve(nextValue);
        nextValue = null;
        resolveNextValue = null;
        ixCursor?.continue();
      } else {
        resolveNextValue = resolve;
      }
    });
 
    function openTransactionRequest() {
      transactionClosed = false;
      const transaction = db.transaction([objectStore], 'readonly');
      transaction.onerror = evt => cursorState.reject(evt);
      transaction.onabort = evt => cursorState.reject(evt);
      transaction.oncomplete = evt => {
        if (resolveNextValue && !cursorFinished) {
          restartingCursor = true;
          openTransactionRequest(); // the transaction closed while we were waiting for a value so open a new one
        } else {
          transactionClosed = true;
        }
      }
      const dataStore = transaction.objectStore(objectStore);
      const ixQuery = convertDBQueryToIDBQuery(query);
      const request: IDBRequest = index
        ? dataStore.index(index).openCursor(ixQuery, direction)
        : dataStore.openCursor(ixQuery, direction);
      request.onerror = evt => cursorState.reject(evt);
      request.onsuccess = evt => {
        ixCursor = (evt.target as any).result;
        Iif (!ixCursor) {
          cursorFinished = true;
          if (resolveNextValue) {
            resolveNextValue(null);
          } else {
            nextValue = null;
          }
          return;
        }
 
        // TODO this can probably be simplified - priorValue should always be true unless the cursor is done in which case we shouldn't get here
        Iif (restartingCursor && priorValue) {
          restartingCursor = false
          Iif (!index) {
            ixCursor.advance(nPriorResults); // TODO this should probably be +1
            return;
          }
          Iif (index && priorValue?.id !== ixCursor?.value?.id) {
            let priorKey = index.split('-').map(key => priorValue[key]);
            Iif (priorKey.length === 1) {
              priorKey = priorKey[0];
            }
            ixCursor.continuePrimaryKey(priorKey, priorValue.id);
            return;
          }
        }
 
        // this is needed because `continuePrimaryKey` gets us to our last value but we want the value after that
        Iif (priorValue?.id === ixCursor.value?.id) {
          ixCursor.continue();
          return;
        }
 
        priorValue = ixCursor.value;
        nPriorResults++;
 
        if (resolveNextValue) {
          resolveNextValue(ixCursor.value);
          resolveNextValue = null;
          nextValue = null;
          ixCursor.continue();
        } else {
          nextValue = ixCursor.value;
        }
      }
    }
    openTransactionRequest();
 
    return cursorState;
  };
 
  const openCursor = async <T extends { id: string } = IData>(query?: DBQuery, index?: Indexes, direction?: IDBCursorDirection, objectStore: 'data' | 'changes' = 'data'): Promise<ICursor<T>> => {
    Iif (typeof index !== 'string') {
      throw new Error('custom indexes not currently supported')
    }
    Iif (!direction) {
      direction = 'next'
    }
    let queryObject: DBKeyRange;
    if (!isObject(query) || isArray(query) || isDate(query)) {
      if (direction === 'next' || direction == 'nextunique') {
        queryObject = { lower: query };
      } else {
        queryObject = { upper: query };
      }
    } else {
      queryObject = { ...query };
    }
 
    let ixCursor = getIXDBCursor<T>(queryObject, index, direction, objectStore);
 
    const cursor: ICursor<T> = {
      next: null,
      value: null,
    }
    let nextValue: Promise<T> = ixCursor.next();
    cursor.next = async () => {
      cursor.value = await nextValue;
      nextValue = ixCursor.next();
      return cursor.value;
    }
    return cursor;
  };
 
  async function deleteData(id: string) {
    const data: IData = await dbOp('data', 'get', id);
    Iif (data.type === 'Index') {
      await deleteIndexEntries(data as IKVIndex);
    }
    return dbOp('data', 'delete', id);
  }
 
  function dbOp(storeName: 'data' | 'files' | 'local' | 'keyValueIndex' | 'changes', op: 'put' | 'delete' | 'get', value) {
    return new Promise<any>((resolve, reject) => {
      const mode: IDBTransactionMode = op === 'get' ? 'readonly' : 'readwrite';
      const transaction = db.transaction([storeName], mode);
      transaction.onerror = evt => reject(evt);
      const request = transaction.objectStore(storeName)[op](value);
      request.onerror = evt => reject(evt);
      request.onsuccess = evt => resolve((evt.target as any).result);
    });
  }
 
  const baseOps: IDB = {
    find,
    openCursor,
    save,
    get: id => dbOp('data', 'get', id),
    delete: deleteData,
    files: {
      save: file => dbOp('files', 'put', file),
      get: id => dbOp('files', 'get', id),
      delete: id => dbOp('files', 'delete', id),
    },
    local: {
      save: data => dbOp('local', 'put', data),
      get: id => dbOp('local', 'get', id),
      delete: id => dbOp('local', 'delete', id),
    },
    changes: {
      save: data => dbOp('changes', 'put', data),
      get: id => dbOp('changes', 'get', id),
      delete: id => dbOp('changes', 'delete', id),
      openCursor: (group, modified?: number, direction: IDBCursorDirection = 'next') => {
        modified ??= direction.startsWith('next') ? -Infinity : Infinity;
        const upperModified = direction.startsWith('next') ? Infinity : modified;
        const lowerModified = direction.startsWith('next') ? modified : -Infinity;
        const query: DBQuery = { lower: [group, lowerModified], upper: [group, upperModified] };
        const index: Indexes = 'group-modified';
        return openCursor<IDataChange>(query, index, direction, 'changes');
      },
      getSubjectChanges: (subject, modified?): Promise<IDataChange[]> => new Promise(async (resolve, reject) => {
        const transaction = db.transaction(['changes'], 'readonly');
        transaction.onerror = evt => reject(evt);
        const dataStore = transaction.objectStore('changes');
        let request: IDBRequest;
        const ixQuery = convertDBQueryToIDBQuery({ lower: [subject, modified || -Infinity], upper: [subject, Infinity] });
        request = dataStore.index('subject-modified').getAll(ixQuery);
        request.onerror = evt => reject(evt);
        request.onsuccess = evt => resolve((evt.target as any).result);
      })
    }
  }
 
  return baseOps;
}