diff --git a/CreateMessage/__tests__/handler.test.ts b/CreateMessage/__tests__/handler.test.ts index 114e4179..69234bc0 100644 --- a/CreateMessage/__tests__/handler.test.ts +++ b/CreateMessage/__tests__/handler.test.ts @@ -10,6 +10,9 @@ import { import { none, some } from "fp-ts/lib/Option"; +import { pipe } from "fp-ts/lib/function"; +import * as E from "fp-ts/lib/Either"; + import { canDefaultAddresses, canPaymentAmount, @@ -41,7 +44,7 @@ import { anIncompleteService, anotherFiscalCode } from "../../__mocks__/mocks"; -import { initAppInsights } from "italia-ts-commons/lib/appinsights"; +import { initAppInsights } from "@pagopa/ts-commons/lib/appinsights"; import { mockOrchestratorContext } from "../../__mocks__/durable-functions"; import { ApiNewMessageWithDefaults } from "../types"; @@ -64,9 +67,9 @@ describe("canWriteMessage", () => { ), // any authorized recipient, possibly also the current one recipient // one random recipient ); - expect(response.isLeft()).toBeTruthy(); - if (response.isLeft()) { - expect(response.value.kind).toEqual( + expect(E.isLeft(response)).toBeTruthy(); + if (E.isLeft(response)) { + expect(response.left.kind).toEqual( "IResponseErrorForbiddenNotAuthorizedForProduction" ); } @@ -86,9 +89,9 @@ describe("canWriteMessage", () => { new Set(authorizedRecipients.filter(_ => _ !== recipient)), // current recipient is not authorized recipient ); - expect(response.isLeft()).toBeTruthy(); - if (response.isLeft()) { - expect(response.value.kind).toEqual( + expect(E.isLeft(response)).toBeTruthy(); + if (E.isLeft(response)) { + expect(response.left.kind).toEqual( "IResponseErrorForbiddenNotAuthorizedForRecipient" ); } @@ -108,7 +111,7 @@ describe("canWriteMessage", () => { new Set([...authorizedRecipients, recipient]), // current recipient always authorized recipient ); - expect(response.isRight()).toBeTruthy(); + expect(E.isRight(response)).toBeTruthy(); } ) ); @@ -125,7 +128,7 @@ describe("canWriteMessage", () => { authorizedRecipients, recipient ); - expect(response.isRight()).toBeTruthy(); + expect(E.isRight(response)).toBeTruthy(); } ) ); @@ -137,7 +140,7 @@ describe("canDefaultAddresses", () => { fc.assert( fc.property(newMessageWithDefaultEmailArb, m => { const response = canDefaultAddresses(m); - expect(response.isLeft()).toBeTruthy(); + expect(E.isLeft(response)).toBeTruthy(); }) ); }); @@ -150,11 +153,13 @@ describe("canPaymentAmount", () => { newMessageWithPaymentDataArb, maxAmountArb, (message, maxAmount) => { + const p = message.content.payment_data; + const response = canPaymentAmount(message.content, maxAmount); if (message.content.payment_data.amount <= maxAmount) { - expect(response.isRight()).toBeTruthy(); + expect(E.isRight(response)).toBeTruthy(); } else { - expect(response.isLeft()).toBeTruthy(); + expect(E.isLeft(response)).toBeTruthy(); } } ) @@ -188,11 +193,11 @@ describe("createMessageDocument", () => { senderServiceId ); - const response = await responseTask.run(); + const response = await responseTask(); expect(mockMessageModel.create).toHaveBeenCalledTimes(1); - expect(response.isRight()).toBeTruthy(); - expect(response.getOrElse(undefined)).toMatchObject({ + expect(E.isRight(response)).toBeTruthy(); + expect(pipe(response, E.getOrElse(undefined))).toMatchObject({ fiscalCode, id: messageId, indexedId: messageId, @@ -233,8 +238,8 @@ describe("forkOrchestrator", () => { service, newMessageWithoutContent, serviceUserEmail - ).run(); - expect(response.isRight()).toBeTruthy(); + )(); + expect(E.isRight(response)).toBeTruthy(); expect(getDfClient).toHaveBeenCalledTimes(1); expect(mockDfClient.startNew).toHaveBeenCalledTimes(1); expect(mockDfClient.startNew).toHaveBeenCalledWith( @@ -255,7 +260,9 @@ describe("forkOrchestrator", () => { serviceVersion: service.version }) ); - expect(response.getOrElse(undefined)).toEqual("orchestratorId"); + expect(pipe(response, E.getOrElse(undefined))).toEqual( + "orchestratorId" + ); } ) ); diff --git a/CreateMessage/__tests__/types.test.ts b/CreateMessage/__tests__/types.test.ts index 8916adc0..57dcd6af 100644 --- a/CreateMessage/__tests__/types.test.ts +++ b/CreateMessage/__tests__/types.test.ts @@ -1,9 +1,14 @@ import { WithinRangeString } from "@pagopa/ts-commons/lib/strings"; import * as t from "io-ts"; -import { toString } from "fp-ts/lib/function"; -import { readableReport } from "italia-ts-commons/lib/reporters"; +import { readableReport } from "@pagopa/ts-commons/lib/reporters"; import { ApiNewMessageWithContentOf } from "../types"; import { PaymentData } from "@pagopa/io-functions-commons/dist/generated/definitions/PaymentData"; +import { json } from "express"; + +import { pipe } from "fp-ts/lib/function"; +import * as E from "fp-ts/lib/Either"; + +const toString = (x: any) => JSON.stringify(x); const aMessageContent = { subject: "a".repeat(10), markdown: "a".repeat(80) }; @@ -23,19 +28,25 @@ describe("ApiNewMessageWithContentOf", () => { const codec = ApiNewMessageWithContentOf(pattern); // positive scenario: we expect a match - codec.decode(aMessageWithSuchSubject).fold( - e => fail(`Should have decoded the value: ${readableReport(e)}`), - e => { - expect(e.content.subject).toBe(aSubject); - } + pipe( + codec.decode(aMessageWithSuchSubject), + E.fold( + e => fail(`Should have decoded the value: ${readableReport(e)}`), + e => { + expect(e.content.subject).toBe(aSubject); + } + ) ); // negative scenario: we expect a no-match - codec.decode(aMessageWithDifferentSubject).fold( - _ => { - expect(true).toBe(true); - }, - e => fail(`Should have not decoded the value: ${toString(e)}`) + pipe( + codec.decode(aMessageWithDifferentSubject), + E.fold( + _ => { + expect(true).toBe(true); + }, + e => fail(`Should have not decoded the value: ${toString(e)}`) + ) ); }); @@ -67,27 +78,36 @@ describe("ApiNewMessageWithContentOf", () => { const codec = ApiNewMessageWithContentOf(pattern); // positive scenario: we expect a match - codec.decode(aMessageWithSuchPaymentData).fold( - e => fail(`Should have decoded the value: ${readableReport(e)}`), - e => { - expect(e.content.payment_data).toEqual( - expect.objectContaining(aPaymentData) - ); - } + pipe( + codec.decode(aMessageWithSuchPaymentData), + E.fold( + e => fail(`Should have decoded the value: ${readableReport(e)}`), + e => { + expect(e.content.payment_data).toEqual( + expect.objectContaining(aPaymentData) + ); + } + ) ); // negative scenario: we expect a no-match - codec.decode(aMessageWithNoPaymentData).fold( - _ => { - expect(true).toBe(true); - }, - e => fail(`Should have not decoded the value: ${toString(e)}`) + pipe( + codec.decode(aMessageWithNoPaymentData), + E.fold( + _ => { + expect(true).toBe(true); + }, + e => fail(`Should have not decoded the value: ${toString(e)}`) + ) ); - codec.decode(aMessageWithAnotherPaymentData).fold( - _ => { - expect(true).toBe(true); - }, - e => fail(`Should have not decoded the value: ${toString(e)}`) + pipe( + codec.decode(aMessageWithAnotherPaymentData), + E.fold( + _ => { + expect(true).toBe(true); + }, + e => fail(`Should have not decoded the value: ${toString(e)}`) + ) ); }); }); diff --git a/CreateMessage/index.ts b/CreateMessage/index.ts index c191b7f8..e2863651 100644 --- a/CreateMessage/index.ts +++ b/CreateMessage/index.ts @@ -14,7 +14,7 @@ import { import { secureExpressApp } from "@pagopa/io-functions-commons/dist/src/utils/express"; import { setAppContext } from "@pagopa/io-functions-commons/dist/src/utils/middlewares/context_middleware"; -import createAzureFunctionHandler from "io-functions-express/dist/src/createAzureFunctionsHandler"; +import createAzureFunctionHandler from "@pagopa/express-azure-functions/dist/src/createAzureFunctionsHandler"; import { withAppInsightsContext } from "@pagopa/io-functions-commons/dist/src/utils/application_insights"; import { cosmosdbInstance } from "../utils/cosmosdb"; diff --git a/CreateNotificationActivity/handler.ts b/CreateNotificationActivity/handler.ts index 92713802..59a1a3f6 100644 --- a/CreateNotificationActivity/handler.ts +++ b/CreateNotificationActivity/handler.ts @@ -120,6 +120,7 @@ export type CreateNotificationActivityResult = t.TypeOf< /** * Returns a function for handling createNotificationActivity */ +// eslint-disable-next-line max-lines-per-function export const getCreateNotificationActivityHandler = ( lNotificationModel: NotificationModel, lDefaultWebhookUrl: HttpsUrl, diff --git a/CreateService/__tests__/handler.test.ts b/CreateService/__tests__/handler.test.ts index 8b6144c6..c29e7b15 100644 --- a/CreateService/__tests__/handler.test.ts +++ b/CreateService/__tests__/handler.test.ts @@ -9,19 +9,19 @@ import { } from "@pagopa/io-functions-commons/dist/src/utils/middlewares/azure_api_auth"; import { IAzureUserAttributes } from "@pagopa/io-functions-commons/dist/src/utils/middlewares/azure_user_attributes"; -import { NonNegativeInteger } from "italia-ts-commons/lib/numbers"; +import { NonNegativeInteger } from "@pagopa/ts-commons/lib/numbers"; import { EmailString, NonEmptyString, OrganizationFiscalCode -} from "italia-ts-commons/lib/strings"; +} from "@pagopa/ts-commons/lib/strings"; import { MaxAllowedPaymentAmount } from "@pagopa/io-functions-commons/dist/generated/definitions/MaxAllowedPaymentAmount"; import { left, right } from "fp-ts/lib/Either"; import { ServiceScopeEnum } from "@pagopa/io-functions-commons/dist/generated/definitions/ServiceScope"; import { ServiceMetadata } from "@pagopa/io-functions-commons/dist/src/models/service"; -import * as reporters from "italia-ts-commons/lib/reporters"; +import * as reporters from "@pagopa/ts-commons/lib/reporters"; import { Subscription } from "../../generated/api-admin/Subscription"; import { UserInfo } from "../../generated/api-admin/UserInfo"; import { ServicePayload } from "../../generated/definitions/ServicePayload"; diff --git a/CreateService/index.ts b/CreateService/index.ts index 33164332..554415c0 100644 --- a/CreateService/index.ts +++ b/CreateService/index.ts @@ -9,7 +9,7 @@ import { import { secureExpressApp } from "@pagopa/io-functions-commons/dist/src/utils/express"; import { setAppContext } from "@pagopa/io-functions-commons/dist/src/utils/middlewares/context_middleware"; -import createAzureFunctionHandler from "io-functions-express/dist/src/createAzureFunctionsHandler"; +import createAzureFunctionHandler from "@pagopa/express-azure-functions/dist/src/createAzureFunctionsHandler"; import { cosmosdbInstance } from "../utils/cosmosdb"; import { apiClient } from "../clients/admin"; diff --git a/EmailNotificationActivity/__tests__/handler.test.ts b/EmailNotificationActivity/__tests__/handler.test.ts index 3810bfbf..81948e31 100644 --- a/EmailNotificationActivity/__tests__/handler.test.ts +++ b/EmailNotificationActivity/__tests__/handler.test.ts @@ -6,15 +6,17 @@ import { NonEmptyString, OrganizationFiscalCode -} from "italia-ts-commons/lib/strings"; +} from "@pagopa/ts-commons/lib/strings"; import { EmailNotificationActivityInput, getEmailNotificationActivityHandler } from "../handler"; -import { some } from "fp-ts/lib/Option"; -import { fromLeft, taskEither } from "fp-ts/lib/TaskEither"; +import { pipe } from "fp-ts/lib/function"; +import * as E from "fp-ts/lib/Either"; +import * as TE from "fp-ts/lib/TaskEither"; +import * as O from "fp-ts/lib/Option"; import { EmailAddress } from "@pagopa/io-functions-commons/dist/generated/definitions/EmailAddress"; import { MessageBodyMarkdown } from "@pagopa/io-functions-commons/dist/generated/definitions/MessageBodyMarkdown"; @@ -72,7 +74,7 @@ const aRetrievedNotification: RetrievedNotification = { }; const notificationModelMock = ({ - find: jest.fn(() => taskEither.of(some(aRetrievedNotification))) + find: jest.fn(() => TE.of(O.some(aRetrievedNotification))) } as unknown) as NotificationModel; const aNotificationId = "A_NOTIFICATION_ID" as NonEmptyString; @@ -129,7 +131,7 @@ const lMailerTransporterMock = ({} as unknown) as mail.MailerTransporter; describe("getEmailNotificationActivityHandler", () => { it("should respond with 'SUCCESS' if the mail is sent", async () => { - jest.spyOn(mail, "sendMail").mockReturnValueOnce(taskEither.of("SUCCESS")); + jest.spyOn(mail, "sendMail").mockReturnValueOnce(TE.of("SUCCESS")); const GetEmailNotificationActivityHandler = getEmailNotificationActivityHandler( lMailerTransporterMock, @@ -150,7 +152,7 @@ describe("getEmailNotificationActivityHandler", () => { jest .spyOn(mail, "sendMail") - .mockReturnValueOnce(fromLeft(new Error(errorMessage))); + .mockReturnValueOnce(TE.left(new Error(errorMessage))); const GetEmailNotificationActivityHandler = getEmailNotificationActivityHandler( lMailerTransporterMock, diff --git a/GetLimitedProfile/index.ts b/GetLimitedProfile/index.ts index f49e2b5a..4df3bb38 100644 --- a/GetLimitedProfile/index.ts +++ b/GetLimitedProfile/index.ts @@ -15,7 +15,7 @@ import { secureExpressApp } from "@pagopa/io-functions-commons/dist/src/utils/ex import { setAppContext } from "@pagopa/io-functions-commons/dist/src/utils/middlewares/context_middleware"; import cors = require("cors"); import express = require("express"); -import createAzureFunctionHandler from "io-functions-express/dist/src/createAzureFunctionsHandler"; +import createAzureFunctionHandler from "@pagopa/express-azure-functions/dist/src/createAzureFunctionsHandler"; import { initTelemetryClient } from "../utils/appinsights"; import { getConfigOrThrow } from "../utils/config"; import { cosmosdbInstance } from "../utils/cosmosdb"; diff --git a/GetLimitedProfileByPOST/index.ts b/GetLimitedProfileByPOST/index.ts index 4d3940a2..bfcde766 100644 --- a/GetLimitedProfileByPOST/index.ts +++ b/GetLimitedProfileByPOST/index.ts @@ -15,7 +15,7 @@ import { secureExpressApp } from "@pagopa/io-functions-commons/dist/src/utils/ex import { setAppContext } from "@pagopa/io-functions-commons/dist/src/utils/middlewares/context_middleware"; import cors = require("cors"); import express = require("express"); -import createAzureFunctionHandler from "io-functions-express/dist/src/createAzureFunctionsHandler"; +import createAzureFunctionHandler from "@pagopa/express-azure-functions/dist/src/createAzureFunctionsHandler"; import { initTelemetryClient } from "../utils/appinsights"; import { getConfigOrThrow } from "../utils/config"; import { cosmosdbInstance } from "../utils/cosmosdb"; diff --git a/GetMessage/__tests__/handler.test.ts b/GetMessage/__tests__/handler.test.ts index e6ad36d8..9f098a0f 100644 --- a/GetMessage/__tests__/handler.test.ts +++ b/GetMessage/__tests__/handler.test.ts @@ -12,13 +12,13 @@ import { } from "@pagopa/io-functions-commons/dist/src/utils/middlewares/azure_api_auth"; import { IAzureUserAttributes } from "@pagopa/io-functions-commons/dist/src/utils/middlewares/azure_user_attributes"; -import { NonNegativeInteger } from "italia-ts-commons/lib/numbers"; +import { NonNegativeInteger } from "@pagopa/ts-commons/lib/numbers"; import { EmailString, FiscalCode, NonEmptyString, OrganizationFiscalCode -} from "italia-ts-commons/lib/strings"; +} from "@pagopa/ts-commons/lib/strings"; import { NewMessageWithoutContent, @@ -44,7 +44,8 @@ import { NotificationChannelStatusValueEnum } from "@pagopa/io-functions-commons import { ServiceId } from "@pagopa/io-functions-commons/dist/generated/definitions/ServiceId"; import { TimeToLiveSeconds } from "@pagopa/io-functions-commons/dist/generated/definitions/TimeToLiveSeconds"; -import { fromLeft, taskEither, TaskEither } from "fp-ts/lib/TaskEither"; +import * as TE from "fp-ts/lib/TaskEither"; + import { GetMessageHandler } from "../handler"; describe("GetMessageHandler", () => { @@ -152,7 +153,7 @@ describe("GetMessageHandler", () => { ): any { return { findNotificationForMessage: jest.fn(() => - taskEither.of(some(aRetrievedNotification)) + TE.of(some(aRetrievedNotification)) ) }; } @@ -183,9 +184,7 @@ describe("GetMessageHandler", () => { }; function getNotificationStatusModelMock( - retrievedNotificationStatus: any = taskEither.of( - some(aRetrievedNotificationStatus) - ) + retrievedNotificationStatus: any = TE.of(some(aRetrievedNotificationStatus)) ): any { return { findOneNotificationStatusByNotificationChannel: jest.fn( @@ -195,21 +194,21 @@ describe("GetMessageHandler", () => { } function getMessageStatusModelMock( - s: TaskEither> = taskEither.of( + s: TE.TaskEither> = TE.of( some(aMessageStatus) ) ): any { return { findLastVersionByModelId: jest.fn().mockReturnValue(s), - upsert: jest.fn(status => fromLeft(status)) + upsert: jest.fn(status => TE.left(status)) }; } it("should respond with a message if requesting user is the sender", async () => { const mockMessageModel = { findMessageForRecipient: jest.fn(() => - taskEither.of(some(aRetrievedMessageWithoutContent)) + TE.of(some(aRetrievedMessageWithoutContent)) ), - getContentFromBlob: jest.fn(() => taskEither.of(none)) + getContentFromBlob: jest.fn(() => TE.of(none)) }; const getMessageHandler = GetMessageHandler( @@ -244,9 +243,9 @@ describe("GetMessageHandler", () => { it("should fail if any error occurs trying to retrieve the message content", async () => { const mockMessageModel = { findMessageForRecipient: jest.fn(() => - taskEither.of(some(aRetrievedMessageWithoutContent)) + TE.of(some(aRetrievedMessageWithoutContent)) ), - getContentFromBlob: jest.fn(() => fromLeft(new Error())) + getContentFromBlob: jest.fn(() => TE.left(new Error())) }; const getMessageHandler = GetMessageHandler( @@ -279,9 +278,9 @@ describe("GetMessageHandler", () => { it("should respond with a message if requesting user is a trusted application", async () => { const mockMessageModel = { findMessageForRecipient: jest.fn(() => - taskEither.of(some(aRetrievedMessageWithoutContent)) + TE.of(some(aRetrievedMessageWithoutContent)) ), - getContentFromBlob: jest.fn(() => taskEither.of(none)) + getContentFromBlob: jest.fn(() => TE.of(none)) }; const getMessageHandler = GetMessageHandler( @@ -321,8 +320,8 @@ describe("GetMessageHandler", () => { }; const mockMessageModel = { - findMessageForRecipient: jest.fn(() => taskEither.of(some(message))), - getContentFromBlob: jest.fn(() => taskEither.of(none)) + findMessageForRecipient: jest.fn(() => TE.of(some(message))), + getContentFromBlob: jest.fn(() => TE.of(none)) }; const getMessageHandler = GetMessageHandler( @@ -353,8 +352,8 @@ describe("GetMessageHandler", () => { it("should respond with not found a message doesn not exist", async () => { const mockMessageModel = { - findMessageForRecipient: jest.fn(() => taskEither.of(none)), - getContentFromBlob: jest.fn(() => taskEither.of(none)) + findMessageForRecipient: jest.fn(() => TE.of(none)), + getContentFromBlob: jest.fn(() => TE.of(none)) }; const getMessageHandler = GetMessageHandler( @@ -399,9 +398,9 @@ describe("GetMessageHandler", () => { const mockMessageModel = { findMessageForRecipient: jest.fn(() => - taskEither.of(some(aRetrievedMessageWithoutContent)) + TE.of(some(aRetrievedMessageWithoutContent)) ), - getContentFromBlob: jest.fn(() => taskEither.of(none)) + getContentFromBlob: jest.fn(() => TE.of(none)) }; const getMessageHandler = GetMessageHandler( @@ -437,15 +436,15 @@ describe("GetMessageHandler", () => { it("should fail if any error occurs trying to retrieve the message status", async () => { const mockMessageModel = { findMessageForRecipient: jest.fn(() => - taskEither.of(some(aRetrievedMessageWithoutContent)) + TE.of(some(aRetrievedMessageWithoutContent)) ), - getContentFromBlob: jest.fn(() => taskEither.of(none)) + getContentFromBlob: jest.fn(() => TE.of(none)) }; const getMessageHandler = GetMessageHandler( mockMessageModel as any, getMessageStatusModelMock( - fromLeft>({ + TE.left>({ body: "error", code: 1 }) @@ -469,9 +468,9 @@ describe("GetMessageHandler", () => { it("should fail if any error occurs trying to retrieve the notification status", async () => { const mockMessageModel = { findMessageForRecipient: jest.fn(() => - taskEither.of(some(aRetrievedMessageWithoutContent)) + TE.of(some(aRetrievedMessageWithoutContent)) ), - getContentFromBlob: jest.fn(() => taskEither.of(none)) + getContentFromBlob: jest.fn(() => TE.of(none)) }; const getMessageHandler = GetMessageHandler( @@ -479,7 +478,7 @@ describe("GetMessageHandler", () => { getMessageStatusModelMock(), { findNotificationForMessage: jest.fn(() => - fromLeft({ + TE.left({ body: "error", code: 1 }) diff --git a/GetMessage/index.ts b/GetMessage/index.ts index 4496e33a..801bc552 100644 --- a/GetMessage/index.ts +++ b/GetMessage/index.ts @@ -14,7 +14,7 @@ import { import { secureExpressApp } from "@pagopa/io-functions-commons/dist/src/utils/express"; import { setAppContext } from "@pagopa/io-functions-commons/dist/src/utils/middlewares/context_middleware"; -import createAzureFunctionHandler from "io-functions-express/dist/src/createAzureFunctionsHandler"; +import createAzureFunctionHandler from "@pagopa/express-azure-functions/dist/src/createAzureFunctionsHandler"; import { MESSAGE_STATUS_COLLECTION_NAME, diff --git a/GetService/__tests__/handler.test.ts b/GetService/__tests__/handler.test.ts index f16d2b22..0c489fd1 100644 --- a/GetService/__tests__/handler.test.ts +++ b/GetService/__tests__/handler.test.ts @@ -9,19 +9,19 @@ import { } from "@pagopa/io-functions-commons/dist/src/utils/middlewares/azure_api_auth"; import { IAzureUserAttributes } from "@pagopa/io-functions-commons/dist/src/utils/middlewares/azure_user_attributes"; -import { NonNegativeInteger } from "italia-ts-commons/lib/numbers"; +import { NonNegativeInteger } from "@pagopa/ts-commons/lib/numbers"; import { EmailString, NonEmptyString, OrganizationFiscalCode -} from "italia-ts-commons/lib/strings"; +} from "@pagopa/ts-commons/lib/strings"; import { toAuthorizedCIDRs } from "@pagopa/io-functions-commons/dist/src/models/service"; import { MaxAllowedPaymentAmount } from "@pagopa/io-functions-commons/dist/generated/definitions/MaxAllowedPaymentAmount"; import { left, right } from "fp-ts/lib/Either"; -import * as reporters from "italia-ts-commons/lib/reporters"; +import * as reporters from "@pagopa/ts-commons/lib/reporters"; import { GetServiceHandler } from "../handler"; const mockContext = { diff --git a/GetService/index.ts b/GetService/index.ts index 872972a8..259f5f35 100644 --- a/GetService/index.ts +++ b/GetService/index.ts @@ -9,7 +9,7 @@ import { import { secureExpressApp } from "@pagopa/io-functions-commons/dist/src/utils/express"; import { setAppContext } from "@pagopa/io-functions-commons/dist/src/utils/middlewares/context_middleware"; -import createAzureFunctionHandler from "io-functions-express/dist/src/createAzureFunctionsHandler"; +import createAzureFunctionHandler from "@pagopa/express-azure-functions/dist/src/createAzureFunctionsHandler"; import { cosmosdbInstance } from "../utils/cosmosdb"; import { apiClient } from "../clients/admin"; diff --git a/GetSubscriptionsFeed/index.ts b/GetSubscriptionsFeed/index.ts index 00b1f258..293580b2 100644 --- a/GetSubscriptionsFeed/index.ts +++ b/GetSubscriptionsFeed/index.ts @@ -10,7 +10,7 @@ import { } from "@pagopa/io-functions-commons/dist/src/models/service"; import { secureExpressApp } from "@pagopa/io-functions-commons/dist/src/utils/express"; import { setAppContext } from "@pagopa/io-functions-commons/dist/src/utils/middlewares/context_middleware"; -import createAzureFunctionHandler from "io-functions-express/dist/src/createAzureFunctionsHandler"; +import createAzureFunctionHandler from "@pagopa/express-azure-functions/dist/src/createAzureFunctionsHandler"; import { cosmosdbInstance } from "../utils/cosmosdb"; import { getConfigOrThrow } from "../utils/config"; diff --git a/GetUserServices/__tests__/handler.test.ts b/GetUserServices/__tests__/handler.test.ts index c2a4f348..563de892 100644 --- a/GetUserServices/__tests__/handler.test.ts +++ b/GetUserServices/__tests__/handler.test.ts @@ -9,19 +9,19 @@ import { } from "@pagopa/io-functions-commons/dist/src/utils/middlewares/azure_api_auth"; import { IAzureUserAttributes } from "@pagopa/io-functions-commons/dist/src/utils/middlewares/azure_user_attributes"; -import { NonNegativeInteger } from "italia-ts-commons/lib/numbers"; +import { NonNegativeInteger } from "@pagopa/ts-commons/lib/numbers"; import { EmailString, NonEmptyString, OrganizationFiscalCode -} from "italia-ts-commons/lib/strings"; +} from "@pagopa/ts-commons/lib/strings"; import { toAuthorizedCIDRs } from "@pagopa/io-functions-commons/dist/src/models/service"; import { MaxAllowedPaymentAmount } from "@pagopa/io-functions-commons/dist/generated/definitions/MaxAllowedPaymentAmount"; import { left, right } from "fp-ts/lib/Either"; -import * as reporters from "italia-ts-commons/lib/reporters"; +import * as reporters from "@pagopa/ts-commons/lib/reporters"; import { Subscription } from "../../generated/api-admin/Subscription"; import { UserInfo } from "../../generated/api-admin/UserInfo"; import { GetUserServicesHandler } from "../handler"; diff --git a/GetUserServices/index.ts b/GetUserServices/index.ts index 414a2e9d..d2259979 100644 --- a/GetUserServices/index.ts +++ b/GetUserServices/index.ts @@ -9,7 +9,7 @@ import { import { secureExpressApp } from "@pagopa/io-functions-commons/dist/src/utils/express"; import { setAppContext } from "@pagopa/io-functions-commons/dist/src/utils/middlewares/context_middleware"; -import createAzureFunctionHandler from "io-functions-express/dist/src/createAzureFunctionsHandler"; +import createAzureFunctionHandler from "@pagopa/express-azure-functions/dist/src/createAzureFunctionsHandler"; import { cosmosdbInstance } from "../utils/cosmosdb"; import { apiClient } from "../clients/admin"; diff --git a/Info/__tests__/handler.test.ts b/Info/__tests__/handler.test.ts index d40dd2b4..dfc2d28c 100644 --- a/Info/__tests__/handler.test.ts +++ b/Info/__tests__/handler.test.ts @@ -1,4 +1,5 @@ -import { fromLeft, taskEither } from "fp-ts/lib/TaskEither"; +import * as TE from "fp-ts/lib/TaskEither"; + import { HealthCheck, HealthProblem } from "../../utils/healthcheck"; import { InfoHandler } from "../handler"; @@ -8,7 +9,7 @@ afterEach(() => { describe("InfoHandler", () => { it("should return an internal error if the application is not healthy", async () => { - const healthCheck: HealthCheck = fromLeft([ + const healthCheck: HealthCheck = TE.left([ "failure 1" as HealthProblem<"Config">, "failure 2" as HealthProblem<"Config"> ]); @@ -20,7 +21,7 @@ describe("InfoHandler", () => { }); it("should return a success if the application is healthy", async () => { - const healthCheck: HealthCheck = taskEither.of(true); + const healthCheck: HealthCheck = TE.of(true); const handler = InfoHandler(healthCheck); const response = await handler(); diff --git a/Info/handler.ts b/Info/handler.ts index 740af9e2..d52340c5 100644 --- a/Info/handler.ts +++ b/Info/handler.ts @@ -6,8 +6,10 @@ import { ResponseErrorInternal, ResponseSuccessJson } from "@pagopa/ts-commons/lib/responses"; + import * as TE from "fp-ts/lib/TaskEither"; import { pipe } from "fp-ts/lib/function"; + import * as packageJson from "../package.json"; import { checkApplicationHealth, HealthCheck } from "../utils/healthcheck"; diff --git a/Info/index.ts b/Info/index.ts index 2b4ab1b5..7939e302 100644 --- a/Info/index.ts +++ b/Info/index.ts @@ -2,7 +2,7 @@ import { AzureFunction, Context } from "@azure/functions"; import { secureExpressApp } from "@pagopa/io-functions-commons/dist/src/utils/express"; import { setAppContext } from "@pagopa/io-functions-commons/dist/src/utils/middlewares/context_middleware"; import * as express from "express"; -import createAzureFunctionHandler from "io-functions-express/dist/src/createAzureFunctionsHandler"; +import createAzureFunctionHandler from "@pagopa/express-azure-functions/dist/src/createAzureFunctionsHandler"; import { Info } from "./handler"; // Setup Express diff --git a/RegenerateServiceKey/__tests__/handler.test.ts b/RegenerateServiceKey/__tests__/handler.test.ts index c40d3ef3..de45c017 100644 --- a/RegenerateServiceKey/__tests__/handler.test.ts +++ b/RegenerateServiceKey/__tests__/handler.test.ts @@ -9,19 +9,19 @@ import { } from "@pagopa/io-functions-commons/dist/src/utils/middlewares/azure_api_auth"; import { IAzureUserAttributes } from "@pagopa/io-functions-commons/dist/src/utils/middlewares/azure_user_attributes"; -import { NonNegativeInteger } from "italia-ts-commons/lib/numbers"; +import { NonNegativeInteger } from "@pagopa/ts-commons/lib/numbers"; import { EmailString, NonEmptyString, OrganizationFiscalCode -} from "italia-ts-commons/lib/strings"; +} from "@pagopa/ts-commons/lib/strings"; import { toAuthorizedCIDRs } from "@pagopa/io-functions-commons/dist/src/models/service"; import { MaxAllowedPaymentAmount } from "@pagopa/io-functions-commons/dist/generated/definitions/MaxAllowedPaymentAmount"; import { left, right } from "fp-ts/lib/Either"; -import * as reporters from "italia-ts-commons/lib/reporters"; +import * as reporters from "@pagopa/ts-commons/lib/reporters"; import { SubscriptionKeyTypeEnum } from "../../generated/api-admin/SubscriptionKeyType"; import { SubscriptionKeyTypePayload } from "../../generated/api-admin/SubscriptionKeyTypePayload"; import { RegenerateServiceKeyHandler } from "../handler"; diff --git a/RegenerateServiceKey/index.ts b/RegenerateServiceKey/index.ts index 36850523..cecbed77 100644 --- a/RegenerateServiceKey/index.ts +++ b/RegenerateServiceKey/index.ts @@ -8,7 +8,7 @@ import { import { secureExpressApp } from "@pagopa/io-functions-commons/dist/src/utils/express"; import { setAppContext } from "@pagopa/io-functions-commons/dist/src/utils/middlewares/context_middleware"; -import createAzureFunctionHandler from "io-functions-express/dist/src/createAzureFunctionsHandler"; +import createAzureFunctionHandler from "@pagopa/express-azure-functions/dist/src/createAzureFunctionsHandler"; import { cosmosdbInstance } from "../utils/cosmosdb"; import { apiClient } from "../clients/admin"; diff --git a/StoreMessageContentActivity/__tests__/handler.test.ts b/StoreMessageContentActivity/__tests__/handler.test.ts index 3a28b057..3c06226f 100644 --- a/StoreMessageContentActivity/__tests__/handler.test.ts +++ b/StoreMessageContentActivity/__tests__/handler.test.ts @@ -9,10 +9,10 @@ import { } from "@pagopa/io-functions-commons/dist/src/models/profile"; import { ServicesPreferencesModel } from "@pagopa/io-functions-commons/dist/src/models/service_preference"; import { NonNegativeNumber } from "@pagopa/ts-commons/lib/numbers"; -import { isBefore } from "date-fns"; -import { fromLeft } from "fp-ts/lib/IOEither"; -import { none, some } from "fp-ts/lib/Option"; -import { taskEither } from "fp-ts/lib/TaskEither"; + +import * as TE from "fp-ts/lib/TaskEither"; +import * as O from "fp-ts/lib/Option"; + import { initTelemetryClient } from "../../utils/appinsights"; import { aCreatedMessageEventSenderMetadata, @@ -45,7 +45,7 @@ const mockTelemetryClient = ({ const findLastVersionByModelIdMock = jest .fn() - .mockImplementation(() => taskEither.of(some(aRetrievedProfile))); + .mockImplementation(() => TE.of(O.some(aRetrievedProfile))); const lProfileModel = ({ findLastVersionByModelId: findLastVersionByModelIdMock } as unknown) as ProfileModel; @@ -54,17 +54,15 @@ const aBlobResult = { name: "ABlobName" }; -const storeContentAsBlobMock = jest.fn(() => taskEither.of(some(aBlobResult))); -const upsertMessageMock = jest.fn(() => - taskEither.of(aRetrievedMessage) -); +const storeContentAsBlobMock = jest.fn(() => TE.of(O.some(aBlobResult))); +const upsertMessageMock = jest.fn(() => TE.of(aRetrievedMessage)); const lMessageModel = ({ storeContentAsBlob: storeContentAsBlobMock, upsert: upsertMessageMock } as unknown) as MessageModel; const findServicePreferenceMock = jest.fn(() => - taskEither.of(some(aRetrievedServicePreference)) + TE.of(O.some(aRetrievedServicePreference)) ); const lServicePreferencesModel = ({ find: findServicePreferenceMock @@ -131,18 +129,18 @@ describe("getStoreMessageContentActivityHandler", () => { }); it.each` - scenario | profileResult | storageResult | upsertResult | preferenceResult | messageEvent | expectedBIOC | optOutEmailSwitchDate | optInEmailEnabled | overrideProfileResult - ${"a retrieved profile mantaining its original isEmailEnabled property"} | ${aRetrievedProfileWithAValidTimestamp} | ${aBlobResult} | ${aRetrievedMessage} | ${some(aRetrievedServicePreference)} | ${aCreatedMessageEvent} | ${[]} | ${aPastOptOutEmailSwitchDate} | ${false} | ${"none"} - ${"retrieved profile with isEmailEnabled to false"} | ${{ ...aRetrievedProfile, isEmailEnabled: false }} | ${aBlobResult} | ${aRetrievedMessage} | ${some(aRetrievedServicePreference)} | ${aCreatedMessageEvent} | ${[]} | ${aPastOptOutEmailSwitchDate} | ${false} | ${"none"} - ${"empty blockedInboxOrChannels if message sender service does not exists in user service preference (AUTO SETTINGS)"} | ${withBlacklist(aRetrievedProfileWithAutoPreferences, [aCreatedMessageEvent.message.senderServiceId])} | ${aBlobResult} | ${aRetrievedMessage} | ${none} | ${aCreatedMessageEvent} | ${[]} | ${aPastOptOutEmailSwitchDate} | ${false} | ${"none"} - ${"empty blockedInboxOrChannels if message sender service exists and is enabled in user service preference (AUTO SETTINGS)"} | ${aRetrievedProfileWithAutoPreferences} | ${aBlobResult} | ${aRetrievedMessage} | ${some(anEnabledServicePreference)} | ${aCreatedMessageEvent} | ${[]} | ${aPastOptOutEmailSwitchDate} | ${false} | ${"none"} - ${"a blocked EMAIL if sender service exists and has EMAIL disabled in user service preference (AUTO SETTINGS)"} | ${withBlacklist(aRetrievedProfileWithAutoPreferences, [aCreatedMessageEvent.message.senderServiceId])} | ${aBlobResult} | ${aRetrievedMessage} | ${some({ ...anEnabledServicePreference, isEmailEnabled: false })} | ${aCreatedMessageEvent} | ${[BlockedInboxOrChannelEnum.EMAIL]} | ${aPastOptOutEmailSwitchDate} | ${false} | ${"none"} - ${"empty blockedInboxOrChannels if message sender service exists and is enabled in user service preference (MANUAL SETTINGS)"} | ${aRetrievedProfileWithManualPreferences} | ${aBlobResult} | ${aRetrievedMessage} | ${some(anEnabledServicePreference)} | ${aCreatedMessageEvent} | ${[]} | ${aPastOptOutEmailSwitchDate} | ${false} | ${"none"} - ${"blocked EMAIL if message sender service exists and has EMAIL disabled in user service preference (MANUAL SETTINGS)"} | ${aRetrievedProfileWithAutoPreferences} | ${aBlobResult} | ${aRetrievedMessage} | ${some({ ...anEnabledServicePreference, isEmailEnabled: false })} | ${aCreatedMessageEvent} | ${[BlockedInboxOrChannelEnum.EMAIL]} | ${aPastOptOutEmailSwitchDate} | ${false} | ${"none"} - ${"blocked EMAIL for a service in blockedInboxOrChannels with email disabled (LEGACY SETTINGS)"} | ${withBlockedEmail(aRetrievedProfileWithLegacyPreferences, [aCreatedMessageEvent.message.senderServiceId])} | ${aBlobResult} | ${aRetrievedMessage} | ${"not-called"} | ${aCreatedMessageEvent} | ${[BlockedInboxOrChannelEnum.EMAIL]} | ${aPastOptOutEmailSwitchDate} | ${false} | ${"none"} - ${"empty blockedInboxOrChannels if the service is not in user's blockedInboxOrChannels (LEGACY SETTINGS)"} | ${withBlacklist(aRetrievedProfileWithLegacyPreferences, ["another-service"])} | ${aBlobResult} | ${aRetrievedMessage} | ${"not-called"} | ${aCreatedMessageEvent} | ${[]} | ${aPastOptOutEmailSwitchDate} | ${false} | ${"none"} - ${"isEmailEnabled overridden to false if profile's timestamp is before optOutEmailSwitchDate"} | ${aRetrievedProfileWithAValidTimestamp} | ${aBlobResult} | ${aRetrievedMessage} | ${"not-called"} | ${aCreatedMessageEvent} | ${[]} | ${aFutureOptOutEmailSwitchDate} | ${true} | ${{ ...aRetrievedProfileWithAValidTimestamp, isEmailEnabled: false }} - ${"isEmailEnabled not overridden if profile's timestamp is after optOutEmailSwitchDate"} | ${aRetrievedProfileWithAValidTimestamp} | ${aBlobResult} | ${aRetrievedMessage} | ${"not-called"} | ${aCreatedMessageEvent} | ${[]} | ${aPastOptOutEmailSwitchDate} | ${true} | ${"none"} + scenario | profileResult | storageResult | upsertResult | preferenceResult | messageEvent | expectedBIOC | optOutEmailSwitchDate | optInEmailEnabled | overrideProfileResult + ${"a retrieved profile mantaining its original isEmailEnabled property"} | ${aRetrievedProfileWithAValidTimestamp} | ${aBlobResult} | ${aRetrievedMessage} | ${O.some(aRetrievedServicePreference)} | ${aCreatedMessageEvent} | ${[]} | ${aPastOptOutEmailSwitchDate} | ${false} | ${"O.none"} + ${"retrieved profile with isEmailEnabled to false"} | ${{ ...aRetrievedProfile, isEmailEnabled: false }} | ${aBlobResult} | ${aRetrievedMessage} | ${O.some(aRetrievedServicePreference)} | ${aCreatedMessageEvent} | ${[]} | ${aPastOptOutEmailSwitchDate} | ${false} | ${"O.none"} + ${"empty blockedInboxOrChannels if message sender service does not exists in user service preference (AUTO SETTINGS)"} | ${withBlacklist(aRetrievedProfileWithAutoPreferences, [aCreatedMessageEvent.message.senderServiceId])} | ${aBlobResult} | ${aRetrievedMessage} | ${O.none} | ${aCreatedMessageEvent} | ${[]} | ${aPastOptOutEmailSwitchDate} | ${false} | ${"O.none"} + ${"empty blockedInboxOrChannels if message sender service exists and is enabled in user service preference (AUTO SETTINGS)"} | ${aRetrievedProfileWithAutoPreferences} | ${aBlobResult} | ${aRetrievedMessage} | ${O.some(anEnabledServicePreference)} | ${aCreatedMessageEvent} | ${[]} | ${aPastOptOutEmailSwitchDate} | ${false} | ${"O.none"} + ${"a blocked EMAIL if sender service exists and has EMAIL disabled in user service preference (AUTO SETTINGS)"} | ${withBlacklist(aRetrievedProfileWithAutoPreferences, [aCreatedMessageEvent.message.senderServiceId])} | ${aBlobResult} | ${aRetrievedMessage} | ${O.some({ ...anEnabledServicePreference, isEmailEnabled: false })} | ${aCreatedMessageEvent} | ${[BlockedInboxOrChannelEnum.EMAIL]} | ${aPastOptOutEmailSwitchDate} | ${false} | ${"O.none"} + ${"empty blockedInboxOrChannels if message sender service exists and is enabled in user service preference (MANUAL SETTINGS)"} | ${aRetrievedProfileWithManualPreferences} | ${aBlobResult} | ${aRetrievedMessage} | ${O.some(anEnabledServicePreference)} | ${aCreatedMessageEvent} | ${[]} | ${aPastOptOutEmailSwitchDate} | ${false} | ${"O.none"} + ${"blocked EMAIL if message sender service exists and has EMAIL disabled in user service preference (MANUAL SETTINGS)"} | ${aRetrievedProfileWithAutoPreferences} | ${aBlobResult} | ${aRetrievedMessage} | ${O.some({ ...anEnabledServicePreference, isEmailEnabled: false })} | ${aCreatedMessageEvent} | ${[BlockedInboxOrChannelEnum.EMAIL]} | ${aPastOptOutEmailSwitchDate} | ${false} | ${"O.none"} + ${"blocked EMAIL for a service in blockedInboxOrChannels with email disabled (LEGACY SETTINGS)"} | ${withBlockedEmail(aRetrievedProfileWithLegacyPreferences, [aCreatedMessageEvent.message.senderServiceId])} | ${aBlobResult} | ${aRetrievedMessage} | ${"not-called"} | ${aCreatedMessageEvent} | ${[BlockedInboxOrChannelEnum.EMAIL]} | ${aPastOptOutEmailSwitchDate} | ${false} | ${"O.none"} + ${"empty blockedInboxOrChannels if the service is not in user's blockedInboxOrChannels (LEGACY SETTINGS)"} | ${withBlacklist(aRetrievedProfileWithLegacyPreferences, ["another-service"])} | ${aBlobResult} | ${aRetrievedMessage} | ${"not-called"} | ${aCreatedMessageEvent} | ${[]} | ${aPastOptOutEmailSwitchDate} | ${false} | ${"O.none"} + ${"isEmailEnabled overridden to false if profile's timestamp is before optOutEmailSwitchDate"} | ${aRetrievedProfileWithAValidTimestamp} | ${aBlobResult} | ${aRetrievedMessage} | ${"not-called"} | ${aCreatedMessageEvent} | ${[]} | ${aFutureOptOutEmailSwitchDate} | ${true} | ${{ ...aRetrievedProfileWithAValidTimestamp, isEmailEnabled: false }} + ${"isEmailEnabled not overridden if profile's timestamp is after optOutEmailSwitchDate"} | ${aRetrievedProfileWithAValidTimestamp} | ${aBlobResult} | ${aRetrievedMessage} | ${"not-called"} | ${aCreatedMessageEvent} | ${[]} | ${aPastOptOutEmailSwitchDate} | ${true} | ${"O.none"} `( "should succeed with $scenario", async ({ @@ -160,17 +158,17 @@ describe("getStoreMessageContentActivityHandler", () => { skipPreferenceMock = preferenceResult === "not-called" }) => { findLastVersionByModelIdMock.mockImplementationOnce(() => - taskEither.of(some(profileResult)) + TE.of(O.some(profileResult)) ); storeContentAsBlobMock.mockImplementationOnce(() => - taskEither.of(some(storageResult)) + TE.of(O.some(storageResult)) ); upsertMessageMock.mockImplementationOnce(() => - taskEither.of(some(upsertResult)) + TE.of(O.some(upsertResult)) ); !skipPreferenceMock && findServicePreferenceMock.mockImplementationOnce(() => - taskEither.of(preferenceResult) + TE.of(preferenceResult) ); const storeMessageContentActivityHandler = getStoreMessageContentActivityHandler( @@ -194,7 +192,7 @@ describe("getStoreMessageContentActivityHandler", () => { if (result.kind === "SUCCESS") { expect(result.blockedInboxOrChannels).toEqual(expectedBIOC); expect(result.profile).toEqual( - overrideProfileResult === "none" + overrideProfileResult === "O.none" ? profileResult : overrideProfileResult ); @@ -207,17 +205,17 @@ describe("getStoreMessageContentActivityHandler", () => { ); it.each` - scenario | failureReason | profileResult | preferenceResult | messageEvent - ${"activity input cannot be decoded"} | ${"BAD_DATA"} | ${"not-called"} | ${"not-called"} | ${{}} - ${"no profile was found"} | ${"PROFILE_NOT_FOUND"} | ${none} | ${"not-called"} | ${aCreatedMessageEvent} - ${"inbox is not enabled"} | ${"MASTER_INBOX_DISABLED"} | ${some({ ...aRetrievedProfile, isInboxEnabled: false })} | ${"not-called"} | ${aCreatedMessageEvent} - ${"message sender is blocked"} | ${"SENDER_BLOCKED"} | ${some(withBlacklist(aRetrievedProfile, [aCreatedMessageEvent.message.senderServiceId]))} | ${"not-called"} | ${aCreatedMessageEvent} - ${"message sender service exists and is not enabled in user service preference (AUTO SETTINGS)"} | ${"SENDER_BLOCKED"} | ${some(aRetrievedProfileWithAutoPreferences)} | ${some(aDisabledServicePreference)} | ${aCreatedMessageEvent} - ${"message sender service exists and has INBOX disabled in user service preference (AUTO SETTINGS)"} | ${"SENDER_BLOCKED"} | ${some(aRetrievedProfileWithAutoPreferences)} | ${some({ anEnabledServicePreference, isInboxEnabled: false })} | ${aCreatedMessageEvent} - ${"message sender service does not exists in user service preference (MANUAL SETTINGS)"} | ${"SENDER_BLOCKED"} | ${some(aRetrievedProfileWithManualPreferences)} | ${none} | ${aCreatedMessageEvent} - ${"message sender service exists and is not enabled in user service preference (MANUAL SETTINGS)"} | ${"SENDER_BLOCKED"} | ${some(aRetrievedProfileWithManualPreferences)} | ${some(aDisabledServicePreference)} | ${aCreatedMessageEvent} - ${"message sender service exists and has INBOX disabled in user service preference (MANUAL SETTINGS)"} | ${"SENDER_BLOCKED"} | ${some(aRetrievedProfileWithManualPreferences)} | ${some({ anEnabledServicePreference, isInboxEnabled: false })} | ${aCreatedMessageEvent} - ${"service in blockedInboxOrChannels with blocked INBOX (LEGACY SETTINGS)"} | ${"SENDER_BLOCKED"} | ${some(withBlacklist(aRetrievedProfileWithLegacyPreferences, [aCreatedMessageEvent.message.senderServiceId]))} | ${"not-called"} | ${aCreatedMessageEvent} + scenario | failureReason | profileResult | preferenceResult | messageEvent + ${"activity input cannot be decoded"} | ${"BAD_DATA"} | ${"not-called"} | ${"not-called"} | ${{}} + ${"no profile was found"} | ${"PROFILE_NOT_FOUND"} | ${O.none} | ${"not-called"} | ${aCreatedMessageEvent} + ${"inbox is not enabled"} | ${"MASTER_INBOX_DISABLED"} | ${O.some({ ...aRetrievedProfile, isInboxEnabled: false })} | ${"not-called"} | ${aCreatedMessageEvent} + ${"message sender is blocked"} | ${"SENDER_BLOCKED"} | ${O.some(withBlacklist(aRetrievedProfile, [aCreatedMessageEvent.message.senderServiceId]))} | ${"not-called"} | ${aCreatedMessageEvent} + ${"message sender service exists and is not enabled in user service preference (AUTO SETTINGS)"} | ${"SENDER_BLOCKED"} | ${O.some(aRetrievedProfileWithAutoPreferences)} | ${O.some(aDisabledServicePreference)} | ${aCreatedMessageEvent} + ${"message sender service exists and has INBOX disabled in user service preference (AUTO SETTINGS)"} | ${"SENDER_BLOCKED"} | ${O.some(aRetrievedProfileWithAutoPreferences)} | ${O.some({ anEnabledServicePreference, isInboxEnabled: false })} | ${aCreatedMessageEvent} + ${"message sender service does not exists in user service preference (MANUAL SETTINGS)"} | ${"SENDER_BLOCKED"} | ${O.some(aRetrievedProfileWithManualPreferences)} | ${O.none} | ${aCreatedMessageEvent} + ${"message sender service exists and is not enabled in user service preference (MANUAL SETTINGS)"} | ${"SENDER_BLOCKED"} | ${O.some(aRetrievedProfileWithManualPreferences)} | ${O.some(aDisabledServicePreference)} | ${aCreatedMessageEvent} + ${"message sender service exists and has INBOX disabled in user service preference (MANUAL SETTINGS)"} | ${"SENDER_BLOCKED"} | ${O.some(aRetrievedProfileWithManualPreferences)} | ${O.some({ anEnabledServicePreference, isInboxEnabled: false })} | ${aCreatedMessageEvent} + ${"service in blockedInboxOrChannels with blocked INBOX (LEGACY SETTINGS)"} | ${"SENDER_BLOCKED"} | ${O.some(withBlacklist(aRetrievedProfileWithLegacyPreferences, [aCreatedMessageEvent.message.senderServiceId]))} | ${"not-called"} | ${aCreatedMessageEvent} `( "should fail if $scenario", async ({ @@ -232,11 +230,11 @@ describe("getStoreMessageContentActivityHandler", () => { }) => { !skipProfileMock && findLastVersionByModelIdMock.mockImplementationOnce(() => { - return taskEither.of(profileResult); + return TE.of(profileResult); }); !skipPreferenceMock && findServicePreferenceMock.mockImplementationOnce(() => { - return taskEither.of(preferenceResult); + return TE.of(preferenceResult); }); const storeMessageContentActivityHandler = getStoreMessageContentActivityHandler( { @@ -271,12 +269,12 @@ describe("getStoreMessageContentActivityHandler", () => { ); it.each` - scenario | profileResult | storageResult | upsertResult | preferenceResult | messageEvent - ${"there is an error while fetching profile"} | ${fromLeft("Profile fetch error")} | ${"not-called"} | ${"not-called"} | ${"not-called"} | ${aCreatedMessageEvent} - ${"message store operation fails"} | ${taskEither.of(some(aRetrievedProfile))} | ${fromLeft(new Error("Error while storing message content"))} | ${"not-called"} | ${"not-called"} | ${aCreatedMessageEvent} - ${"message upsert fails"} | ${taskEither.of(some(aRetrievedProfile))} | ${taskEither.of(some(aBlobResult))} | ${fromLeft(new Error("Error while upserting message"))} | ${"not-called"} | ${aCreatedMessageEvent} - ${"user's service preference retrieval fails (AUTO)"} | ${taskEither.of(some(aRetrievedProfileWithAutoPreferences))} | ${"not-called"} | ${"not-called"} | ${fromLeft(new Error("Error while reading preference"))} | ${aCreatedMessageEvent} - ${"user's service preference retrieval fails (MANUAL SETTINGS)"} | ${taskEither.of(some(aRetrievedProfileWithManualPreferences))} | ${"not-called"} | ${"not-called"} | ${fromLeft({ kind: "COSMOS_EMPTY_RESPONSE" })} | ${aCreatedMessageEvent} + scenario | profileResult | storageResult | upsertResult | preferenceResult | messageEvent + ${"there is an error while fetching profile"} | ${TE.left("Profile fetch error")} | ${"not-called"} | ${"not-called"} | ${"not-called"} | ${aCreatedMessageEvent} + ${"message store operation fails"} | ${TE.of(O.some(aRetrievedProfile))} | ${TE.left(new Error("Error while storing message content"))} | ${"not-called"} | ${"not-called"} | ${aCreatedMessageEvent} + ${"message upsert fails"} | ${TE.of(O.some(aRetrievedProfile))} | ${TE.of(O.some(aBlobResult))} | ${TE.left(new Error("Error while upserting message"))} | ${"not-called"} | ${aCreatedMessageEvent} + ${"user's service preference retrieval fails (AUTO)"} | ${TE.of(O.some(aRetrievedProfileWithAutoPreferences))} | ${"not-called"} | ${"not-called"} | ${TE.left(new Error("Error while reading preference"))} | ${aCreatedMessageEvent} + ${"user's service preference retrieval fails (MANUAL SETTINGS)"} | ${TE.of(O.some(aRetrievedProfileWithManualPreferences))} | ${"not-called"} | ${"not-called"} | ${TE.left({ kind: "COSMOS_EMPTY_RESPONSE" })} | ${aCreatedMessageEvent} `( "should throw an Error if $scenario", async ({ diff --git a/UpdateService/__tests__/handler.test.ts b/UpdateService/__tests__/handler.test.ts index 70247692..84ede81b 100644 --- a/UpdateService/__tests__/handler.test.ts +++ b/UpdateService/__tests__/handler.test.ts @@ -9,12 +9,12 @@ import { } from "@pagopa/io-functions-commons/dist/src/utils/middlewares/azure_api_auth"; import { IAzureUserAttributes } from "@pagopa/io-functions-commons/dist/src/utils/middlewares/azure_user_attributes"; -import { NonNegativeInteger } from "italia-ts-commons/lib/numbers"; +import { NonNegativeInteger } from "@pagopa/ts-commons/lib/numbers"; import { EmailString, NonEmptyString, OrganizationFiscalCode -} from "italia-ts-commons/lib/strings"; +} from "@pagopa/ts-commons/lib/strings"; import { ServiceMetadata } from "@pagopa/io-functions-commons/dist/src/models/service"; @@ -22,7 +22,7 @@ import { MaxAllowedPaymentAmount } from "@pagopa/io-functions-commons/dist/gener import { left, right } from "fp-ts/lib/Either"; import { ServiceScopeEnum } from "@pagopa/io-functions-commons/dist/generated/definitions/ServiceScope"; -import * as reporters from "italia-ts-commons/lib/reporters"; +import * as reporters from "@pagopa/ts-commons/lib/reporters"; import { Service } from "../../generated/api-admin/Service"; import { Subscription } from "../../generated/api-admin/Subscription"; import { UserInfo } from "../../generated/api-admin/UserInfo"; diff --git a/UpdateService/index.ts b/UpdateService/index.ts index 75f9d2a9..978d8725 100644 --- a/UpdateService/index.ts +++ b/UpdateService/index.ts @@ -9,7 +9,7 @@ import { import { secureExpressApp } from "@pagopa/io-functions-commons/dist/src/utils/express"; import { setAppContext } from "@pagopa/io-functions-commons/dist/src/utils/middlewares/context_middleware"; -import createAzureFunctionHandler from "io-functions-express/dist/src/createAzureFunctionsHandler"; +import createAzureFunctionHandler from "@pagopa/express-azure-functions/dist/src/createAzureFunctionsHandler"; import { cosmosdbInstance } from "../utils/cosmosdb"; import { apiClient } from "../clients/admin"; diff --git a/UploadOrganizationLogo/__tests__/handler.test.ts b/UploadOrganizationLogo/__tests__/handler.test.ts index 0bf11a7f..98187750 100644 --- a/UploadOrganizationLogo/__tests__/handler.test.ts +++ b/UploadOrganizationLogo/__tests__/handler.test.ts @@ -9,19 +9,19 @@ import { } from "@pagopa/io-functions-commons/dist/src/utils/middlewares/azure_api_auth"; import { IAzureUserAttributes } from "@pagopa/io-functions-commons/dist/src/utils/middlewares/azure_user_attributes"; -import { NonNegativeInteger } from "italia-ts-commons/lib/numbers"; +import { NonNegativeInteger } from "@pagopa/ts-commons/lib/numbers"; import { EmailString, NonEmptyString, OrganizationFiscalCode -} from "italia-ts-commons/lib/strings"; +} from "@pagopa/ts-commons/lib/strings"; import { toAuthorizedCIDRs } from "@pagopa/io-functions-commons/dist/src/models/service"; import { MaxAllowedPaymentAmount } from "@pagopa/io-functions-commons/dist/generated/definitions/MaxAllowedPaymentAmount"; import { left, right } from "fp-ts/lib/Either"; -import * as reporters from "italia-ts-commons/lib/reporters"; +import * as reporters from "@pagopa/ts-commons/lib/reporters"; import { Logo } from "../../generated/api-admin/Logo"; import { UploadOrganizationLogoHandler } from "../handler"; diff --git a/UploadOrganizationLogo/index.ts b/UploadOrganizationLogo/index.ts index eb7814d6..71d249ef 100644 --- a/UploadOrganizationLogo/index.ts +++ b/UploadOrganizationLogo/index.ts @@ -8,7 +8,7 @@ import { import { secureExpressApp } from "@pagopa/io-functions-commons/dist/src/utils/express"; import { setAppContext } from "@pagopa/io-functions-commons/dist/src/utils/middlewares/context_middleware"; -import createAzureFunctionHandler from "io-functions-express/dist/src/createAzureFunctionsHandler"; +import createAzureFunctionHandler from "@pagopa/express-azure-functions/dist/src/createAzureFunctionsHandler"; import { cosmosdbInstance } from "../utils/cosmosdb"; import { apiClient } from "../clients/admin"; diff --git a/UploadServiceLogo/__tests__/handler.test.ts b/UploadServiceLogo/__tests__/handler.test.ts index a1bb636b..3ca6fec3 100644 --- a/UploadServiceLogo/__tests__/handler.test.ts +++ b/UploadServiceLogo/__tests__/handler.test.ts @@ -9,19 +9,19 @@ import { } from "@pagopa/io-functions-commons/dist/src/utils/middlewares/azure_api_auth"; import { IAzureUserAttributes } from "@pagopa/io-functions-commons/dist/src/utils/middlewares/azure_user_attributes"; -import { NonNegativeInteger } from "italia-ts-commons/lib/numbers"; +import { NonNegativeInteger } from "@pagopa/ts-commons/lib/numbers"; import { EmailString, NonEmptyString, OrganizationFiscalCode -} from "italia-ts-commons/lib/strings"; +} from "@pagopa/ts-commons/lib/strings"; import { toAuthorizedCIDRs } from "@pagopa/io-functions-commons/dist/src/models/service"; import { MaxAllowedPaymentAmount } from "@pagopa/io-functions-commons/dist/generated/definitions/MaxAllowedPaymentAmount"; import { left, right } from "fp-ts/lib/Either"; -import * as reporters from "italia-ts-commons/lib/reporters"; +import * as reporters from "@pagopa/ts-commons/lib/reporters"; import { Logo } from "../../generated/api-admin/Logo"; import { UploadServiceLogoHandler } from "../handler"; diff --git a/UploadServiceLogo/index.ts b/UploadServiceLogo/index.ts index 6056dc06..77f942db 100644 --- a/UploadServiceLogo/index.ts +++ b/UploadServiceLogo/index.ts @@ -8,7 +8,7 @@ import { import { secureExpressApp } from "@pagopa/io-functions-commons/dist/src/utils/express"; import { setAppContext } from "@pagopa/io-functions-commons/dist/src/utils/middlewares/context_middleware"; -import createAzureFunctionHandler from "io-functions-express/dist/src/createAzureFunctionsHandler"; +import createAzureFunctionHandler from "@pagopa/express-azure-functions/dist/src/createAzureFunctionsHandler"; import { cosmosdbInstance } from "../utils/cosmosdb"; import { apiClient } from "../clients/admin"; diff --git a/WebhookNotificationActivity/__tests__/handler.test.ts b/WebhookNotificationActivity/__tests__/handler.test.ts index c7176ef4..c4698ff6 100644 --- a/WebhookNotificationActivity/__tests__/handler.test.ts +++ b/WebhookNotificationActivity/__tests__/handler.test.ts @@ -5,14 +5,12 @@ jest.mock("applicationinsights"); jest.mock("azure-storage"); -import { isLeft, isRight, right } from "fp-ts/lib/Either"; -import { none, some } from "fp-ts/lib/Option"; import { EmailString, FiscalCode, NonEmptyString, OrganizationFiscalCode -} from "italia-ts-commons/lib/strings"; +} from "@pagopa/ts-commons/lib/strings"; import { CreatedMessageEventSenderMetadata } from "@pagopa/io-functions-commons/dist/src/models/created_message_sender_metadata"; import { Notification } from "@pagopa/io-functions-commons/dist/src/models/notification"; @@ -20,7 +18,7 @@ import { isTransientError } from "@pagopa/io-functions-commons/dist/src/utils/er import { NotificationEvent } from "@pagopa/io-functions-commons/dist/src/models/notification_event"; -import { readableReport } from "italia-ts-commons/lib/reporters"; +import { readableReport } from "@pagopa/ts-commons/lib/reporters"; import { getWebhookNotificationActivityHandler, @@ -36,15 +34,18 @@ import { NotificationChannelEnum } from "@pagopa/io-functions-commons/dist/gener import { TimeToLiveSeconds } from "@pagopa/io-functions-commons/dist/generated/definitions/TimeToLiveSeconds"; import { getNotifyClient } from "../client"; -import { agent } from "italia-ts-commons"; +import { agent } from "@pagopa/ts-commons"; import { AbortableFetch, setFetchTimeout, toFetch -} from "italia-ts-commons/lib/fetch"; -import { Millisecond } from "italia-ts-commons/lib/units"; -import { taskEither } from "fp-ts/lib/TaskEither"; -import { fromLeft } from "fp-ts/lib/IOEither"; +} from "@pagopa/ts-commons/lib/fetch"; +import { Millisecond } from "@pagopa/ts-commons/lib/units"; + +import { pipe } from "fp-ts/lib/function"; +import * as E from "fp-ts/lib/Either"; +import * as TE from "fp-ts/lib/TaskEither"; +import * as O from "fp-ts/lib/Option"; afterEach(() => { jest.restoreAllMocks(); @@ -109,16 +110,19 @@ const getMockNotificationEvent = ( subject: aMessageBodySubject } ) => { - return NotificationEvent.decode( - Object.assign({}, aNotificationEvent, { - content: messageContent, - message: aNotificationEvent.message + return pipe( + NotificationEvent.decode( + Object.assign({}, aNotificationEvent, { + content: messageContent, + message: aNotificationEvent.message + }) + ), + E.getOrElseW(errs => { + throw new Error( + "Cannot deserialize NotificationEvent: " + readableReport(errs) + ); }) - ).getOrElseL(errs => { - throw new Error( - "Cannot deserialize NotificationEvent: " + readableReport(errs) - ); - }); + ); }; const aNotification: Notification = { @@ -163,8 +167,8 @@ describe("sendToWebhook", () => { aMessageContent, aSenderMetadata, false - ).run(); - expect(isRight(ret)).toBeTruthy(); + )(); + expect(E.isRight(ret)).toBeTruthy(); }); it("should remove message content if the service require secure channel", async () => { @@ -181,13 +185,13 @@ describe("sendToWebhook", () => { requireSecureChannels: true }, false - ).run(); + )(); expect(fetchApi.mock.calls[0][1]).toHaveProperty("body"); const body = JSON.parse(fetchApi.mock.calls[0][1].body); expect(body).toHaveProperty("message"); expect(body).toHaveProperty("sender_metadata"); expect(body).not.toHaveProperty("content"); - expect(isRight(ret)).toBeTruthy(); + expect(E.isRight(ret)).toBeTruthy(); }); it("should remove message content if webhook message content is disabled", async () => { const expectedResponse = { message: "OK" }; @@ -200,13 +204,13 @@ describe("sendToWebhook", () => { aMessageContent, aSenderMetadata, true - ).run(); + )(); expect(fetchApi.mock.calls[0][1]).toHaveProperty("body"); const body = JSON.parse(fetchApi.mock.calls[0][1].body); expect(body).toHaveProperty("message"); expect(body).toHaveProperty("sender_metadata"); expect(body).not.toHaveProperty("content"); - expect(isRight(ret)).toBeTruthy(); + expect(E.isRight(ret)).toBeTruthy(); }); it("should return a transient error in case of timeout", async () => { const abortableFetch = AbortableFetch(agent.getHttpsFetch(process.env)); @@ -219,10 +223,10 @@ describe("sendToWebhook", () => { aMessageContent, aSenderMetadata, false - ).run(); - expect(isLeft(ret)).toBeTruthy(); - if (isLeft(ret)) { - expect(isTransientError(ret.value)).toBeTruthy(); + )(); + expect(E.isLeft(ret)).toBeTruthy(); + if (E.isLeft(ret)) { + expect(isTransientError(ret.left)).toBeTruthy(); } }); @@ -236,11 +240,11 @@ describe("sendToWebhook", () => { {} as any, {} as any, false - ).run(); + )(); expect(fetchApi).toHaveBeenCalledTimes(1); - expect(isLeft(ret)).toBeTruthy(); - if (isLeft(ret)) { - expect(isTransientError(ret.value)).toBeTruthy(); + expect(E.isLeft(ret)).toBeTruthy(); + if (E.isLeft(ret)) { + expect(isTransientError(ret.left)).toBeTruthy(); } }); @@ -254,11 +258,11 @@ describe("sendToWebhook", () => { {} as any, {} as any, false - ).run(); + )(); expect(fetchApi).toHaveBeenCalledTimes(1); - expect(isLeft(ret)).toBeTruthy(); - if (isLeft(ret)) { - expect(isTransientError(ret.value)).toBeFalsy(); + expect(E.isLeft(ret)).toBeTruthy(); + if (E.isLeft(ret)) { + expect(isTransientError(ret.left)).toBeFalsy(); } }); }); @@ -266,7 +270,7 @@ describe("sendToWebhook", () => { describe("handler", () => { it("should return a transient error when there's an error while retrieving the notification", async () => { const notificationModelMock = { - find: jest.fn(() => fromLeft("error")) + find: jest.fn(() => TE.left("error")) }; await expect( @@ -282,7 +286,7 @@ describe("handler", () => { it("should return a transient error when the notification does not exist", async () => { const notificationModelMock = { - find: jest.fn(() => taskEither.of(none)) + find: jest.fn(() => TE.of(O.none)) }; await expect( @@ -298,7 +302,7 @@ describe("handler", () => { it("should return a permanent error when the notification does not contain the webhook url", async () => { const notificationModelMock = { - find: jest.fn(() => taskEither.of(some({}))) + find: jest.fn(() => TE.of(O.some({}))) }; await expect( @@ -314,13 +318,13 @@ describe("handler", () => { it("should forward a notification", async () => { const notificationModelMock = { - find: jest.fn(() => taskEither.of(some(aNotification))), - update: jest.fn(() => taskEither.of(some(aNotification))) + find: jest.fn(() => TE.of(O.some(aNotification))), + update: jest.fn(() => TE.of(O.some(aNotification))) }; const notifyCallApiMock = jest .fn() - .mockReturnValue(Promise.resolve(right({ status: 200 }))); + .mockReturnValue(Promise.resolve(E.right({ status: 200 }))); const result = await getWebhookNotificationActivityHandler( notificationModelMock as any, @@ -341,7 +345,7 @@ describe("handler", () => { const notifyCallApiMock = jest .fn() - .mockReturnValue(Promise.resolve(right({ status: 200 }))); + .mockReturnValue(Promise.resolve(E.right({ status: 200 }))); const aLongMessageContent = { markdown: aMessageBodyMarkdown, @@ -349,8 +353,8 @@ describe("handler", () => { }; const notificationModelMock = { - find: jest.fn(() => taskEither.of(some(aNotification))), - update: jest.fn(() => taskEither.of(some(aNotification))) + find: jest.fn(() => TE.of(O.some(aNotification))), + update: jest.fn(() => TE.of(O.some(aNotification))) }; const result = await getWebhookNotificationActivityHandler( @@ -370,11 +374,11 @@ describe("handler", () => { it("should track delivery failures", async () => { const notifyCallApiMock = jest .fn() - .mockReturnValue(Promise.resolve(right({ status: 401 }))); + .mockReturnValue(Promise.resolve(E.right({ status: 401 }))); const notificationModelMock = { - find: jest.fn(() => taskEither.of(some(aNotification))), - update: jest.fn(() => taskEither.of(some(aNotification))) + find: jest.fn(() => TE.of(O.some(aNotification))), + update: jest.fn(() => TE.of(O.some(aNotification))) }; await expect( @@ -392,7 +396,7 @@ describe("handler", () => { it("should stop processing in case the message is expired", async () => { const notificationModelMock = { - find: jest.fn(() => right(some({}))) + find: jest.fn(() => E.right(O.some({}))) }; const notificationEvent = getMockNotificationEvent(); diff --git a/package.json b/package.json index a9fddca1..bc6c05a1 100644 --- a/package.json +++ b/package.json @@ -34,7 +34,7 @@ "devDependencies": { "@azure/functions": "^1.2.0", "@pagopa/eslint-config": "^1.3.1", - "@pagopa/openapi-codegen-ts": "../../utils/openapi-codegen-ts/pagopa-openapi-codegen-ts-9.2.0.tgz", + "@pagopa/openapi-codegen-ts": "^10.0.0", "@types/cors": "^2.8.4", "@types/documentdb": "^1.10.5", "@types/express": "^4.16.0", @@ -58,8 +58,9 @@ }, "dependencies": { "@azure/cosmos": "^3.11.5", - "@pagopa/io-functions-commons": "../../commons/io-functions-commons/pagopa-io-functions-commons-21.0.0.tgz", - "@pagopa/ts-commons": "^10.0.0", + "@pagopa/express-azure-functions": "^2.0.0", + "@pagopa/io-functions-commons": "^21.0.0", + "@pagopa/ts-commons": "^10.0.1", "applicationinsights": "^1.7.4", "azure-storage": "^2.10.4", "cors": "^2.8.4", @@ -69,7 +70,6 @@ "express": "^4.15.3", "fp-ts": "^2.11.1", "html-to-text": "^4.0.0", - "io-functions-express": "^0.1.1", "io-ts": "^2.2.16", "node-fetch": "^2.6.1", "nodemailer": "^6.4.16", diff --git a/utils/__tests__/arbitraries.ts b/utils/__tests__/arbitraries.ts index ef11b1fd..5fa5985a 100644 --- a/utils/__tests__/arbitraries.ts +++ b/utils/__tests__/arbitraries.ts @@ -7,17 +7,21 @@ import { Service } from "@pagopa/io-functions-commons/dist/src/models/service"; import { ClientIp } from "@pagopa/io-functions-commons/dist/src/utils/middlewares/client_ip_middleware"; import * as assert from "assert"; import * as fc from "fast-check"; -import { some } from "fp-ts/lib/Option"; + +import { flow, pipe } from "fp-ts/lib/function"; +import * as E from "fp-ts/lib/Either"; +import * as O from "fp-ts/lib/Option"; + import { NonNegativeInteger, WithinRangeInteger -} from "italia-ts-commons/lib/numbers"; +} from "@pagopa/ts-commons/lib/numbers"; import { EmailString, FiscalCode, NonEmptyString, PatternString -} from "italia-ts-commons/lib/strings"; +} from "@pagopa/ts-commons/lib/strings"; import { legacyProfileServicePreferencesSettings } from "../../__mocks__/mocks"; // @@ -70,7 +74,7 @@ export const fiscalCodeArrayArb = fc.array(fiscalCodeArb); export const fiscalCodeSetArb = fiscalCodeArrayArb.map(_ => new Set(_)); -export const clientIpArb = fc.ipV4().map(_ => some(_) as ClientIp); +export const clientIpArb = fc.ipV4().map(_ => O.some(_) as ClientIp); const messageContentSubject = fc.string(10, 120); const messageContentMarkdown = fc.string(80, 10000); @@ -78,12 +82,15 @@ const messageContentMarkdown = fc.string(80, 10000); export const newMessageArb = fc .tuple(messageContentSubject, messageContentMarkdown) .map(([subject, markdown]) => - NewMessage.decode({ - content: { - markdown, - subject - } - }).getOrElse(undefined) + pipe( + NewMessage.decode({ + content: { + markdown, + subject + } + }), + E.getOrElse(undefined) + ) ) .filter(_ => _ !== undefined); @@ -104,9 +111,7 @@ export const messageTimeToLiveArb = fc export const amountArb = fc .integer(1, 9999999999) .map(_ => - WithinRangeInteger(1, 9999999999) - .decode(_) - .getOrElse(undefined) + pipe(WithinRangeInteger(1, 9999999999).decode(_), E.getOrElse(undefined)) ) .filter(_ => _ !== undefined); diff --git a/utils/__tests__/comma-separated-list.test.ts b/utils/__tests__/comma-separated-list.test.ts index 0c1a4ba7..f31381d5 100644 --- a/utils/__tests__/comma-separated-list.test.ts +++ b/utils/__tests__/comma-separated-list.test.ts @@ -1,8 +1,11 @@ import * as t from "io-ts"; -import { readableReport } from "italia-ts-commons/lib/reporters"; -import { FiscalCode } from "italia-ts-commons/lib/strings"; +import { readableReport } from "@pagopa/ts-commons/lib/reporters"; +import { FiscalCode } from "@pagopa/ts-commons/lib/strings"; import { CommaSeparatedListOf } from "../comma-separated-list"; +import { pipe } from "fp-ts/lib/function"; +import * as E from "fp-ts/lib/Either"; + describe("CommaSeparatedListOf", () => { it.each` title | input | expected | decoder @@ -14,16 +17,17 @@ describe("CommaSeparatedListOf", () => { ${"trim elements"} | ${"a , b, c "} | ${["a", "b", "c"]} | ${t.string} ${"fiscal codes"} | ${"AAABBB80A01C123D"} | ${["AAABBB80A01C123D"]} | ${FiscalCode} `("should parse $title", ({ input, expected, decoder }) => { - CommaSeparatedListOf(decoder) - .decode(input) - .fold( + pipe( + CommaSeparatedListOf(decoder).decode(input), + E.fold( err => { fail(`cannot decode input: ${readableReport(err)}`); }, value => { expect(value).toEqual(expected); } - ); + ) + ); }); it.each` @@ -33,6 +37,6 @@ describe("CommaSeparatedListOf", () => { ${"'1,2,3' into [1,2,3]"} | ${"1,2,3"} | ${t.number} `("should fail to parse $title", ({ input, decoder }) => { const result = CommaSeparatedListOf(decoder).decode(input); - expect(result.isLeft()).toBeTruthy(); + expect(E.isLeft(result)).toBeTruthy(); }); }); diff --git a/utils/__tests__/profile.test.ts b/utils/__tests__/profile.test.ts index 7314c756..ad0d6f14 100644 --- a/utils/__tests__/profile.test.ts +++ b/utils/__tests__/profile.test.ts @@ -1,6 +1,6 @@ import * as fc from "fast-check"; -import { NonEmptyString } from "italia-ts-commons/lib/strings"; +import { NonEmptyString } from "@pagopa/ts-commons/lib/strings"; import { BlockedInboxOrChannelEnum } from "@pagopa/io-functions-commons/dist/generated/definitions/BlockedInboxOrChannel"; @@ -34,8 +34,13 @@ const mockTelemetryClient = ({ } as unknown) as ReturnType; import { ServicesPreferencesModel } from "@pagopa/io-functions-commons/dist/src/models/service_preference"; + import { some, none } from "fp-ts/lib/Option"; -import { fromLeft, taskEither } from "fp-ts/lib/TaskEither"; +import { pipe } from "fp-ts/lib/function"; +import * as E from "fp-ts/lib/Either"; +import * as TE from "fp-ts/lib/TaskEither"; +import * as O from "fp-ts/lib/Option"; + import { UserGroup } from "@pagopa/io-functions-commons/dist/src/utils/middlewares/azure_api_auth"; import { initTelemetryClient } from "../appinsights"; @@ -48,13 +53,16 @@ describe("isSenderAllowed", () => { const result = await isSenderAllowedLegacy( blockedInboxOrChannels, "01234567890" as NonEmptyString - ).run(); + )(); - result.fold( - _ => fail("Unexpected failure"), - isAllowed => { - expect(isAllowed).toBe(false); - } + pipe( + result, + E.fold( + _ => fail("Unexpected failure"), + isAllowed => { + expect(isAllowed).toBe(false); + } + ) ); }); @@ -64,13 +72,16 @@ describe("isSenderAllowed", () => { const result = await isSenderAllowedLegacy( blockedInboxOrChannels, "01234567890" as NonEmptyString - ).run(); + )(); - result.fold( - _ => fail("Unexpected failure"), - isAllowed => { - expect(isAllowed).toBe(true); - } + pipe( + result, + E.fold( + _ => fail("Unexpected failure"), + isAllowed => { + expect(isAllowed).toBe(true); + } + ) ); }); }); @@ -112,7 +123,7 @@ const aRetrievedProfileWithAutoPreferences = { }; const mockProfileFindLast = jest.fn(() => - taskEither.of(some(aRetrievedProfileWithLegacyPreferences)) + TE.of(some(aRetrievedProfileWithLegacyPreferences)) ); const mockProfileModel = ({ findLastVersionByModelId: mockProfileFindLast @@ -155,11 +166,9 @@ describe("getLimitedProfileTask", () => { `( "should $allowOrNot a sender if the user uses $mode subscription mode and $preferencesConfiguration", async ({ maybeProfile, maybePreference, expected }) => { - mockProfileFindLast.mockImplementationOnce(() => - taskEither.of(maybeProfile) - ); + mockProfileFindLast.mockImplementationOnce(() => TE.of(maybeProfile)); mockServicePreferenceFind.mockImplementationOnce(() => - taskEither.of(maybePreference) + TE.of(maybePreference) ); const result = await getLimitedProfileTask( @@ -171,7 +180,7 @@ describe("getLimitedProfileTask", () => { [], mockServicePreferenceModel, mockTelemetryClient - ).run(); + )(); result.apply(mockExpresseResponse); expect(result.kind).toBe("IResponseSuccessJson"); @@ -184,9 +193,9 @@ describe("getLimitedProfileTask", () => { it.each` scenario | responseKind | maybeProfile - ${"the requested profile does not have the inbox enabled"} | ${"IResponseErrorNotFound"} | ${taskEither.of(some({ ...aRetrievedProfile, isInboxEnabled: false }))} - ${"the requested profile is not found in the db"} | ${"IResponseErrorNotFound"} | ${taskEither.of(none)} - ${"a database error occurs"} | ${"IResponseErrorQuery"} | ${fromLeft({})} + ${"the requested profile does not have the inbox enabled"} | ${"IResponseErrorNotFound"} | ${TE.of(some({ ...aRetrievedProfile, isInboxEnabled: false }))} + ${"the requested profile is not found in the db"} | ${"IResponseErrorNotFound"} | ${TE.of(none)} + ${"a database error occurs"} | ${"IResponseErrorQuery"} | ${TE.left({})} `( "should respond with $responseKind when $scenario", async ({ responseKind, maybeProfile }) => { @@ -205,7 +214,7 @@ describe("getLimitedProfileTask", () => { [], mockServicePreferenceModel, mockTelemetryClient - ).run(); + )(); expect(mockProfileModel.findLastVersionByModelId).toHaveBeenCalledTimes( 1 @@ -225,9 +234,7 @@ describe("getLimitedProfileTask", () => { "should respond with 403 IResponseErrorForbiddenNotAuthorizedForRecipient when $scenario", async ({ groups, service }) => { const mockProfileModel = ({ - findLastVersionByModelId: jest.fn(() => - taskEither.of(some(aRetrievedProfile)) - ) + findLastVersionByModelId: jest.fn(() => TE.of(some(aRetrievedProfile))) } as unknown) as ProfileModel; const response = await getLimitedProfileTask( { @@ -248,7 +255,7 @@ describe("getLimitedProfileTask", () => { [], mockServicePreferenceModel, mockTelemetryClient - ).run(); + )(); expect(mockProfileModel.findLastVersionByModelId).not.toHaveBeenCalled(); diff --git a/yarn.lock b/yarn.lock index b4adc0de..a54e4edd 100644 --- a/yarn.lock +++ b/yarn.lock @@ -739,16 +739,22 @@ eslint-plugin-sonarjs "^0.5.0" prettier "^2.1.2" -"@pagopa/io-functions-commons@../../commons/io-functions-commons/pagopa-io-functions-commons-21.0.0.tgz": - version "21.0.0" - resolved "../../commons/io-functions-commons/pagopa-io-functions-commons-21.0.0.tgz#ca4396f60b0a6c1ca0bfa266cfdad76acd6830fe" +"@pagopa/express-azure-functions@^2.0.0": + version "2.0.0" + resolved "https://registry.yarnpkg.com/@pagopa/express-azure-functions/-/express-azure-functions-2.0.0.tgz#eb52a0b997d931c1509372e2a9bea22a8ca85c17" + integrity sha512-IFZqtk0e2sfkMZIxYqPORzxcKRkbIrVJesR6eMLNwzh1rA4bl2uh9ZHk1m55LNq4ZmaxREDu+1JcGlIaZQgKNQ== + +"@pagopa/io-functions-commons@^21.0.0": + version "21.1.1" + resolved "https://registry.yarnpkg.com/@pagopa/io-functions-commons/-/io-functions-commons-21.1.1.tgz#d43e28f1d0d4151c2b713a4a616219fabaf0180d" + integrity sha512-tdGRCvQjxf8u/yIoaRtOdRystAcOniXn/u1V0jcEQHRnICQhCQtp9N31JDzfd8iVU5UAUhf2C8EEsTZOlex93g== dependencies: "@azure/cosmos" "^3.11.5" - "@pagopa/ts-commons" "^10.0.0" + "@pagopa/ts-commons" "^10.0.1" applicationinsights "^1.8.10" azure-storage "^2.10.4" cidr-matcher "^2.1.1" - fp-ts "^2.11.1" + fp-ts "^2.10.5" helmet "^4.6.0" helmet-csp "^2.5.1" io-ts "^2.2.16" @@ -762,14 +768,15 @@ remark-rehype "^3.0.0" request-ip "^2.1.3" ulid "^2.3.0" - unified "^9.2.1" + unified "^9.2.2" winston "^3.1.0" -"@pagopa/openapi-codegen-ts@../../utils/openapi-codegen-ts/pagopa-openapi-codegen-ts-9.2.0.tgz": - version "9.2.0" - resolved "../../utils/openapi-codegen-ts/pagopa-openapi-codegen-ts-9.2.0.tgz#93dddfce5f86b0f9efbf4d5af4e6c371084575e3" +"@pagopa/openapi-codegen-ts@^10.0.0": + version "10.0.0" + resolved "https://registry.yarnpkg.com/@pagopa/openapi-codegen-ts/-/openapi-codegen-ts-10.0.0.tgz#8668513fadf42b6dbb4ce61c42fe53aaf8e1cb7e" + integrity sha512-AnY/myxrwTjRHRDYqYHFUdta5xwiatYpTtxFVDx0JNaWmg1ggwf+g8OTiI+hupsOr3NLQ2Xzrqf/5Yuxm3GzFg== dependencies: - "@pagopa/ts-commons" "../../commons/io-ts-commons/pagopa-ts-commons-10.0.0.tgz" + "@pagopa/ts-commons" "^10.0.0" fs-extra "^6.0.0" nunjucks "^3.2.2" prettier "^1.12.1" @@ -778,10 +785,10 @@ write-yaml-file "^4.1.3" yargs "^11.1.0" -"@pagopa/ts-commons@^9.2.0", "@pagopa/ts-commons@^9.5.1", "@pagopa/ts-commons@^9.6.0": - version "9.6.0" - resolved "https://registry.yarnpkg.com/@pagopa/ts-commons/-/ts-commons-9.6.0.tgz#dbc837e8afa0aa66ab174d49757321a9fe18e416" - integrity sha512-GrXz6qFtBeRPS7reVxLEze6OvHUNMlCp4Ksbqwijl8xdkXD9ETCgU+9nKjGSPS6fOz2pUIOuIcts72HX7wlGmA== +"@pagopa/ts-commons@^10.0.0", "@pagopa/ts-commons@^10.0.1": + version "10.0.1" + resolved "https://registry.yarnpkg.com/@pagopa/ts-commons/-/ts-commons-10.0.1.tgz#086ae8067405f7d95802e6727a93167698ee3525" + integrity sha512-Hl4dEpXjqSniXxpGxPaYhzgV2MeDxYa1PeHt4Wsg9vctjzkb2KHkSlegQtdyPMnV3wKHx01HqepOxEXt0uGoKA== dependencies: abort-controller "^3.0.0" agentkeepalive "^4.1.4" @@ -3911,11 +3918,6 @@ invert-kv@^2.0.0: resolved "https://registry.yarnpkg.com/invert-kv/-/invert-kv-2.0.0.tgz#7393f5afa59ec9ff5f67a27620d11c226e3eec02" integrity sha512-wPVv/y/QQ/Uiirj/vh3oP+1Ww+AWehmi1g5fFWGPF6IpCBCDVrhgHRMvrLfdYcwDh3QJbGXDW4JAuzxElLSqKA== -io-functions-express@^0.1.1: - version "0.1.1" - resolved "https://registry.yarnpkg.com/io-functions-express/-/io-functions-express-0.1.1.tgz#6ae954fe89ec1d797c5e5d10eca5e77f08ff4a4d" - integrity sha512-Co7sovRyB0lxgU6NFh5v72Apude3XbgKQtqA7slryvKoEqLAvlnLU7DtsYVoF62O3ZJdtSHYf9JWuhDc/di1mg== - io-ts@^2.2.16: version "2.2.16" resolved "https://registry.yarnpkg.com/io-ts/-/io-ts-2.2.16.tgz#597dffa03db1913fc318c9c6df6931cb4ed808b2" @@ -7598,7 +7600,7 @@ unherit@^1.0.4: inherits "^2.0.0" xtend "^4.0.0" -unified@^9.2.1: +unified@^9.2.2: version "9.2.2" resolved "https://registry.yarnpkg.com/unified/-/unified-9.2.2.tgz#67649a1abfc3ab85d2969502902775eb03146975" integrity sha512-Sg7j110mtefBD+qunSLO1lqOEKdrwBFBrR6Qd8f4uwkhWNlbkaqwHse6e7QvD3AP/MNoJdEDLaf8OxYyoWgorQ==