IndexedDBStore.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. const prettierBytes = require('@transloadit/prettier-bytes')
  2. const indexedDB = typeof window !== 'undefined'
  3. && (window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.OIndexedDB || window.msIndexedDB)
  4. const isSupported = !!indexedDB
  5. const DB_NAME = 'uppy-blobs'
  6. const STORE_NAME = 'files' // maybe have a thumbnail store in the future
  7. const DEFAULT_EXPIRY = 24 * 60 * 60 * 1000 // 24 hours
  8. const DB_VERSION = 3
  9. // Set default `expires` dates on existing stored blobs.
  10. function migrateExpiration (store) {
  11. const request = store.openCursor()
  12. request.onsuccess = (event) => {
  13. const cursor = event.target.result
  14. if (!cursor) {
  15. return
  16. }
  17. const entry = cursor.value
  18. entry.expires = Date.now() + DEFAULT_EXPIRY
  19. cursor.update(entry)
  20. }
  21. }
  22. function connect (dbName) {
  23. const request = indexedDB.open(dbName, DB_VERSION)
  24. return new Promise((resolve, reject) => {
  25. request.onupgradeneeded = (event) => {
  26. const db = event.target.result
  27. const { transaction } = event.currentTarget
  28. if (event.oldVersion < 2) {
  29. // Added in v2: DB structure changed to a single shared object store
  30. const store = db.createObjectStore(STORE_NAME, { keyPath: 'id' })
  31. store.createIndex('store', 'store', { unique: false })
  32. }
  33. if (event.oldVersion < 3) {
  34. // Added in v3
  35. const store = transaction.objectStore(STORE_NAME)
  36. store.createIndex('expires', 'expires', { unique: false })
  37. migrateExpiration(store)
  38. }
  39. transaction.oncomplete = () => {
  40. resolve(db)
  41. }
  42. }
  43. request.onsuccess = (event) => {
  44. resolve(event.target.result)
  45. }
  46. request.onerror = reject
  47. })
  48. }
  49. function waitForRequest (request) {
  50. return new Promise((resolve, reject) => {
  51. request.onsuccess = (event) => {
  52. resolve(event.target.result)
  53. }
  54. request.onerror = reject
  55. })
  56. }
  57. let cleanedUp = false
  58. class IndexedDBStore {
  59. constructor (opts) {
  60. this.opts = {
  61. dbName: DB_NAME,
  62. storeName: 'default',
  63. expires: DEFAULT_EXPIRY, // 24 hours
  64. maxFileSize: 10 * 1024 * 1024, // 10 MB
  65. maxTotalSize: 300 * 1024 * 1024, // 300 MB
  66. ...opts,
  67. }
  68. this.name = this.opts.storeName
  69. const createConnection = () => {
  70. return connect(this.opts.dbName)
  71. }
  72. if (!cleanedUp) {
  73. cleanedUp = true
  74. this.ready = IndexedDBStore.cleanup()
  75. .then(createConnection, createConnection)
  76. } else {
  77. this.ready = createConnection()
  78. }
  79. }
  80. key (fileID) {
  81. return `${this.name}!${fileID}`
  82. }
  83. /**
  84. * List all file blobs currently in the store.
  85. */
  86. list () {
  87. return this.ready.then((db) => {
  88. const transaction = db.transaction([STORE_NAME], 'readonly')
  89. const store = transaction.objectStore(STORE_NAME)
  90. const request = store.index('store')
  91. .getAll(IDBKeyRange.only(this.name))
  92. return waitForRequest(request)
  93. }).then((files) => {
  94. const result = {}
  95. files.forEach((file) => {
  96. result[file.fileID] = file.data
  97. })
  98. return result
  99. })
  100. }
  101. /**
  102. * Get one file blob from the store.
  103. */
  104. get (fileID) {
  105. return this.ready.then((db) => {
  106. const transaction = db.transaction([STORE_NAME], 'readonly')
  107. const request = transaction.objectStore(STORE_NAME)
  108. .get(this.key(fileID))
  109. return waitForRequest(request)
  110. }).then((result) => ({
  111. id: result.data.fileID,
  112. data: result.data.data,
  113. }))
  114. }
  115. /**
  116. * Get the total size of all stored files.
  117. *
  118. * @private
  119. */
  120. getSize () {
  121. return this.ready.then((db) => {
  122. const transaction = db.transaction([STORE_NAME], 'readonly')
  123. const store = transaction.objectStore(STORE_NAME)
  124. const request = store.index('store')
  125. .openCursor(IDBKeyRange.only(this.name))
  126. return new Promise((resolve, reject) => {
  127. let size = 0
  128. request.onsuccess = (event) => {
  129. const cursor = event.target.result
  130. if (cursor) {
  131. size += cursor.value.data.size
  132. cursor.continue()
  133. } else {
  134. resolve(size)
  135. }
  136. }
  137. request.onerror = () => {
  138. reject(new Error('Could not retrieve stored blobs size'))
  139. }
  140. })
  141. })
  142. }
  143. /**
  144. * Save a file in the store.
  145. */
  146. put (file) {
  147. if (file.data.size > this.opts.maxFileSize) {
  148. return Promise.reject(new Error('File is too big to store.'))
  149. }
  150. return this.getSize().then((size) => {
  151. if (size > this.opts.maxTotalSize) {
  152. return Promise.reject(new Error('No space left'))
  153. }
  154. return this.ready
  155. }).then((db) => {
  156. const transaction = db.transaction([STORE_NAME], 'readwrite')
  157. const request = transaction.objectStore(STORE_NAME).add({
  158. id: this.key(file.id),
  159. fileID: file.id,
  160. store: this.name,
  161. expires: Date.now() + this.opts.expires,
  162. data: file.data,
  163. })
  164. return waitForRequest(request)
  165. })
  166. }
  167. /**
  168. * Delete a file blob from the store.
  169. */
  170. delete (fileID) {
  171. return this.ready.then((db) => {
  172. const transaction = db.transaction([STORE_NAME], 'readwrite')
  173. const request = transaction.objectStore(STORE_NAME)
  174. .delete(this.key(fileID))
  175. return waitForRequest(request)
  176. })
  177. }
  178. /**
  179. * Delete all stored blobs that have an expiry date that is before Date.now().
  180. * This is a static method because it deletes expired blobs from _all_ Uppy instances.
  181. */
  182. static cleanup () {
  183. return connect(DB_NAME).then((db) => {
  184. const transaction = db.transaction([STORE_NAME], 'readwrite')
  185. const store = transaction.objectStore(STORE_NAME)
  186. const request = store.index('expires')
  187. .openCursor(IDBKeyRange.upperBound(Date.now()))
  188. return new Promise((resolve, reject) => {
  189. request.onsuccess = (event) => {
  190. const cursor = event.target.result
  191. if (cursor) {
  192. const entry = cursor.value
  193. cursor.delete() // Ignoring return value … it's not terrible if this goes wrong.
  194. cursor.continue()
  195. } else {
  196. resolve(db)
  197. }
  198. }
  199. request.onerror = reject
  200. })
  201. }).then((db) => {
  202. db.close()
  203. })
  204. }
  205. }
  206. IndexedDBStore.isSupported = isSupported
  207. module.exports = IndexedDBStore