Skip to content

Commit

Permalink
chore: unsubscribe from given subscription
Browse files Browse the repository at this point in the history
BREAKING CHANGE:  signature of unsubscribe and subscribe changed
  • Loading branch information
JGiter committed Apr 29, 2021
1 parent 068b55e commit 6984c11
Showing 1 changed file with 20 additions and 12 deletions.
32 changes: 20 additions & 12 deletions src/iam.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ export enum ENSNamespaceTypes {
* Decentralized Identity and Access Management (IAM) Type
*/
export class IAM extends IAMBase {
private _exchangeSubscription: Subscription | undefined;
private _subscriptions: Subscription[] = [];
static async isMetamaskExtensionPresent() {
const provider = (await detectEthereumProvider({ mustBeMetaMask: true })) as
| {
Expand Down Expand Up @@ -1418,26 +1418,34 @@ export class IAM extends IAMBase {
throw new CacheClientNotProvidedError();
}

async subscribeToMessages({
topic = `${this._did}.${NATS_EXCHANGE_TOPIC}`,
async subscribeTo({
subject = `${this._did}.${NATS_EXCHANGE_TOPIC}`,
messageHandler
}: {
topic?: string;
subject?: string;
messageHandler: (data: IMessage) => void;
}) {
if (!this._natsConnection) {
return;
}
this._exchangeSubscription = this._natsConnection.subscribe(topic);
for await (const msg of this._exchangeSubscription) {
const decodedMessage = this._jsonCodec?.decode(msg.data) as IMessage;
messageHandler(decodedMessage);
}
const subscription = this._natsConnection.subscribe(subject, {
callback: (err, msg) => {
if (err) {
console.error(`Nats error:${err.message}`);
return;
}
const decodedMessage = this._jsonCodec?.decode(msg.data) as IMessage;
messageHandler(decodedMessage);
}
});
this._subscriptions.push(subscription);
return subscription.getID();
}

async unsubscribeFromMessages() {
if (this._exchangeSubscription) {
this._exchangeSubscription.unsubscribe();
async unsubscribeFrom(subscriptionId: number) {
const i = this._subscriptions.findIndex((s) => s.getID() === subscriptionId);
if (i !== -1) {
this._subscriptions.splice(i, 1)[0].unsubscribe();
}
}

Expand Down

0 comments on commit 6984c11

Please sign in to comment.