Skip to content
Snippets Groups Projects
agentUtils.ts 2.06 KiB
Newer Older
  • Learn to ignore specific revisions
  • import {Agent, CredentialExchangeRecord, CredentialState, ProofExchangeRecord, ProofState} from "@aries-framework/core";
    
    
    export interface Notification {
      key: string;
      connection?: any;
      credentialOffer?: CredentialExchangeRecord;
      proofRequest?: ProofExchangeRecord;
    }
    
    export const getNotifications = async (agent: Agent): Promise<Notification[]> => {
      const newOffers = await agent.credentials.findAllByQuery({ state: CredentialState.OfferReceived });
      const newProofRequests = await agent.proofs.findAllByQuery({ state: ProofState.RequestReceived });
    
      const rejectedIds: string[] = [];
      // Declining the credential if connection is deleted
      for await (const offer of newOffers) {
        if (!offer.connectionId) {
          await agent.credentials.declineOffer(offer.id);
          rejectedIds.push(offer.id);
        }
      }
      // Declining the proof if connection is deleted and message doesn't have ~service decorator
      for await (const proof of newProofRequests) {
        if (!proof.connectionId) {
          await agent.proofs.declineRequest(proof.id);
          rejectedIds.push(proof.id);
        }
      }
    
      const notifications: Notification[] = [];
    
      const filteredOffers = newOffers.filter(p => !rejectedIds.some(rejId => rejId === p.id));
      for await (const offer of filteredOffers) {
        const connection = await agent.connections.getById(offer.connectionId as string);
        notifications.push({ key: offer.id, credentialOffer: offer, connection: connection });
      }
    
      const filteredProofRequests = newProofRequests.filter(p => !rejectedIds.some(rejId => rejId === p.id))
      for await (const request of filteredProofRequests) {
        const connection = await agent.connections.getById(request.connectionId as string);
        notifications.push({ key: request.id, proofRequest: request, connection: connection });
      }
    
      return notifications.sort((a, b) => {
        const aCreatedAt = a.credentialOffer?.createdAt || a.proofRequest?.createdAt as Date;
        const bCreatedAt = b.credentialOffer?.createdAt || b.proofRequest?.createdAt as Date;
        return new Date(bCreatedAt).getTime() - new Date(aCreatedAt).getTime();
      });
    };