Advertisement
Guest User

Untitled

a guest
Feb 22nd, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.35 KB | None | 0 0
  1. var getTableSize = function(db, dbName){
  2. return new Promise((resolve,reject) => {
  3. if (db == null) {
  4. return reject();
  5. }
  6. var size = 0;
  7. db = event.target.result;
  8. var transaction = db.transaction([dbName])
  9. .objectStore(dbName)
  10. .openCursor();
  11.  
  12. transaction.onsuccess = function(event){
  13. var cursor = event.target.result;
  14. if(cursor){
  15. var storedObject = cursor.value;
  16. var json = JSON.stringify(storedObject);
  17. size += json.length;
  18. cursor.continue();
  19. }
  20. else{
  21. resolve(size);
  22. }
  23. }.bind(this);
  24. transaction.onerror = function(err){
  25. reject("error in " + dbName + ": " + err);
  26. }
  27. });
  28. };
  29.  
  30. var getDatabaseSize = function (dbName) {
  31. var request = indexedDB.open(dbName);
  32. var db;
  33. var dbSize = 0;
  34. request.onerror = function(event) {
  35. alert("Why didn't you allow my web app to use IndexedDB?!");
  36. };
  37. request.onsuccess = function(event) {
  38. db = event.target.result;
  39. var tableNames = [ ...db.objectStoreNames ];
  40. (function(tableNames, db) {
  41. var tableSizeGetters = tableNames
  42. .reduce( (acc, tableName) => {
  43. acc.push( getTableSize(db, tableName) );
  44. return acc;
  45. }, []);
  46.  
  47. Promise.all(tableSizeGetters)
  48. .then(sizes => {
  49. console.log('--------- ' + db.name + ' -------------');
  50. tableNames.forEach( (tableName,i) => {
  51. console.log(" - " + tableName + "\t: " + humanReadableSize(sizes[i]));
  52. });
  53. var total = sizes.reduce(function(acc, val) {
  54. return acc + val;
  55. }, 0);
  56.  
  57. console.log("TOTAL: " + humanReadableSize(total))
  58. });
  59. })(tableNames, db);
  60. };
  61. };
  62.  
  63. function humanReadableSize(bytes) {
  64. var thresh = 1024;
  65. if(Math.abs(bytes) < thresh) {
  66. return bytes + ' B';
  67. }
  68. var units = ['KB','MB','GB','TB','PB','EB','ZB','YB'];
  69. var u = -1;
  70. do {
  71. bytes /= thresh;
  72. ++u;
  73. } while(Math.abs(bytes) >= thresh && u < units.length - 1);
  74. return bytes.toFixed(1)+' '+units[u];
  75. }
  76.  
  77. var printIndexDBSizes = function() {
  78. indexedDB.webkitGetDatabaseNames().onsuccess = function (e) {
  79. var databaseNames = e.target.result;
  80. var dbName;
  81. for(var i=0; i < databaseNames.length; i++) {
  82. dbName = databaseNames.item(i);
  83. getDatabaseSize(dbName);
  84. };
  85. };
  86. }
  87.  
  88. //usage
  89. printIndexDBSizes();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement