Greasy Fork is available in English.

Web IndexedDB Helper

浏览器数据库工具类

Tento skript by neměl být instalován přímo. Jedná se o knihovnu, kterou by měly jiné skripty využívat pomocí meta příkazu // @require https://update.greatest.deepsurf.us/scripts/473362/1237033/Web%20IndexedDB%20Helper.js

  1. // ==UserScript==
  2. // @name Web IndexedDB Helper
  3. // @namespace web-indexed-database-helper
  4. // @version 1.0.0
  5. // @description 浏览器数据库工具类
  6. // @author 如梦Nya
  7. // @license MIT
  8. // @match *://*/*
  9. // ==/UserScript==
  10.  
  11. class _WebIndexedDBHelper {
  12. constructor() {
  13. /** @type {IDBDatabase} */
  14. this.db = undefined
  15. }
  16.  
  17. /**
  18. * 打开数据库
  19. * @param {string} dbName 数据库名
  20. * @param {number | undefined} dbVersion 数据库版本
  21. * @returns {Promise<WebDB, any>}
  22. */
  23. open(dbName, dbVersion) {
  24. let self = this
  25. return new Promise(function (resolve, reject) {
  26. /** @type {IDBFactory} */
  27. const indexDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB
  28. let req = indexDB.open(dbName, dbVersion)
  29. req.onerror = reject
  30. req.onsuccess = function () {
  31. self.db = this.result
  32. resolve(self)
  33. }
  34. })
  35. }
  36.  
  37. /**
  38. * 查出一条数据
  39. * @param {string} tableName 表名
  40. * @param {string} key 键名
  41. * @returns {Promise<any, any>}
  42. */
  43. get(tableName, key) {
  44. let self = this
  45. return new Promise(function (resolve, reject) {
  46. let req = self.db.transaction([tableName]).objectStore(tableName).get(key)
  47. req.onerror = reject
  48. req.onsuccess = function () {
  49. resolve(this.result)
  50. }
  51. })
  52. }
  53.  
  54. /**
  55. * 插入、更新一条数据
  56. * @param {string} tableName 表名
  57. * @param {string} key 键名
  58. * @param {any} value 数据
  59. * @returns {Promise<IDBValidKey, any>}
  60. */
  61. put(tableName, key, value) {
  62. let self = this
  63. return new Promise(function (resolve, reject) {
  64. let req = self.db.transaction([tableName], 'readwrite').objectStore(tableName).put(value, key)
  65. req.onerror = reject
  66. req.onsuccess = function () {
  67. resolve(this.result)
  68. }
  69. })
  70. }
  71.  
  72. /**
  73. * 关闭数据库
  74. */
  75. close() {
  76. this.db.close()
  77. delete this.db
  78. }
  79. }
  80.  
  81. const WebDB = {
  82. /**
  83. * 打开数据库
  84. * @param {string} dbName 数据库名
  85. * @param {number | undefined} dbVersion 数据库版本
  86. * @returns {Promise<WebDB, any>}
  87. */
  88. open: function (dbName, dbVersion) {
  89. return new _WebIndexedDBHelper().open(dbName, dbVersion)
  90. }
  91. }