diff --git a/src/configuration/__tests__/configuration.test.ts b/src/configuration/__tests__/configuration.test.ts index 6617ca3..4421baa 100644 --- a/src/configuration/__tests__/configuration.test.ts +++ b/src/configuration/__tests__/configuration.test.ts @@ -1,7 +1,7 @@ import * as E from "fp-ts/Either"; import { Configuration } from "../../types/configuration/configuration"; import { - JSON_CONF_VAR_NAME, + CONFIG_VAR_NAME, decodeConfiguration, readAndParseEnv, } from "../service"; @@ -13,10 +13,9 @@ jest.mock("../../types/configuration/configuration", () => ({ })); const jsonData = { key: "value" }; -const jsonFileContent = JSON.stringify(jsonData); beforeAll(() => { - process.env[JSON_CONF_VAR_NAME] = jsonFileContent; + process.env[CONFIG_VAR_NAME] = JSON.stringify(jsonData); }); describe("readAndParseEnv", () => { @@ -29,7 +28,7 @@ describe("readAndParseEnv", () => { }); it("should return Left with error if reading or parsing fails", () => { - process.env[JSON_CONF_VAR_NAME] = "invalid-json"; + process.env[CONFIG_VAR_NAME] = "invalid-json"; const result = readAndParseEnv(); diff --git a/src/configuration/service.ts b/src/configuration/service.ts index d25bd9d..be7436a 100644 --- a/src/configuration/service.ts +++ b/src/configuration/service.ts @@ -1,27 +1,32 @@ /* eslint-disable no-console */ +import { errorsToReadableMessages } from "@pagopa/ts-commons/lib/reporters"; import * as E from "fp-ts/Either"; +import * as J from "fp-ts/Json"; import { pipe } from "fp-ts/lib/function"; import * as t from "io-ts"; import { NonEmptyString } from "io-ts-types/lib/NonEmptyString"; import { Configuration } from "../types/configuration/configuration"; -export const JSON_CONF_VAR_NAME = "JSON_CONFIGURATION"; -export type JSONConfiguration = t.TypeOf; -export const JSONConfiguration = t.type({ - JSON_CONFIGURATION: NonEmptyString, +export const CONFIG_VAR_NAME = "CONFIGURATION"; +export type EnvConfiguration = t.TypeOf; +export const EnvConfiguration = t.type({ + CONFIGURATION: NonEmptyString, }); -export const getConfigOrThrow = (): E.Either => +export const getConfigOrThrow = (): E.Either => pipe( - E.tryCatch( - () => - JSONConfiguration.decode({ - ...process.env, - }), - E.toError, - ), - E.getOrElse(() => { - throw new Error(`Invalid configuration`); + EnvConfiguration.decode({ + ...process.env, + CONFIGURATION: pipe( + process.env[CONFIG_VAR_NAME], + J.parse, + E.getOrElse(() => ""), + ), + }), + E.mapLeft((errs) => { + throw new Error( + `Invalid configuration|ERROR=${errorsToReadableMessages(errs)}`, + ); }), ); @@ -31,7 +36,7 @@ export const readAndParseEnv = (): E.Either => E.chain((conf) => E.tryCatch(() => { console.log(conf); - return JSON.parse(conf.JSON_CONFIGURATION); + return JSON.parse(conf.CONFIGURATION); }, E.toError), ), E.mapLeft(() => new Error(`Error during JSON reading`)),