Ingen beskrivning
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

async-iterators.cjs 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. 'use strict';
  2. var wrapIdbValue = require('./wrap-idb-value.cjs');
  3. const advanceMethodProps = ['continue', 'continuePrimaryKey', 'advance'];
  4. const methodMap = {};
  5. const advanceResults = new WeakMap();
  6. const ittrProxiedCursorToOriginalProxy = new WeakMap();
  7. const cursorIteratorTraps = {
  8. get(target, prop) {
  9. if (!advanceMethodProps.includes(prop))
  10. return target[prop];
  11. let cachedFunc = methodMap[prop];
  12. if (!cachedFunc) {
  13. cachedFunc = methodMap[prop] = function (...args) {
  14. advanceResults.set(this, ittrProxiedCursorToOriginalProxy.get(this)[prop](...args));
  15. };
  16. }
  17. return cachedFunc;
  18. },
  19. };
  20. async function* iterate(...args) {
  21. // tslint:disable-next-line:no-this-assignment
  22. let cursor = this;
  23. if (!(cursor instanceof IDBCursor)) {
  24. cursor = await cursor.openCursor(...args);
  25. }
  26. if (!cursor)
  27. return;
  28. cursor = cursor;
  29. const proxiedCursor = new Proxy(cursor, cursorIteratorTraps);
  30. ittrProxiedCursorToOriginalProxy.set(proxiedCursor, cursor);
  31. // Map this double-proxy back to the original, so other cursor methods work.
  32. wrapIdbValue.reverseTransformCache.set(proxiedCursor, wrapIdbValue.unwrap(cursor));
  33. while (cursor) {
  34. yield proxiedCursor;
  35. // If one of the advancing methods was not called, call continue().
  36. cursor = await (advanceResults.get(proxiedCursor) || cursor.continue());
  37. advanceResults.delete(proxiedCursor);
  38. }
  39. }
  40. function isIteratorProp(target, prop) {
  41. return ((prop === Symbol.asyncIterator &&
  42. wrapIdbValue.instanceOfAny(target, [IDBIndex, IDBObjectStore, IDBCursor])) ||
  43. (prop === 'iterate' && wrapIdbValue.instanceOfAny(target, [IDBIndex, IDBObjectStore])));
  44. }
  45. wrapIdbValue.replaceTraps((oldTraps) => ({
  46. ...oldTraps,
  47. get(target, prop, receiver) {
  48. if (isIteratorProp(target, prop))
  49. return iterate;
  50. return oldTraps.get(target, prop, receiver);
  51. },
  52. has(target, prop) {
  53. return isIteratorProp(target, prop) || oldTraps.has(target, prop);
  54. },
  55. }));