kubo-rpc-client
Version:
A client library for the Kubo RPC API
58 lines • 2.08 kB
JavaScript
const LOAD_HASHER = async (codeOrName) => Promise.reject(new Error(`No hasher found for "${codeOrName}"`));
export class Multihashes {
_hashersByName;
_hashersByCode;
_loadHasher;
constructor(options) {
// Object with current list of active hashers
this._hashersByName = {};
// Object with current list of active hashers
this._hashersByCode = {};
this._loadHasher = options.loadHasher ?? LOAD_HASHER;
// Enable all supplied hashers
for (const hasher of options.hashers) {
this.addHasher(hasher);
}
}
/**
* Add support for a multibase hasher
*/
addHasher(hasher) {
if (this._hashersByName[hasher.name] != null || this._hashersByCode[hasher.code] != null) {
throw new Error(`Resolver already exists for codec "${hasher.name}"`);
}
this._hashersByName[hasher.name] = hasher;
this._hashersByCode[hasher.code] = hasher;
}
/**
* Remove support for a multibase hasher
*/
removeHasher(hasher) {
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
delete this._hashersByName[hasher.name];
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
delete this._hashersByCode[hasher.code];
}
/**
* @param {number | string} code
*/
async getHasher(code) {
const table = typeof code === 'string' ? this._hashersByName : this._hashersByCode;
// @ts-expect-error cannot derive code type
if (table[code] != null) {
// @ts-expect-error cannot derive code type
return table[code];
}
// If not supported, attempt to dynamically load this hasher
const hasher = await this._loadHasher(code);
// @ts-expect-error cannot derive code type
if (table[code] == null) {
this.addHasher(hasher);
}
return hasher;
}
listHashers() {
return Object.values(this._hashersByName);
}
}
//# sourceMappingURL=multihashes.js.map