Skip to content

Instantly share code, notes, and snippets.

@HDegroote
Created August 30, 2022 07:48
Show Gist options
  • Save HDegroote/d5781a2e5fa022f1ff5fbd6b74e10786 to your computer and use it in GitHub Desktop.
Save HDegroote/d5781a2e5fa022f1ff5fbd6b74e10786 to your computer and use it in GitHub Desktop.
Illustration of 2 approaches for a createUniqueCore function
const Corestore = require("corestore")
const ram = require("random-access-memory")
async function ensureIsNonExistingCoreName (name, corestore) {
try {
await (corestore.get({ name, createIfMissing: false })).ready()
} catch (e) {
return // Error confirms it is indeed missing
}
throw new Error(`A hypercore with name '${name}' already exists in the corestore`)
}
async function createUniqueCore(name, corestore) {
await ensureIsNonExistingCoreName(name, corestore)
const core = corestore.get({ name })
await core.ready()
return core
}
async function createUniqueCoreComplex(name, corestore) {
const isUniquePromise = ensureIsNonExistingCoreName(name, corestore)
const core = corestore.get({ name })
await isUniquePromise
await core.ready()
return core
}
const corestore = new Corestore(ram)
await corestore.ready()
const name = "core1"
console.log("Simple implementation (incomplete): ")
const [core1, core2] = await Promise.all(
[createUniqueCore(name, corestore), createUniqueCore(name, corestore)]
)
console.log(core1.key, '===', core2.key) // Both are created
console.log("Complex implementation (hard to reason about): ")
await corestore.ready()
const name2 = "core3"
//Throws
const [core3, core4] = await Promise.all(
[createUniqueCoreComplex(name2, corestore), createUniqueCoreComplex(name2, corestore)]
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment