MCPcopy
hub / github.com/gruns/ImmortalDB / ImmortalStorage

Class ImmortalStorage

src/index.js:72–185  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

70}
71
72class ImmortalStorage {
73 constructor (stores = DEFAULT_STORES) {
74 this.stores = []
75
76 // Initialize stores asynchronously. Accept both instantiated store
77 // objects and uninstantiated store classes. If the latter,
78 // implicitly instantiate instances thereof in this constructor.
79 //
80 // This constructor must accept both instantiated store objects and
81 // uninstantiated store classes because it's impossible to export
82 // ImmortalStore if it only took store objects initialized
83 // asynchronously. Like:
84 //
85 // ;(async () => {
86 // const cookieStore = await CookieStore()
87 // const ImmortalDB = new ImmortalStorage([cookieStore])
88 // export { ImmortalDB } // <----- Doesn't work.
89 // })
90 //
91 // So to export a synchronous ImmortalStorage class, datastore
92 // classes (whose definitions are synchronous) must be accepted in
93 // addition to instantiated store objects.
94 this.onReady = (async () => {
95 this.stores = (await Promise.all(
96 stores.map(async StoreClassOrInstance => {
97 if (typeof StoreClassOrInstance === 'object') { // Store instance.
98 return StoreClassOrInstance
99 } else { // Store class.
100 try {
101 return await new StoreClassOrInstance() // Instantiate instance.
102 } catch (err) {
103 // TODO(grun): Log (where?) that the <Store> constructor Promise
104 // failed.
105 return null
106 }
107 }
108 }),
109 )).filter(Boolean)
110 })()
111 }
112
113 async get (key, _default = null) {
114 await this.onReady
115
116 const prefixedKey = `${DEFAULT_KEY_PREFIX}${key}`
117
118 const values = await Promise.all(
119 this.stores.map(async store => {
120 try {
121 return await store.get(prefixedKey)
122 } catch (err) {
123 cl(err)
124 }
125 }),
126 )
127
128 const counted = Array.from(countUniques(values).entries())
129 counted.sort((a, b) => a[1] <= b[1])

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected