@@ -9,10 +9,33 @@ const idb = self.indexedDB ||
9
9
self . webkitIndexedDB ||
10
10
self . msIndexedDB
11
11
12
- module . exports = function createTempRepo ( repoPath ) {
13
- repoPath = repoPath || '/ipfs-' + nanoid ( )
12
+ /**
13
+ * @param {object } options
14
+ * @param {string } [options.path]
15
+ * @param {number } [options.version]
16
+ * @param {number } [options.spec]
17
+ * @param {import('ipfs-core-types/src/config').Config } [options.config]
18
+ */
19
+ module . exports = async function createTempRepo ( options = { } ) {
20
+ options . path = options . path || `ipfs-${ nanoid ( ) } `
14
21
15
- const repo = new IPFSRepo ( repoPath )
22
+ await createDB ( options . path , ( objectStore ) => {
23
+ const encoder = new TextEncoder ( )
24
+
25
+ if ( options . version ) {
26
+ objectStore . put ( encoder . encode ( `${ options . version } ` ) , '/version' )
27
+ }
28
+
29
+ if ( options . spec ) {
30
+ objectStore . put ( encoder . encode ( `${ options . spec } ` ) , '/datastore_spec' )
31
+ }
32
+
33
+ if ( options . config ) {
34
+ objectStore . put ( encoder . encode ( JSON . stringify ( options . config ) ) , '/config' )
35
+ }
36
+ } )
37
+
38
+ const repo = new IPFSRepo ( options . path )
16
39
17
40
repo . teardown = async ( ) => {
18
41
try {
@@ -23,9 +46,50 @@ module.exports = function createTempRepo (repoPath) {
23
46
}
24
47
}
25
48
26
- idb . deleteDatabase ( repoPath )
27
- idb . deleteDatabase ( repoPath + '/blocks' )
49
+ idb . deleteDatabase ( options . path )
50
+ idb . deleteDatabase ( options . path + '/blocks' )
28
51
}
29
52
30
53
return repo
31
54
}
55
+
56
+ /**
57
+ * Allows pre-filling the root IndexedDB object store with data
58
+ *
59
+ * @param {string } path
60
+ * @param {(objectStore: IDBObjectStore) => void } fn
61
+ */
62
+ function createDB ( path , fn ) {
63
+ return new Promise ( ( resolve , reject ) => {
64
+ const request = idb . open ( path , 1 )
65
+
66
+ request . onupgradeneeded = ( ) => {
67
+ const db = request . result
68
+
69
+ db . onerror = ( ) => {
70
+ reject ( new Error ( 'Could not create database' ) )
71
+ }
72
+
73
+ db . createObjectStore ( path )
74
+ }
75
+
76
+ request . onsuccess = ( ) => {
77
+ const db = request . result
78
+
79
+ const transaction = db . transaction ( path , 'readwrite' )
80
+ transaction . onerror = ( ) => {
81
+ reject ( new Error ( 'Could not add data to database' ) )
82
+ }
83
+ transaction . oncomplete = ( ) => {
84
+ db . close ( )
85
+ resolve ( )
86
+ }
87
+
88
+ const objectStore = transaction . objectStore ( path )
89
+
90
+ fn ( objectStore )
91
+
92
+ transaction . commit ( )
93
+ }
94
+ } )
95
+ }
0 commit comments