UNPKG

@mojaloop/ml-schema-transformer-lib

Version:
1 lines 16.7 kB
{"version":3,"sources":["../../../src/lib/validation/index.ts","../../../src/types/index.ts","../../../src/lib/validation/validator.ts"],"sourcesContent":["/*****\n License\n --------------\n Copyright © 2020-2025 Mojaloop Foundation\n The Mojaloop files are made available by the Mojaloop Foundation under the Apache License, Version 2.0 (the \"License\") and you may not use these files except in compliance with the License. You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, the Mojaloop files are distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.\n\n Contributors\n --------------\n This is the official list of the Mojaloop project contributors for this file.\n Names of the original copyright holders (individuals or organizations)\n should be listed with a '*' in the first column. People who have\n contributed from an organization can be listed under the organization\n that actually holds the copyright for their contributions (see the\n Mojaloop Foundation for an example). Those individuals should have\n their names indented and be marked with a '-'. Email address can be added\n optionally within square brackets <email>.\n\n * Mojaloop Foundation\n - Name Surname <name.surname@mojaloop.io>\n \n * Steven Oderayi <steven.oderayi@infitx.com>\n --------------\n ******/\n\nimport path from 'path';\nimport NodeCache from 'node-cache';\nimport { ContextLogger } from '@mojaloop/central-services-logger/src/contextLogger';\nimport { API_NAME, GenericObject, HTTP_METHOD } from '../../types';\nimport { Validator } from './validator';\n\nconst validatorsCache = new NodeCache();\n\nexport const getApiSpecPath = (apiName: API_NAME, version: string): string => {\n let specFile: string;\n\n switch (apiName) {\n case API_NAME.FSPIOP:\n specFile = `../docs/fspiop-rest-v${version}-openapi3-snippets.yaml`;\n break;\n case API_NAME.ISO20022:\n specFile = `../docs/fspiop-rest-v${version}-ISO20022-openapi3-snippets.yaml`;\n break;\n default:\n throw new Error(`Invalid API name: ${apiName} in getApiSpecPath`);\n }\n\n const specPath = path.join(path.dirname(require.resolve('@mojaloop/api-snippets')), specFile);\n return specPath;\n}\n\n/**\n * Returns true or throws if the target object fails validation against the API spec\n */\nexport const validateBody = async (body: GenericObject, spec: { name: API_NAME, version: string, path: string, method: HTTP_METHOD }): Promise<boolean> => {\n const apiSpecPath = getApiSpecPath(spec.name, spec.version);\n\n let validator: Validator = validatorsCache.get(apiSpecPath) as Validator;\n if (!validator) {\n validator = new Validator(apiSpecPath);\n await validator.initialize();\n validatorsCache.set(apiSpecPath, validator);\n }\n\n return validator.validateBody({ body, path: spec.path, method: spec.method }) as boolean;\n}\n \nexport const applyTargetValidation = async (params: { source: GenericObject, target: GenericObject, options: GenericObject, logger: ContextLogger }) => {\n const { target, options, logger } = params;\n\n if (!options.validateTarget) {\n logger.debug('Skipping target validation', { target, options });\n return target;\n }\n\n const targetSpec = options.applyTargetValidation?.targetSpec;\n if (!targetSpec || !targetSpec.name || !targetSpec.path || !targetSpec.method) {\n logger.error('Missing or invalid targetSpec in applyTargetValidation options', { target, targetSpec });\n throw new Error('Missing or invalid targetSpec in applyTargetValidation options');\n }\n\n await validateBody(target.body, targetSpec);\n\n return target;\n}\n","/*****\n License\n --------------\n Copyright © 2020-2025 Mojaloop Foundation\n The Mojaloop files are made available by the Mojaloop Foundation under the Apache License, Version 2.0 (the \"License\") and you may not use these files except in compliance with the License. You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, the Mojaloop files are distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.\n\n Contributors\n --------------\n This is the official list of the Mojaloop project contributors for this file.\n Names of the original copyright holders (individuals or organizations)\n should be listed with a '*' in the first column. People who have\n contributed from an organization can be listed under the organization\n that actually holds the copyright for their contributions (see the\n Mojaloop Foundation for an example). Those individuals should have\n their names indented and be marked with a '-'. Email address can be added\n optionally within square brackets <email>.\n\n * Mojaloop Foundation\n - Name Surname <name.surname@mojaloop.io>\n \n * Steven Oderayi <steven.oderayi@infitx.com>\n --------------\n ******/\n\nimport { ContextLogger } from '@mojaloop/central-services-logger/src/contextLogger';\nimport { AsyncTransformer, Options, State, TransformDefinition, Transformer } from './map-transform';\n\nexport enum HTTP_METHOD {\n GET = 'GET',\n PUT = 'PUT',\n POST = 'POST',\n DELETE = 'DELETE',\n PATCH = 'PATCH'\n}\n\nexport enum API_NAME {\n FSPIOP = 'fspiop',\n ISO20022 = 'iso'\n}\n\nexport interface ITransformer {\n transform(source: Partial<Source>, { mapperOptions }: { mapperOptions?: State }): Promise<Partial<Target>>;\n}\n\nexport type FacadeOptions = { overrideMapping?: TransformDefinition, mapTransformOptions?: Options, mapperOptions?: State, validateTarget?: boolean };\n\nexport type FspiopFacadeOptions = FacadeOptions & { unrollExtensions?: boolean };\nexport type FspiopFacadeFunction = (source: Source, options: FacadeOptions) => Promise<IsoTarget>;\nexport type IsoFacadeOptions = FacadeOptions & { rollUpUnmappedAsExtensions?: boolean };\nexport type IsoFacadeFunction = (source: IsoSource, options: FacadeOptions) => Promise<Partial<Target>>;\n\nexport type TransformFunctionOptions = { mapping: TransformDefinition, mapperOptions?: State, mapTransformOptions?: Options, logger: ContextLogger };\nexport type CreateTransformerOptions = { mapTransformOptions?: Options };\n\nexport enum ID_GENERATOR_TYPE {\n ulid = 'ulid',\n uuid = 'uuid'\n}\n\nexport interface ICustomTransforms {\n [key: string | symbol]: Transformer | AsyncTransformer\n}\n\nexport type ConfigOptions = {\n logger?: ContextLogger;\n isTestingMode?: boolean;\n unrollExtensions?: boolean;\n rollUpUnmappedAsExtensions?: boolean;\n validateTarget?: boolean;\n}\n\nexport type Headers = {\n 'fspiop-source': string;\n 'fspiop-destination': string;\n}\n\nexport type Params = {\n Type?: string;\n ID?: string;\n SubId?: string;\n}\n\nexport type PartyIdParamsSource = {\n Type: string;\n ID: string;\n SubId?: string;\n IdPath?: string; // format: IdType/IdValue or IdType/IdValue/SubIdValue\n} | {\n Type?: string;\n ID?: string;\n SubId?: string;\n IdPath: string; // format: IdType/IdValue or IdType/IdValue/SubIdValue\n}\n\nexport type PartyIdParamsTarget = {\n Type: string;\n ID: string;\n SubId?: string;\n}\n\nexport type Source = {\n body: GenericObject;\n headers?: Headers;\n params?: Partial<Params>;\n}\n\nexport type Target = {\n body: GenericObject;\n headers: Headers;\n params: Params;\n};\n\nexport type FspiopSource = Pick<Source, 'body'>;\nexport type FspiopTarget = Pick<Target, 'body'>;\nexport type FspiopPutQuotesSource = { body: GenericObject, params: Pick<Params, 'ID'>, $context?: { isoPostQuote: GenericObject }, headers?: Headers } | {body: GenericObject, params: Pick<Params, 'ID'>, headers: Headers, $context?: { isoPostQuote: GenericObject } };\nexport type FspiopPutQuotesTarget = { body: GenericObject, headers: Headers, params: Pick<Params, 'ID'> };\nexport type FspiopPutPartiesSource = { body: GenericObject, headers: Headers, params: PartyIdParamsSource };\nexport type FspiopPutPartiesTarget = { body: GenericObject, headers: Headers, params: PartyIdParamsTarget };\nexport type FspiopPutPartiesErrorSource = { body: GenericObject, headers: Headers, params: PartyIdParamsSource };\nexport type FspiopPutPartiesErrorTarget = { body: GenericObject, headers: Headers, params: PartyIdParamsTarget };\nexport type FspiopPostTransfersSource = { body: GenericObject, $context?: { isoPostQuoteResponse: GenericObject }, headers?: Headers } | {body: GenericObject, params: Pick<Params, 'ID'>, headers: Headers, $context?: { isoPostQuoteResponse: GenericObject } };\n\nexport type IsoSource = Pick<Source, 'body'>;\nexport type IsoTarget = Pick<Target, 'body'>;\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\nexport type GenericObject = Record<string, any>;\nexport type Primitive = string | number | boolean;\n\n// Pipeline types\nexport type PipelineStep = ({ source, target, options, logger }: { source: GenericObject, target: GenericObject, options: GenericObject, logger: ContextLogger }) => GenericObject;\nexport type PipelineStepsConfig = { [key: string]: GenericObject };\nexport type PipelineOptions = {\n pipelineSteps: PipelineStep[];\n logger: ContextLogger;\n [key: string]: any;\n}\n\n\nexport type Json = string | number | boolean | Json[] | { [key: string]: Json };\nexport type LogContext = Json | string | null;\nexport const logLevelsMap = {\n error: 'error',\n warn: 'warn',\n info: 'info',\n verbose: 'verbose',\n debug: 'debug',\n silly: 'silly',\n audit: 'audit',\n trace: 'trace',\n perf: 'perf',\n} as const;\n\nexport const logLevelValues = Object.values(logLevelsMap);\nexport type LogLevel = (typeof logLevelValues)[number];\nexport * from './type-guards';\n\nexport type Request = {\n path: string;\n method: HTTP_METHOD;\n headers: GenericObject;\n body: GenericObject;\n query: GenericObject;\n}\n\n","/*****\n License\n --------------\n Copyright © 2020-2025 Mojaloop Foundation\n The Mojaloop files are made available by the Mojaloop Foundation under the Apache License, Version 2.0 (the \"License\") and you may not use these files except in compliance with the License. You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, the Mojaloop files are distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.\n\n Contributors\n --------------\n This is the official list of the Mojaloop project contributors for this file.\n Names of the original copyright holders (individuals or organizations)\n should be listed with a '*' in the first column. People who have\n contributed from an organization can be listed under the organization\n that actually holds the copyright for their contributions (see the\n Mojaloop Foundation for an example). Those individuals should have\n their names indented and be marked with a '-'. Email address can be added\n optionally within square brackets <email>.\n\n * Mojaloop Foundation\n - Name Surname <name.surname@mojaloop.io>\n\n * Infitx\n - Steven Oderayi <steven.oderayi@infitx.com>\n --------------\n ******/\n\nimport SwaggerParser from '@apidevtools/swagger-parser';\nimport { OpenAPIValidator, Document } from 'openapi-backend';\nimport { ErrorObject, Options } from 'ajv';\nimport stringify from 'fast-safe-stringify';\nimport { Request } from '../../types';\n\nexport class Validator {\n apiDoc: string;\n apiSpec: Document;\n apiValidator: OpenAPIValidator;\n ajvOpts: Options = { allErrors: true, coerceTypes: true, strict: false }\n\n /**\n * @param apiDoc - The path to the OpenAPI document or the document itself\n */\n constructor(apiDoc: string) {\n this.apiDoc = apiDoc;\n this.apiSpec = {} as Document;\n this.apiValidator = {} as OpenAPIValidator;\n }\n\n async initialize() {\n this.apiSpec = await SwaggerParser.validate(this.apiDoc) as Document;\n this.apiValidator = new OpenAPIValidator({ definition: this.apiSpec, ajvOpts: this.ajvOpts });\n }\n\n validateRequest(request: Request, returnErrors: boolean = false): boolean | ErrorObject[] {\n const validation = this.apiValidator.validateRequest(request);\n\n if (validation.errors && validation.errors.length > 0) {\n if (returnErrors) return validation.errors;\n throw new Error(`Validation errors: ${stringify(validation.errors)}`);\n }\n\n return true;\n }\n\n validateBody(partialRequest: Pick<Request, 'body' | 'path' | 'method'>, returnErrors: boolean = false): boolean | ErrorObject[] {\n const { body, path, method } = partialRequest;\n const validation = this.apiValidator.validateRequest({ path, method, body, headers: {} });\n\n if (validation.errors) {\n const bodyErrors = validation.errors.filter((error: any) => error.instancePath === '/requestBody');\n if (bodyErrors && bodyErrors.length > 0) {\n if (returnErrors) return bodyErrors;\n throw new Error(`Validation errors: ${stringify(bodyErrors)}`);\n }\n }\n\n return true;\n }\n\n validateHeaders(partialRequest: Pick<Request, 'headers' | 'path' | 'method'>, returnErrors: boolean = false): boolean | ErrorObject[] {\n const { headers, path, method } = partialRequest;\n const validation = this.apiValidator.validateRequest({ path, method, headers, body: {} });\n\n if (validation.errors) {\n const headersErrors = validation.errors.filter((error: any) => error.instancePath === '/header');\n if (headersErrors && headersErrors.length > 0) {\n if (returnErrors) return headersErrors;\n throw new Error(`Validation errors: ${stringify(headersErrors)}`);\n }\n }\n\n return true;\n }\n}\n"],"mappings":";;;;;;;;AA4BA,OAAO,UAAU;AACjB,OAAO,eAAe;;;ACoHf,IAAM,eAAe;AAAA,EAC1B,OAAO;AAAA,EACP,MAAM;AAAA,EACN,MAAM;AAAA,EACN,SAAS;AAAA,EACT,OAAO;AAAA,EACP,OAAO;AAAA,EACP,OAAO;AAAA,EACP,OAAO;AAAA,EACP,MAAM;AACR;AAEO,IAAM,iBAAiB,OAAO,OAAO,YAAY;;;AChIxD,OAAO,mBAAmB;AAC1B,SAAS,wBAAkC;AAE3C,O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