UNPKG

@affinidi-tdk/iota-browser

Version:

Browser module to fetch data through Affinidi Iota Framework

84 lines 3.73 kB
import { toUtf8 } from '@aws-sdk/util-utf8-browser'; import { EventTypes, responseCallbackEventSchema, } from '../validators/events'; import { InternalErrorCode, throwEventError, newUnexpectedError, } from '../validators/error'; import { Logger } from '@affinidi-tdk/common/helpers'; import { presentationSubmissionSchema, verifiablePresentationSchema, } from '../validators/ssi'; export class IotaResponse { correlationId; verifiablePresentation; presentationSubmission; constructor(correlationId, verifiablePresentation, presentationSubmission) { this.correlationId = correlationId; this.verifiablePresentation = verifiablePresentation; this.presentationSubmission = presentationSubmission; } } export class ResponseHandler { channelProvider; constructor(channelProvider) { this.channelProvider = channelProvider; } getResponseHandler(event) { let responseCallback; let verifiablePresentation; let presentationSubmission; try { responseCallback = responseCallbackEventSchema.parse(event); } catch (e) { throw newUnexpectedError(InternalErrorCode.RESPONSE_CALLBACK_EVENT, event.correlationId); } try { const vpJson = JSON.parse(responseCallback.vpToken); verifiablePresentation = verifiablePresentationSchema.parse(vpJson); } catch (e) { throw newUnexpectedError(InternalErrorCode.PARSING_VERIFIABLE_PRESENTATION, event.correlationId); } try { const presentationSubmissionJson = JSON.parse(responseCallback.presentationSubmission); presentationSubmission = presentationSubmissionSchema.parse(presentationSubmissionJson); } catch (e) { throw newUnexpectedError(InternalErrorCode.PARSING_PRESENTATION_SUBMISSION, event.correlationId); } const response = new IotaResponse(responseCallback.correlationId, verifiablePresentation, presentationSubmission); return response; } async getResponse(correlationId) { const client = this.channelProvider.getClient(); return new Promise((resolve, reject) => { client.on('messageReceived', (messageReceivedEvent) => { if (messageReceivedEvent.message.payload) { const raw_data = toUtf8(messageReceivedEvent.message.payload); try { Logger.debug('Event received', raw_data); const event = JSON.parse(raw_data); if (correlationId !== event.correlationId) { return; } if (event.eventType === EventTypes.ResponseCallback) { const response = this.getResponseHandler(event); Logger.debug('Response received', response); resolve(response); } else if (event.eventType === EventTypes.Error) { Logger.debug('Error received', event); throwEventError(event); } } catch (error) { Logger.debug('Error on data request'); reject(error); } } }); }); } getResponseWithCallback(correlationId, callback) { this.getResponse(correlationId) .then((response) => callback(null, response)) .catch((error) => callback(error, null)); } } //# sourceMappingURL=response-handler.js.map