@libp2p/interface-mocks
Version:
Mock implementations of several libp2p interfaces
66 lines • 1.93 kB
JavaScript
import merge from 'merge-options';
export class MockRegistrar {
topologies = new Map();
handlers = new Map();
getProtocols() {
return Array.from(this.handlers.keys()).sort();
}
async handle(protocol, handler, opts) {
const options = merge.bind({ ignoreUndefined: true })({
maxInboundStreams: 1,
maxOutboundStreams: 1
}, opts);
if (this.handlers.has(protocol)) {
throw new Error(`Handler already registered for protocol ${protocol}`);
}
this.handlers.set(protocol, {
handler,
options
});
}
async unhandle(protocol) {
this.handlers.delete(protocol);
}
getHandler(protocol) {
const handler = this.handlers.get(protocol);
if (handler == null) {
throw new Error(`No handler registered for protocol ${protocol}`);
}
return handler;
}
async register(protocol, topology) {
const id = `topology-id-${Math.random()}`;
let topologies = this.topologies.get(protocol);
if (topologies == null) {
topologies = [];
}
topologies.push({
id,
topology
});
this.topologies.set(protocol, topologies);
return id;
}
unregister(id) {
if (!Array.isArray(id)) {
id = [id];
}
id.forEach(id => this.topologies.delete(id));
}
getTopologies(protocol) {
return (this.topologies.get(protocol) ?? []).map(t => t.topology);
}
}
export function mockRegistrar() {
return new MockRegistrar();
}
export async function mockIncomingStreamEvent(protocol, conn, remotePeer) {
return {
...await conn.newStream([protocol]),
// @ts-expect-error incomplete implementation
connection: {
remotePeer
}
};
}
//# sourceMappingURL=registrar.js.map