How to use italia-ts-commons - 10 common examples

To help you get started, we’ve selected a few italia-ts-commons examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github teamdigitale / io-functions / lib / emailnotifications_queue_handler.ts View on Github external
// as the notification object is retrieved from database (?)
    return left(
      TransientError(
        `Notification not found|notification=${notificationId}|message=${
          message.id
        }`
      )
    );
  }

  const errorOrEmailNotification = EmailNotification.decode(
    maybeEmailNotification.value
  );

  if (isLeft(errorOrEmailNotification)) {
    const error = readableReport(errorOrEmailNotification.value);
    return left(
      PermanentError(
        `Wrong format for email notification|notification=${notificationId}|message=${
          message.id
        }|${error}`
      )
    );
  }

  const emailNotification = errorOrEmailNotification.value.channels.EMAIL;

  const documentHtml = await generateDocumentHtml(
    content.subject,
    content.markdown,
    senderMetadata
  );
github teamdigitale / io-functions / lib / controllers / messages.ts View on Github external
serviceVersion: userAttributes.service.version
      })
    );

    if (isLeft(createdMessageEventOrError)) {
      winston.error(
        `CreateMessageHandler|Unable to decode CreatedMessageEvent|${
          userService.serviceId
        }|${retrievedMessage.id}|${readableReport(
          createdMessageEventOrError.value
        ).replace(/\n/g, " / ")}`
      );

      return ResponseErrorValidation(
        "Unable to decode CreatedMessageEvent",
        readableReport(createdMessageEventOrError.value)
      );
    }

    // queue the message to the created messages queue by setting
    // the message to the output binding of this function
    // tslint:disable-next-line:no-object-mutation
    context.bindings.createdMessage = createdMessageEventOrError.value;

    //
    // generate appinsights event
    //

    // track the event that a message has been created
    appInsightsClient.trackEvent({
      measurements: {
        duration: diffInMilliseconds(startRequestTime)
github teamdigitale / io-functions / lib / emailnotifications_queue_handler.ts View on Github external
winston.debug(
    `EmailNotificationsHandlerIndex|Dequeued email notification|${JSON.stringify(
      context.bindings
    )}`
  );

  // since this function gets triggered by a queued message that gets
  // deserialized from a json object, we must first check that what we
  // got is what we expect.
  const errorOrNotificationEvent = NotificationEvent.decode(
    context.bindings.notificationEvent
  );
  if (isLeft(errorOrNotificationEvent)) {
    winston.error(
      `EmailNotificationsHandler|Fatal! No valid message found in bindings.|${readableReport(
        errorOrNotificationEvent.value
      )}`
    );
    return stopProcessing;
  }
  const emailNotificationEvent = errorOrNotificationEvent.value;

  const notificationStatusUpdater = getNotificationStatusUpdater(
    notificationStatusModel,
    NotificationChannelEnum.EMAIL,
    emailNotificationEvent.message.id,
    emailNotificationEvent.notificationId
  );

  winston.debug(`useSendgridTransport:${useSendgridTransport}`);
github teamdigitale / io-functions / lib / webhook_queue_handler.ts View on Github external
// as the notification object is retrieved from database (?)
    return left(
      TransientError(
        `Notification not found|notification=${notificationId}|message=${
          message.id
        }`
      )
    );
  }

  const errorOrWebhookNotification = WebhookNotification.decode(
    maybeWebhookNotification.value
  );

  if (isLeft(errorOrWebhookNotification)) {
    const error = readableReport(errorOrWebhookNotification.value);
    return left(
      PermanentError(
        `Wrong format for webhook notification|notification=${notificationId}|message=${
          message.id
        }|${error}`
      )
    );
  }

  const webhookNotification = errorOrWebhookNotification.value.channels.WEBHOOK;

  const startWebhookCallTime = process.hrtime();

  const sendResult = await sendToWebhook(
    webhookNotification.url,
    message,
github teamdigitale / io-functions / lib / webhook_queue_handler.ts View on Github external
winston.debug(
    `WebhookNotificationsHandlerIndex|Dequeued webhook notification|${JSON.stringify(
      context.bindings
    )}`
  );

  // since this function gets triggered by a queued message that gets
  // deserialized from a json object, we must first check that what we
  // got is what we expect.
  const errorOrNotificationEvent = NotificationEvent.decode(
    context.bindings.notificationEvent
  );
  if (isLeft(errorOrNotificationEvent)) {
    winston.error(
      `WebhookNotificationsHandler|Fatal! No valid message found in bindings.|${readableReport(
        errorOrNotificationEvent.value
      )}`
    );
    return;
  }
  const webhookNotificationEvent = errorOrNotificationEvent.value;

  const notificationStatusUpdater = getNotificationStatusUpdater(
    notificationStatusModel,
    NotificationChannelEnum.WEBHOOK,
    webhookNotificationEvent.message.id,
    webhookNotificationEvent.notificationId
  );

  const serviceId = webhookNotificationEvent.message.senderServiceId;
github teamdigitale / io-functions / lib / controllers / messages.ts View on Github external
message: newMessageWithoutContent,
        senderMetadata: {
          departmentName: userAttributes.service.departmentName,
          organizationFiscalCode: userAttributes.service.organizationFiscalCode,
          organizationName: userAttributes.service.organizationName,
          serviceName: userAttributes.service.serviceName
        },
        serviceVersion: userAttributes.service.version
      })
    );

    if (isLeft(createdMessageEventOrError)) {
      winston.error(
        `CreateMessageHandler|Unable to decode CreatedMessageEvent|${
          userService.serviceId
        }|${retrievedMessage.id}|${readableReport(
          createdMessageEventOrError.value
        ).replace(/\n/g, " / ")}`
      );

      return ResponseErrorValidation(
        "Unable to decode CreatedMessageEvent",
        readableReport(createdMessageEventOrError.value)
      );
    }

    // queue the message to the created messages queue by setting
    // the message to the output binding of this function
    // tslint:disable-next-line:no-object-mutation
    context.bindings.createdMessage = createdMessageEventOrError.value;

    //
github teamdigitale / io-functions / lib / controllers / messages.ts View on Github external
const returnedMessage:
      | MessageResponseWithContent
      | MessageResponseWithoutContent = {
      message,
      notification: notificationStatuses.toUndefined(),
      // we do not return the status date-time
      status: maybeMessageStatus
        .map(messageStatus => messageStatus.status)
        // when the message has been received but a MessageStatus
        // does not exist yet, the message is considered to be
        // in the ACCEPTED state (not yet stored in the inbox)
        .getOrElse(MessageStatusValueEnum.ACCEPTED)
    };

    return ResponseSuccessJson(returnedMessage);
  };
}
github teamdigitale / io-functions / lib / controllers / debug.ts View on Github external
const getDebugHandler: GetDebug = (request, _, auth, userAttributes) => {
  return Promise.resolve(
    ResponseSuccessJson({
      auth: {
        ...auth,
        // must convert the Set to an Array
        // see https://stackoverflow.com/questions/31190885/json-stringify-a-set
        groups: Array.from(auth.groups.values())
      },
      body: request.body,
      headers: request.headers,
      params: request.params,
      user: userAttributes
    })
  );
};
github teamdigitale / io-functions / lib / controllers / profiles.ts View on Github external
return async (auth, _, userAttributes, fiscalCode) => {
    const errorOrMaybeProfile = await profileModel.findOneProfileByFiscalCode(
      fiscalCode
    );
    if (isRight(errorOrMaybeProfile)) {
      const maybeProfile = errorOrMaybeProfile.value;
      if (isSome(maybeProfile)) {
        const profile = maybeProfile.value;
        if (auth.groups.has(UserGroup.ApiFullProfileRead)) {
          // if the client is a trusted application we return the
          // extended profile
          return ResponseSuccessJson(toExtendedProfile(profile));
        } else {
          // or else, we return a limited profile
          return ResponseSuccessJson(
            toLimitedProfile(
              profile,
              isSenderAllowed(
                profile.blockedInboxOrChannels,
                userAttributes.service.serviceId
              )
            )
          );
        }
      } else {
        return ResponseErrorNotFound(
          "Profile not found",
          "The profile you requested was not found in the system."
        );
      }
    } else {
github teamdigitale / io-functions / lib / compute_visible_services.ts View on Github external
// if the service is not visible anymore
    // delete it from the visible services list
    return remove(service.serviceId, visibleServicesObj);
  } else if (
    // if the service is visible and we don't have a related
    // cached visible service yet...
    service.isVisible &&
    (isNone(maybeVisibleService) ||
      // ... or if the updated service is visible and the version
      // is greater than the stored version of the cached visible service
      service.version > maybeVisibleService.value.version)
  ) {
    // store the visible service into the object (map)
    return insert(
      service.serviceId,
      pick(
        [
          "departmentName",
          "id",
          "organizationFiscalCode",
          "organizationName",
          "serviceId",
          "serviceName",
          "version"
        ],
        service
      ),
      visibleServicesObj
    );
  }
  return visibleServicesObj;
}