Skip to content

Commit a13f969

Browse files
committed
feat: add storage interface + implement indexedDb
1 parent f2fbf90 commit a13f969

File tree

3 files changed

+50
-0
lines changed

3 files changed

+50
-0
lines changed

package-lock.json

Lines changed: 11 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
"@ipld/dag-pb": "^2.1.18",
2929
"@multiformats/blake2": "^1.0.11",
3030
"browser-readablestream-to-it": "^2.0.4",
31+
"idb": "^7.1.1",
3132
"ipfs-unixfs-exporter": "https://gitpkg.now.sh/filecoin-saturn/js-ipfs-unixfs/packages/ipfs-unixfs-exporter?build",
3233
"multiformats": "^12.1.1"
3334
},

src/utils/storage.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
// @ts-check
2+
3+
import { openDB } from 'idb'
4+
5+
const DEFAULT_IDB_VERSION = 1
6+
const DEFAULT_IDB_STORAGE_NAME = 'saturn-db'
7+
const DEFAULT_SATURN_STORAGE_NAME = 'saturn-client'
8+
9+
/**
10+
* @typedef {object} Storage
11+
* @property {function():boolean} check - Checks if the provided Storage is accessible
12+
* @property {function(string):Promise<any>} get - Retrieves the value associated with the key.
13+
* @property {function(string,any):Promise<void>} set - Sets a new value for the key.
14+
* @property {function(string):Promise<any>} delete - Deletes the value associated with the key.
15+
*/
16+
17+
/**
18+
* @function indexedDbStorage
19+
* @returns {Storage}
20+
*/
21+
export function indexedDbStorage () {
22+
const indexedDbExists = (typeof window !== 'undefined') && window?.indexedDB
23+
let dbPromise
24+
if (indexedDbExists) {
25+
dbPromise = openDB(DEFAULT_IDB_STORAGE_NAME, DEFAULT_IDB_VERSION, {
26+
upgrade (db) {
27+
db.createObjectStore(DEFAULT_SATURN_STORAGE_NAME)
28+
}
29+
})
30+
}
31+
32+
return {
33+
check: () => Boolean(indexedDbExists),
34+
get: async (key) => indexedDbExists && (await dbPromise).get(DEFAULT_SATURN_STORAGE_NAME, key),
35+
set: async (key, value) => indexedDbExists && (await dbPromise).put(DEFAULT_SATURN_STORAGE_NAME, value, key),
36+
delete: async (key) => indexedDbExists && (await dbPromise).delete(DEFAULT_SATURN_STORAGE_NAME, key)
37+
}
38+
}

0 commit comments

Comments
 (0)