value.any.js (2664B)
1 // META: global=window,worker 2 // META: title=IndexedDB: keys and values 3 // META: script=resources/support.js 4 // @author Odin Hørthe Omdal <mailto:odinho@opera.com> 5 'use strict'; 6 7 8 function setOnUpgradeNeeded(t, predicate, _instanceof, value) { 9 createdb(t).onupgradeneeded = t.step_func(e => { 10 const db = e.target.result; 11 const store = db.createObjectStore("store"); 12 store.add(value, 1); 13 14 e.target.onsuccess = t.step_func(e => { 15 const transaction = db.transaction("store", "readonly"); 16 const objectStore = transaction.objectStore("store"); 17 objectStore.get(1).onsuccess = t.step_func(e => { 18 if (predicate) { 19 assert_true(predicate(e.target.result), 20 "Predicate should return true for the deserialized result."); 21 } else if (_instanceof) { 22 assert_true(e.target.result instanceof _instanceof, "instanceof"); 23 } 24 t.done(); 25 }); 26 }); 27 }); 28 } 29 30 // BigInt and BigInt objects are supported in serialization, per 31 // https://github.com/whatwg/html/pull/3480 32 // This support allows them to be used as IndexedDB values. 33 34 function value_test(value, predicate, name) { 35 async_test(t => { 36 t.step(function () { 37 assert_true(predicate(value), 38 "Predicate should return true for the initial value."); 39 }); 40 41 setOnUpgradeNeeded(t, predicate, null, value); 42 }, "BigInts as values in IndexedDB - " + name); 43 } 44 45 value_test(1n, 46 x => x === 1n, 47 "primitive BigInt"); 48 value_test(Object(1n), 49 x => typeof x === 'object' && 50 x instanceof BigInt && 51 x.valueOf() === 1n, 52 "BigInt object"); 53 value_test({ val: 1n }, 54 x => x.val === 1n, 55 "primitive BigInt inside object"); 56 value_test({ val: Object(1n) }, 57 x => x.val.valueOf() === 1n && 58 x.val instanceof BigInt && 59 x.val.valueOf() === 1n, 60 "BigInt object inside object"); 61 62 // However, BigInt is not supported as an IndexedDB key; support 63 // has been proposed in the following PR, but that change has not 64 // landed at the time this patch was written 65 // https://github.com/w3c/IndexedDB/pull/231 66 67 function invalidKey(key, name) { 68 test(t => { 69 assert_throws_dom("DataError", () => indexedDB.cmp(0, key)); 70 }, "BigInts as keys in IndexedDB - " + name); 71 } 72 73 invalidKey(1n, "primitive BigInt"); 74 // Still an error even if the IndexedDB patch lands 75 invalidKey(Object(1n), "BigInt object"); 76 77 function value(value, _instanceof) { 78 async_test(t => { 79 t.step(function () { 80 assert_true(value instanceof _instanceof, "TEST ERROR, instanceof"); 81 }); 82 83 setOnUpgradeNeeded(t, null, _instanceof, value); 84 }, "Values - " + _instanceof.name); 85 } 86 87 value(new Date(), Date); 88 value(new Array(), Array);