From a8ccdcd09ec3a4907804eb6d6a0e836a1e98aad3 Mon Sep 17 00:00:00 2001 From: Ricardo Gomez_Ulmke Date: Sat, 4 Mar 2023 05:02:34 +0100 Subject: [PATCH 01/33] bump version --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index e54fb5a35..dfc5cef59 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@solace-labs/solace-tools-typescript", - "version": "2.9.5", + "version": "2.9.6", "private": true, "workspaces": [ "packages/*" From 2463aa37389a8af0d4ccd1701a81f35dd23c6384 Mon Sep 17 00:00:00 2001 From: Ricardo Gomez_Ulmke Date: Sat, 4 Mar 2023 08:48:18 +0100 Subject: [PATCH 02/33] init integration tests --- packages/integration-tests/.gitignore | 2 + packages/integration-tests/.mocharc.yml | 12 + packages/integration-tests/README.md | 3 + packages/integration-tests/package.json | 21 + packages/integration-tests/source.env.sh | 37 ++ packages/integration-tests/src/.gitignore | 1 + packages/integration-tests/src/compiler.ts | 3 + .../integration-tests/src/data/xml-schema.xsd | 51 +++ .../src/lib/EpSdkPinoLogger.ts | 83 ++++ .../integration-tests/src/lib/TestConfig.ts | 36 ++ .../integration-tests/src/lib/TestLogger.ts | 18 + .../integration-tests/src/lib/TestService.ts | 104 +++++ .../src/lib/TestStubEpCoreOpenApi.ts | 52 +++ .../src/lib/customOpenApiRequest.ts | 370 ++++++++++++++++++ packages/integration-tests/src/lib/index.ts | 4 + packages/integration-tests/src/setup.spec.ts | 71 ++++ .../ep-xml-schema/ep-xml-schema-api.x-spec.ts | 212 ++++++++++ packages/integration-tests/tsconfig.json | 31 ++ 18 files changed, 1111 insertions(+) create mode 100644 packages/integration-tests/.gitignore create mode 100644 packages/integration-tests/.mocharc.yml create mode 100644 packages/integration-tests/README.md create mode 100644 packages/integration-tests/package.json create mode 100644 packages/integration-tests/source.env.sh create mode 100644 packages/integration-tests/src/.gitignore create mode 100644 packages/integration-tests/src/compiler.ts create mode 100644 packages/integration-tests/src/data/xml-schema.xsd create mode 100644 packages/integration-tests/src/lib/EpSdkPinoLogger.ts create mode 100644 packages/integration-tests/src/lib/TestConfig.ts create mode 100644 packages/integration-tests/src/lib/TestLogger.ts create mode 100644 packages/integration-tests/src/lib/TestService.ts create mode 100644 packages/integration-tests/src/lib/TestStubEpCoreOpenApi.ts create mode 100644 packages/integration-tests/src/lib/customOpenApiRequest.ts create mode 100644 packages/integration-tests/src/lib/index.ts create mode 100644 packages/integration-tests/src/setup.spec.ts create mode 100644 packages/integration-tests/src/specs/ep-xml-schema/ep-xml-schema-api.x-spec.ts create mode 100644 packages/integration-tests/tsconfig.json diff --git a/packages/integration-tests/.gitignore b/packages/integration-tests/.gitignore new file mode 100644 index 000000000..de4d1f007 --- /dev/null +++ b/packages/integration-tests/.gitignore @@ -0,0 +1,2 @@ +dist +node_modules diff --git a/packages/integration-tests/.mocharc.yml b/packages/integration-tests/.mocharc.yml new file mode 100644 index 000000000..9abe2a8aa --- /dev/null +++ b/packages/integration-tests/.mocharc.yml @@ -0,0 +1,12 @@ +require: +- ./src/compiler.ts +file: + - src/setup.spec.ts +timeout: 180000 +bail: true +exit: true +parallel: false +extension: + - 'ts' +full-trace: true +diff: true diff --git a/packages/integration-tests/README.md b/packages/integration-tests/README.md new file mode 100644 index 000000000..1e6801382 --- /dev/null +++ b/packages/integration-tests/README.md @@ -0,0 +1,3 @@ +# integration tests + +internal integration tests. diff --git a/packages/integration-tests/package.json b/packages/integration-tests/package.json new file mode 100644 index 000000000..898d166b7 --- /dev/null +++ b/packages/integration-tests/package.json @@ -0,0 +1,21 @@ +{ + "name": "@internal/integration-tests", + "version": "0.1.0", + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "license": "Apache-2.0", + "private": true, + "scripts": { + "compile": "tsc", + "build": "tsc", + "clean": "rm -rf dist && rm -rf .turbo", + "build:test": "yarn build", + "test:x": "yarn build:test && . ./source.env.sh && mocha --config .mocharc.yml src/**/**.x-spec.ts && unset_source_env" + }, + "dependencies": {}, + "devDependencies": { + "@solace-labs/ep-openapi-node": "^2.53.0", + "@solace-labs/ep-sdk": "0.56.1", + "@solace-labs/ep-asyncapi": "0.53.2" + } +} diff --git a/packages/integration-tests/source.env.sh b/packages/integration-tests/source.env.sh new file mode 100644 index 000000000..c4fbda69b --- /dev/null +++ b/packages/integration-tests/source.env.sh @@ -0,0 +1,37 @@ +# +# Environment for tests +# +# Usage: +# source source.env.sh && {run-tests} && unset_source_env + +unset_source_env() { + # env vars for tests + unset INTEGRATION_TESTS_EP_SDK_LOG_LEVEL + unset INTEGRATION_TESTS_ENABLE_API_CALL_LOGGING + unset INTEGRATION_TESTS_SOLACE_CLOUD_TOKEN + # unset this function + unset -f unset_source_env +} +# export enum EEpSdkLogLevel { +# Silent = 0, +# FatalError = 1, +# Error = 2, +# Warn = 3, +# Info = 4, +# Debug = 5, +# Trace = 6, +# } +export INTEGRATION_TESTS_EP_SDK_LOG_LEVEL=0 +export INTEGRATION_TESTS_ENABLE_API_CALL_LOGGING="true" + +###################################################### + +NOLOG_INTEGRATION_TESTS_SOLACE_CLOUD_TOKEN=$INTEGRATION_TESTS_SOLACE_CLOUD_TOKEN +export INTEGRATION_TESTS_SOLACE_CLOUD_TOKEN="***" + +logName='[source.env.sh]' +echo "$logName - test environment:" +echo "$logName - INTEGRATION_TESTS_:" +export -p | sed 's/declare -x //' | grep INTEGRATION_TESTS_ + +export INTEGRATION_TESTS_SOLACE_CLOUD_TOKEN=$NOLOG_INTEGRATION_TESTS_SOLACE_CLOUD_TOKEN diff --git a/packages/integration-tests/src/.gitignore b/packages/integration-tests/src/.gitignore new file mode 100644 index 000000000..98d8a5a63 --- /dev/null +++ b/packages/integration-tests/src/.gitignore @@ -0,0 +1 @@ +logs diff --git a/packages/integration-tests/src/compiler.ts b/packages/integration-tests/src/compiler.ts new file mode 100644 index 000000000..076c22033 --- /dev/null +++ b/packages/integration-tests/src/compiler.ts @@ -0,0 +1,3 @@ +require('ts-node').register({ + project: './tsconfig.json' +}); \ No newline at end of file diff --git a/packages/integration-tests/src/data/xml-schema.xsd b/packages/integration-tests/src/data/xml-schema.xsd new file mode 100644 index 000000000..12efaf14b --- /dev/null +++ b/packages/integration-tests/src/data/xml-schema.xsd @@ -0,0 +1,51 @@ + + + + + + + + + + + + + + + + + + + + + + + ComplexType1 + + + + + doc for elem1 + + + + + doc for elem2 + + + + + + + + + + + diff --git a/packages/integration-tests/src/lib/EpSdkPinoLogger.ts b/packages/integration-tests/src/lib/EpSdkPinoLogger.ts new file mode 100644 index 000000000..fe2f50630 --- /dev/null +++ b/packages/integration-tests/src/lib/EpSdkPinoLogger.ts @@ -0,0 +1,83 @@ +import pino from 'pino'; +import { + EEpSdkLogLevel, + IEpSdkLoggerInstance, + IEpSdkLogDetails, + IEpSdkLogEntry +} from "@solace-labs/ep-sdk"; + + +export class EpSdkPinoLogger implements IEpSdkLoggerInstance { + appId: string; + epSdkLogLevel: EEpSdkLogLevel; + static logLevelMap: Map = new Map([ + // [EEpSdkLogLevel.Silent, "silent"], + [EEpSdkLogLevel.Error, "error"], + [EEpSdkLogLevel.Warn, "warn"], + [EEpSdkLogLevel.Info, "info"], + [EEpSdkLogLevel.Debug, "debug"], + [EEpSdkLogLevel.Trace, "trace"], + ]); + + public static L = pino({ + name: "ep-sdk-test", + level: "info", + }); + + private static getPinoLevel = (epSdkLogLevel: EEpSdkLogLevel): string => { + let pinoLogLevel: string | undefined = EpSdkPinoLogger.logLevelMap.get(epSdkLogLevel); + if(pinoLogLevel === undefined) throw new TypeError(`${EpSdkPinoLogger.name}: cannot find pino log level mapping for epSdkLogLevel=${epSdkLogLevel}`); + return pinoLogLevel; + } + + constructor(appId: string, epSdkLogLevel: EEpSdkLogLevel) { + this.appId = appId; + this.epSdkLogLevel = epSdkLogLevel; + EpSdkPinoLogger.L = pino({ + name: appId, + level: EpSdkPinoLogger.getPinoLevel(epSdkLogLevel) + }); + } + + public setLogLevel(epSdkLogLevel: EEpSdkLogLevel) { + EpSdkPinoLogger.L.level = EpSdkPinoLogger.getPinoLevel(epSdkLogLevel); + } + + public createLogEntry = (logName: string, details: IEpSdkLogDetails): IEpSdkLogEntry => { + const d = new Date(); + return { + logger: EpSdkPinoLogger.name, + appId: this.appId, + logName: logName, + timestamp: d.toUTCString(), + ...details + }; + } + + public fatal = (logEntry: IEpSdkLogEntry): void => { + EpSdkPinoLogger.L.fatal(logEntry); + } + + public error = (logEntry: IEpSdkLogEntry): void => { + EpSdkPinoLogger.L.error(logEntry); + } + + public warn = (logEntry: IEpSdkLogEntry): void => { + if(this.epSdkLogLevel > EEpSdkLogLevel.Silent) EpSdkPinoLogger.L.warn(logEntry); + } + + public info = (logEntry: IEpSdkLogEntry): void => { + if(this.epSdkLogLevel > EEpSdkLogLevel.Silent) EpSdkPinoLogger.L.info(logEntry); + } + + public debug = (logEntry: IEpSdkLogEntry): void => { + if(this.epSdkLogLevel > EEpSdkLogLevel.Silent) EpSdkPinoLogger.L.debug(logEntry); + } + + public trace = (logEntry: IEpSdkLogEntry): void => { + if(this.epSdkLogLevel > EEpSdkLogLevel.Silent) EpSdkPinoLogger.L.trace(logEntry); + } + + +} + diff --git a/packages/integration-tests/src/lib/TestConfig.ts b/packages/integration-tests/src/lib/TestConfig.ts new file mode 100644 index 000000000..61e6bc18c --- /dev/null +++ b/packages/integration-tests/src/lib/TestConfig.ts @@ -0,0 +1,36 @@ + +import { + ITestSolaceCloudApiConfigBase, + TestSolaceCloudApiConfigBase, +} from '@internal/tools/src/testLib'; +import { EEpSdkLogLevel } from '@solace-labs/ep-sdk'; + +enum EEnvVarPartials { + EP_SDK_LOG_LEVEL = "EP_SDK_LOG_LEVEL", +}; + +export interface ITestConfig extends ITestSolaceCloudApiConfigBase { + dataRootDir: string; + epSdkLogLevel: EEpSdkLogLevel; +}; + +class TestConfig extends TestSolaceCloudApiConfigBase { + + public init({ scriptDir }: { scriptDir: string }): void { + super.initialize({ + appId: 'INTEGRATION_TESTS', + }); + const _testConfig: ITestConfig = { + ...(this.testConfig as ITestSolaceCloudApiConfigBase), + dataRootDir: this.getValidatedReadDir(`${scriptDir}/data`), + epSdkLogLevel: this.getMandatoryEnvVarValueAsNumber(this.createEnvVar({ envVarPartial: EEnvVarPartials.EP_SDK_LOG_LEVEL }) + ), + }; + this.testConfig = _testConfig; + } + + public getConfig(): ITestConfig { return super.getConfig() as ITestConfig; } + +} + +export default new TestConfig(); \ No newline at end of file diff --git a/packages/integration-tests/src/lib/TestLogger.ts b/packages/integration-tests/src/lib/TestLogger.ts new file mode 100644 index 000000000..5ff1cc23e --- /dev/null +++ b/packages/integration-tests/src/lib/TestLogger.ts @@ -0,0 +1,18 @@ +import { + TestContext, + TestLoggerBase +} from "@internal/tools/src"; +import { EpSdkError } from "@solace-labs/ep-sdk"; + + +export class TestLogger extends TestLoggerBase { + + public static createNotEpSdkErrorMessage = (e: Error): string => { + return `[${TestContext.getItId()}]: error is not an instance of EpSdkError, name=${e.name}, message=${e.message}`; + } + public static createEpSdkTestFailMessage = (message: string, epSdkError: EpSdkError): string => { + return `[${TestContext.getItId()}]: message=${message}, epSdkError=${epSdkError}`; + } + +} + diff --git a/packages/integration-tests/src/lib/TestService.ts b/packages/integration-tests/src/lib/TestService.ts new file mode 100644 index 000000000..19d38ca03 --- /dev/null +++ b/packages/integration-tests/src/lib/TestService.ts @@ -0,0 +1,104 @@ +import { expect } from "chai"; +import { + ApiError, +} from "@solace-labs/ep-openapi-node"; +import { + EEpSdkTask_TargetState, + EpSdkApplicationDomainTask, + EpSdkEpEventTask, + EpSdkSchemaTask, + IEpSdkEpEventTask_ExecuteReturn, + IEpSdkSchemaTask_ExecuteReturn, + EpSdkEventApiTask, + IEpSdkEventApiTask_ExecuteReturn +} from "@solace-labs/ep-sdk"; +import { TestLogger } from "./TestLogger"; + +export class TestService { + + public static applicationDomainAbsent = async({ applicationDomainName }: { + applicationDomainName: string; + }): Promise => { + const funcName = "applicationDomainAbsent"; + const logName = `${TestService.name}.${funcName}()`; + try { + const epSdkApplicationDomainTask = new EpSdkApplicationDomainTask({ + applicationDomainName: applicationDomainName, + epSdkTask_TargetState: EEpSdkTask_TargetState.ABSENT, + }); + const epSdkApplicationDomainTask_ExecuteReturn = await epSdkApplicationDomainTask.execute('xContextId'); + return undefined; + } catch (e) { + expect(e instanceof ApiError, TestLogger.createNotApiErrorMessage(`${logName}: ${e.message}`)).to.be.true; + expect(false, TestLogger.createApiTestFailMessage(logName, e)).to.be.true; + } + }; + + public static applicationDomainPresent = async({ applicationDomainName }: { + applicationDomainName: string; + }): Promise => { + const funcName = "applicationDomainPresent"; + const logName = `${TestService.name}.${funcName}()`; + try { + const epSdkApplicationDomainTask = new EpSdkApplicationDomainTask({ + applicationDomainName: applicationDomainName, + epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, + }); + const epSdkApplicationDomainTask_ExecuteReturn = await epSdkApplicationDomainTask.execute('xContextId'); + if(epSdkApplicationDomainTask_ExecuteReturn.epObject.id === undefined) throw new Error('epSdkApplicationDomainTask_ExecuteReturn.epObject.id === undefined'); + return epSdkApplicationDomainTask_ExecuteReturn.epObject.id; + } catch (e) { + expect(e instanceof ApiError, TestLogger.createNotApiErrorMessage(`${logName}: ${e.message}`)).to.be.true; + expect(false, TestLogger.createApiTestFailMessage(logName, e)).to.be.true; + } + }; + + public static schemaAbsent = async({ applicationDomainId, schemaName }:{ + applicationDomainId: string; + schemaName: string; + }): Promise => { + const funcName = "schemaAbsent"; + const logName = `${TestService.name}.${funcName}()`; + try { + const epSdkSchemaTask = new EpSdkSchemaTask({ epSdkTask_TargetState: EEpSdkTask_TargetState.ABSENT, applicationDomainId, schemaName }); + const epSdkSchemaTask_ExecuteReturn: IEpSdkSchemaTask_ExecuteReturn = await epSdkSchemaTask.execute('xContextId'); + return undefined; + } catch (e) { + expect(e instanceof ApiError, TestLogger.createNotApiErrorMessage(`${logName}: ${e.message}`)).to.be.true; + expect(false, TestLogger.createApiTestFailMessage(logName, e)).to.be.true; + } + } + + public static eventAbsent = async({ applicationDomainId, eventName }:{ + applicationDomainId: string; + eventName: string; + }): Promise => { + const funcName = "eventAbsent"; + const logName = `${TestService.name}.${funcName}()`; + try { + const epSdkEpEventTask = new EpSdkEpEventTask({ epSdkTask_TargetState: EEpSdkTask_TargetState.ABSENT, applicationDomainId, eventName }); + const epSdkEpEventTask_ExecuteReturn: IEpSdkEpEventTask_ExecuteReturn = await epSdkEpEventTask.execute('xContextId'); + return undefined; + } catch (e) { + expect(e instanceof ApiError, TestLogger.createNotApiErrorMessage(`${logName}: ${e.message}`)).to.be.true; + expect(false, TestLogger.createApiTestFailMessage(logName, e)).to.be.true; + } + } + + public static eventApiAbsent = async({ applicationDomainId, eventApiName }:{ + applicationDomainId: string; + eventApiName: string; + }): Promise => { + const funcName = "eventApiAbsent"; + const logName = `${TestService.name}.${funcName}()`; + try { + const epSdkEventApiTask = new EpSdkEventApiTask({ epSdkTask_TargetState: EEpSdkTask_TargetState.ABSENT, applicationDomainId, eventApiName }); + const epSdkEventApiTask_ExecuteReturn: IEpSdkEventApiTask_ExecuteReturn = await epSdkEventApiTask.execute('xContextId'); + return undefined; + } catch (e) { + expect(e instanceof ApiError, TestLogger.createNotApiErrorMessage(`${logName}: ${e.message}`)).to.be.true; + expect(false, TestLogger.createApiTestFailMessage(logName, e)).to.be.true; + } + } + +} diff --git a/packages/integration-tests/src/lib/TestStubEpCoreOpenApi.ts b/packages/integration-tests/src/lib/TestStubEpCoreOpenApi.ts new file mode 100644 index 000000000..9b61ad345 --- /dev/null +++ b/packages/integration-tests/src/lib/TestStubEpCoreOpenApi.ts @@ -0,0 +1,52 @@ +import * as sinon from "sinon"; +import { + TestContext, + ApiRequestOptions +} from "@internal/tools/src"; +import { + CancelablePromise, + OpenAPIConfig, + ApiResult, +} from "@solace-labs/ep-openapi-node"; +import * as __requestLib from "@solace-labs/ep-openapi-node/dist/core/request"; +import { customRequest } from "./customOpenApiRequest"; +import TestConfig from "./TestConfig"; +import { TestLogger } from "./TestLogger"; + +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +// Stubbing global request from openapi +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +// export const request = (config: OpenAPIConfig, options: ApiRequestOptions): CancelablePromise => { +const stub = sinon.stub(__requestLib, "request"); +stub.callsFake((config: OpenAPIConfig, options: ApiRequestOptions): CancelablePromise => { + +// stub.callsFake( +// ( +// config: OpenAPIConfig, +// options: ApiRequestOptions +// ): CancelablePromise => { + TestContext.setApiRequestOptions(options); + if (TestConfig.getConfig().enableApiLogging) TestLogger.logApiRequestOptions(TestContext.getItId(), options); + + TestContext.setApiResult(undefined); + TestContext.setApiError(undefined); + + // const cancelablePromise = stub.wrappedMethod(config, options) as CancelablePromise; + // call my own request + const cancelablePromise: CancelablePromise = customRequest(config, options) as CancelablePromise; + + cancelablePromise.then((value: ApiResult) => { + TestContext.setApiResult(value); + if (TestConfig.getConfig().enableApiLogging) TestLogger.logApiResult(TestContext.getItId(), TestContext.getApiResult()); + }, (reason) => { + TestContext.setApiError(reason); + if(!TestConfig.getConfig().enableApiLogging) { + TestLogger.logApiRequestOptions(TestContext.getItId(), options); + TestLogger.logApiResult(TestContext.getItId(), TestContext.getApiResult()); + } + TestLogger.logApiError(TestContext.getItId(), TestContext.getApiError()); + } + ); + return cancelablePromise as unknown as CancelablePromise; + } +); diff --git a/packages/integration-tests/src/lib/customOpenApiRequest.ts b/packages/integration-tests/src/lib/customOpenApiRequest.ts new file mode 100644 index 000000000..5b49b5d0d --- /dev/null +++ b/packages/integration-tests/src/lib/customOpenApiRequest.ts @@ -0,0 +1,370 @@ +/* istanbul ignore file */ +/* tslint:disable */ +/* eslint-disable */ +import { AbortController } from "abort-controller"; +import FormData from "form-data"; +import fetch, { BodyInit, Headers, RequestInit, Response } from "node-fetch"; + +import { + ApiError, + CancelablePromise, + OpenAPIConfig, + OnCancel, + ApiResult, + ApiRequestOptions, +} from "@solace-labs/ep-openapi-node"; + +const isDefined = ( + value: T | null | undefined +): value is Exclude => { + return value !== undefined && value !== null; +}; + +const isString = (value: any): value is string => { + return typeof value === "string"; +}; + +const isStringWithValue = (value: any): value is string => { + return isString(value) && value !== ""; +}; + +const isBlob = (value: any): value is Blob => { + return ( + typeof value === "object" && + typeof value.type === "string" && + typeof value.stream === "function" && + typeof value.arrayBuffer === "function" && + typeof value.constructor === "function" && + typeof value.constructor.name === "string" && + /^(Blob|File)$/.test(value.constructor.name) && + /^(Blob|File)$/.test(value[Symbol.toStringTag]) + ); +}; + +const isFormData = (value: any): value is FormData => { + return value instanceof FormData; +}; + +const base64 = (str: string): string => { + try { + return btoa(str); + } catch (err) { + // @ts-ignore + return Buffer.from(str).toString("base64"); + } +}; + +const getQueryString = (params: Record): string => { + const qs: string[] = []; + + const append = (key: string, value: any) => { + qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`); + }; + + const process = (key: string, value: any) => { + if (isDefined(value)) { + if (Array.isArray(value)) { + value.forEach((v) => { + process(key, v); + }); + } else if (typeof value === "object") { + Object.entries(value).forEach(([k, v]) => { + process(`${key}[${k}]`, v); + }); + } else { + append(key, value); + } + } + }; + + Object.entries(params).forEach(([key, value]) => { + process(key, value); + }); + + if (qs.length > 0) { + return `?${qs.join("&")}`; + } + + return ""; +}; + +const getUrl = (config: OpenAPIConfig, options: ApiRequestOptions): string => { + const encoder = config.ENCODE_PATH || encodeURI; + + const path = options.url + .replace("{api-version}", config.VERSION) + .replace(/{(.*?)}/g, (substring: string, group: string) => { + if (options.path?.hasOwnProperty(group)) { + return encoder(String(options.path[group])); + } + return substring; + }); + + const url = `${config.BASE}${path}`; + if (options.query) { + return `${url}${getQueryString(options.query)}`; + } + return url; +}; + +const getFormData = (options: ApiRequestOptions): FormData | undefined => { + if (options.formData) { + const formData = new FormData(); + + const process = (key: string, value: any) => { + if (isString(value) || isBlob(value)) { + formData.append(key, value); + } else { + formData.append(key, JSON.stringify(value)); + } + }; + + Object.entries(options.formData) + .filter(([_, value]) => isDefined(value)) + .forEach(([key, value]) => { + if (Array.isArray(value)) { + value.forEach((v) => process(key, v)); + } else { + process(key, value); + } + }); + + return formData; + } + return undefined; +}; + +type Resolver = (options: ApiRequestOptions) => Promise; + +const resolve = async ( + options: ApiRequestOptions, + resolver?: T | Resolver +): Promise => { + if (typeof resolver === "function") { + return (resolver as Resolver)(options); + } + return resolver; +}; + +const getHeaders = async ( + config: OpenAPIConfig, + options: ApiRequestOptions +): Promise => { + const token = await resolve(options, config.TOKEN); + const username = await resolve(options, config.USERNAME); + const password = await resolve(options, config.PASSWORD); + const additionalHeaders = await resolve(options, config.HEADERS); + + const headers = Object.entries({ + Accept: "application/json", + ...additionalHeaders, + ...options.headers, + }) + .filter(([_, value]) => isDefined(value)) + .reduce( + (headers, [key, value]) => ({ + ...headers, + [key]: String(value), + }), + {} as Record + ); + + if (isStringWithValue(token)) { + headers["Authorization"] = `Bearer ${token}`; + } + + if (isStringWithValue(username) && isStringWithValue(password)) { + const credentials = base64(`${username}:${password}`); + headers["Authorization"] = `Basic ${credentials}`; + } + + if (options.body) { + if (options.mediaType) { + headers["Content-Type"] = options.mediaType; + } else if (isBlob(options.body)) { + headers["Content-Type"] = "application/octet-stream"; + } else if (isString(options.body)) { + headers["Content-Type"] = "text/plain"; + } else if (!isFormData(options.body)) { + headers["Content-Type"] = "application/json"; + } + } + + return new Headers(headers); +}; + +const getRequestBody = (options: ApiRequestOptions): any => { + if (options.body) { + if (options.mediaType?.includes("/json")) { + return JSON.stringify(options.body); + } else if ( + isString(options.body) || + isBlob(options.body) || + isFormData(options.body) + ) { + return options.body as any; + } else { + return JSON.stringify(options.body); + } + } + return; +}; + +export const sendRequest = async ( + options: ApiRequestOptions, + url: string, + body: any, + formData: FormData | undefined, + headers: Headers, + onCancel: OnCancel +): Promise => { + const controller = new AbortController(); + + const request: RequestInit = { + headers, + method: options.method, + body: body ?? formData, + signal: controller.signal, + }; + + onCancel(() => controller.abort()); + + return await fetch(url, request); +}; + +const getResponseHeader = ( + response: Response, + responseHeader?: string +): string | undefined => { + if (responseHeader) { + const content = response.headers.get(responseHeader); + if (isString(content)) { + return content; + } + } + return undefined; +}; + +const getResponseBody = async (response: Response): Promise => { + if (response.status !== 204) { + try { + const contentType = response.headers.get("Content-Type"); + if (contentType) { + const isJSON = contentType.toLowerCase().startsWith("application/json"); + if (isJSON) { + return await response.json(); + } else { + return await response.text(); + } + } + } catch (error) { + console.error(error); + } + } + return; +}; + +const catchErrorCodes = ( + options: ApiRequestOptions, + result: ApiResult +): void => { + const errors: Record = { + 400: "Bad Request", + 401: "Unauthorized", + 403: "Forbidden", + 404: "Not Found", + 500: "Internal Server Error", + 502: "Bad Gateway", + 503: "Service Unavailable", + ...options.errors, + }; + + const error = errors[result.status]; + if (error) { + throw new ApiError(result, error); + } + + if (!result.ok) { + throw new ApiError(result, "Generic Error"); + } +}; + +// ******************************************************************************************************** +// CUSTOM CODE FROM HERE +// ******************************************************************************************************** + +function parseCookies(response: Response) { + const raw = response.headers.raw()["set-cookie"]; + // console.log(`\n\n\nOpenApi.parseCookies(): raw=${JSON.stringify(raw, null, 2)}`); + if (raw === undefined) return undefined; + return raw + .map((entry) => { + const parts = entry.split(";"); + const cookiePart = parts[0]; + return cookiePart; + }) + .join(";"); +} + +/** + * Request method + * @param config The OpenAPI configuration object + * @param options The request options from the service + * @returns CancelablePromise + * @throws ApiError + */ +export const customRequest = ( + config: OpenAPIConfig, + options: ApiRequestOptions +): CancelablePromise => { + return new CancelablePromise(async (resolve, reject, onCancel) => { + try { + const url = getUrl(config, options); + const formData = getFormData(options); + const body = getRequestBody(options); + const headers = await getHeaders(config, options); + + if (!onCancel.isCancelled) { + const response = await sendRequest( + options, + url, + body, + formData, + headers, + onCancel + ); + + // console.log(`\n\n\n ------- BEGIN customRequest:`); + // console.log(`customRequest(): response.headers=${JSON.stringify(response.headers.raw(), null, 2)}`); + + const cookies = parseCookies(response); + + // console.log(`customRequest(): cookies=${cookies}`); + + // ApimServerAPIClient.setRefreshToken( { value: cookies }); + + // console.log(`END customRequest ------- \n\n\n`); + + const responseBody = await getResponseBody(response); + const responseHeader = getResponseHeader( + response, + options.responseHeader + ); + + const result: ApiResult = { + url, + ok: response.ok, + status: response.status, + statusText: response.statusText, + body: responseHeader ?? responseBody, + }; + + catchErrorCodes(options, result); + + resolve(result.body); + } + } catch (error) { + reject(error); + } + }); +}; diff --git a/packages/integration-tests/src/lib/index.ts b/packages/integration-tests/src/lib/index.ts new file mode 100644 index 000000000..2bf3ba808 --- /dev/null +++ b/packages/integration-tests/src/lib/index.ts @@ -0,0 +1,4 @@ +export * from './TestLogger'; +export * from './EpSdkPinoLogger'; +export { default as TestConfig } from './TestConfig'; +export * from './TestService'; diff --git a/packages/integration-tests/src/setup.spec.ts b/packages/integration-tests/src/setup.spec.ts new file mode 100644 index 000000000..1b3f82057 --- /dev/null +++ b/packages/integration-tests/src/setup.spec.ts @@ -0,0 +1,71 @@ +import "mocha"; +import path from "path"; +import { expect } from "chai"; +import { OpenAPI as EpCoreOpenAPI } from "@solace-labs/ep-openapi-node"; +import { TestContext } from "@internal/tools/src"; +import { TestConfig, TestLogger } from "./lib"; +import { + EpSdkClient, + EpSdkConsoleLogger, + EpSdkLogger, + EpSdkConfig, +} from "@solace-labs/ep-sdk"; + +// load test stub +const x = require("./lib/TestStubEpCoreOpenApi"); + +// ensure any unhandled exception cause exit = 1 +function onUncaught(err: any) { + console.log(err); + process.exit(1); +} +process.on("unhandledRejection", onUncaught); + +const scriptName: string = path.basename(__filename); +const scriptDir: string = path.dirname(__filename); + +TestLogger.setLogging(true); +TestLogger.logMessage(scriptName, ">>> initializing ..."); + +before(async () => { + TestContext.newItId(); +}); + +after(async () => { + TestContext.newItId(); + // put general cleanup code here if required +}); + +describe(`${scriptName}`, () => { + context(`${scriptName}`, () => { + beforeEach(() => { + TestContext.newItId(); + }); + + it(`${scriptName}: should initialize test config & logger`, async () => { + try { + TestConfig.init({ scriptDir: scriptDir }); + const epSdkConsoleLogger: EpSdkConsoleLogger = new EpSdkConsoleLogger( + TestConfig.getAppId(), + TestConfig.getConfig().epSdkLogLevel + ); + EpSdkLogger.initialize({ epSdkLoggerInstance: epSdkConsoleLogger }); + EpSdkConfig.initialize(TestConfig.getAppId()); + } catch (e) { + expect(false, TestLogger.createTestFailMessageForError("intitializing test config failed",e)).to.be.true; + } + }); + + it(`${scriptName}: should initialize EP client`, async () => { + try { + EpSdkClient.initialize({ + globalOpenAPI: EpCoreOpenAPI, + token: TestConfig.getSolaceCloudToken(), + baseUrl: TestConfig.getConfig().apiBaseUrl, + }); + } catch (e) { + expect(false, TestLogger.createTestFailMessageForError("initializing ep client", e)).to.be.true; + } + }); + }); +}); diff --git a/packages/integration-tests/src/specs/ep-xml-schema/ep-xml-schema-api.x-spec.ts b/packages/integration-tests/src/specs/ep-xml-schema/ep-xml-schema-api.x-spec.ts new file mode 100644 index 000000000..0d60aebf1 --- /dev/null +++ b/packages/integration-tests/src/specs/ep-xml-schema/ep-xml-schema-api.x-spec.ts @@ -0,0 +1,212 @@ +import "mocha"; +import { expect } from "chai"; +import path from "path"; +import fs from 'fs'; +import { TestContext, TestUtils } from "@internal/tools/src"; +import { TestLogger, TestConfig, TestService } from "../../lib"; +import { + ApiError, + EventApIsService +} from "@solace-labs/ep-openapi-node"; +import { + EEpSdkSchemaContentType, + EEpSdkSchemaType, + EEpSdkTask_TargetState, + EpSdkEpEventTask, + EpSdkEpEventVersionTask, + EpSdkSchemaTask, + EpSdkSchemaVersionTask, + EpSdkStatesService, + IEpSdkEpEventTask_ExecuteReturn, + IEpSdkEpEventVersionTask_ExecuteReturn, + IEpSdkSchemaTask_ExecuteReturn, + IEpSdkSchemaVersionTask_ExecuteReturn, + EpSdkEventApiTask, + IEpSdkEventApiTask_ExecuteReturn, + EpSdkEventApiVersionTask, + IEpSdkEventApiVersionTask_ExecuteReturn +} from "@solace-labs/ep-sdk"; + + +const scriptName: string = path.basename(__filename); +TestLogger.logMessage(scriptName, ">>> starting ..."); +const TestSpecName = scriptName; +const TestSpecId = TestUtils.getShortUUID(); + +let ApplicationDomainName: string; +let ApplicationDomainId: string | undefined; +let SchemaName: string; +let SchemaId: string | undefined; +let SchemaVersionId: string | undefined; +let SchemaContentXSD: string; +let EventName: string; +let EventId: string; +let EventVersionId: string; +let EventApiName: string; +let EventApiId: string; +let EventApiVersionId: string; + +const initializeGlobals = () => { + ApplicationDomainName = `${TestConfig.getAppId()}/${TestSpecName}`; + SchemaName = ApplicationDomainName; + SchemaContentXSD = TestUtils.readFile(`${TestConfig.getConfig().dataRootDir}/xml-schema.xsd`); + EventName = ApplicationDomainName; + EventApiName = ApplicationDomainName; +} + +describe(`${scriptName}`, () => { + + before(async() => { + TestContext.newItId(); + initializeGlobals(); + ApplicationDomainId = await TestService.applicationDomainAbsent({ applicationDomainName: ApplicationDomainName }); + ApplicationDomainId = await TestService.applicationDomainPresent({ applicationDomainName: ApplicationDomainName }); + // EventApiId = await TestService.eventApiAbsent({ applicationDomainId: ApplicationDomainId, eventApiName: EventApiName }); + // EventId = await TestService.eventAbsent({ applicationDomainId: ApplicationDomainId, eventName: EventName }); + // SchemaId = await TestService.schemaAbsent({ applicationDomainId: ApplicationDomainId, schemaName: SchemaName }); + }); + + beforeEach(() => { + TestContext.newItId(); + }); + + after(async() => { + TestContext.newItId(); + ApplicationDomainId = await TestService.applicationDomainAbsent({ applicationDomainName: ApplicationDomainName }); + }); + + it(`${scriptName}: create xsd/xml schema`, async () => { + try { + const epSdkSchemaTask = new EpSdkSchemaTask({ + epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, + applicationDomainId: ApplicationDomainId, + schemaName: SchemaName, + schemaObjectSettings: { + shared: true, + contentType: EEpSdkSchemaContentType.APPLICATION_XML, + schemaType: EEpSdkSchemaType.XSD + }, + }); + const epSdkSchemaTask_ExecuteReturn: IEpSdkSchemaTask_ExecuteReturn = await epSdkSchemaTask.execute('xContextId'); + SchemaId = epSdkSchemaTask_ExecuteReturn.epObject.id; + } catch (e) { + expect(e instanceof ApiError, TestLogger.createNotApiErrorMessage(e.message)).to.be.true; + expect(false, TestLogger.createApiTestFailMessage("failed", e)).to.be.true; + } + }); + + it(`${scriptName}: create xml schema version`, async () => { + try { + const epSdkSchemaVersionTask = new EpSdkSchemaVersionTask({ + epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, + applicationDomainId: ApplicationDomainId, + schemaId: SchemaId, + versionString: "0.1.0", + schemaVersionSettings: { + stateId: EpSdkStatesService.releasedId, + displayName: 'xml schema', + description: "description", + content: SchemaContentXSD, + }, + }); + const epSdkSchemaVersionTask_ExecuteReturn: IEpSdkSchemaVersionTask_ExecuteReturn = await epSdkSchemaVersionTask.execute('xContextId'); + SchemaVersionId = epSdkSchemaVersionTask_ExecuteReturn.epObject.id; + } catch (e) { + expect(e instanceof ApiError, TestLogger.createNotApiErrorMessage(e.message)).to.be.true; + expect(false, TestLogger.createApiTestFailMessage("failed", e)).to.be.true; + } + }); + + it(`${scriptName}: create event`, async () => { + try { + const epSdkEpEventTask = new EpSdkEpEventTask({ + epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, + applicationDomainId: ApplicationDomainId, + eventName: EventName, + eventObjectSettings: { shared: true }, + }); + const epSdkEpEventTask_ExecuteReturn: IEpSdkEpEventTask_ExecuteReturn = await epSdkEpEventTask.execute('xContextId'); + EventId = epSdkEpEventTask_ExecuteReturn.epObject.id; + } catch (e) { + expect(e instanceof ApiError, TestLogger.createNotApiErrorMessage(e.message)).to.be.true; + expect(false, TestLogger.createApiTestFailMessage("failed", e)).to.be.true; + } + }); + + it(`${scriptName}: create event version`, async () => { + try { + const epSdkEpEventVersionTask = new EpSdkEpEventVersionTask({ + epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, + applicationDomainId: ApplicationDomainId, + eventId: EventId, + versionString: "0.1.0", + topicString: "test/xml/event", + eventVersionSettings: { + stateId: EpSdkStatesService.releasedId, + description: "description", + displayName: "displayName", + schemaVersionId: SchemaVersionId, + }, + }); + const epSdkEpEventVersionTask_ExecuteReturn: IEpSdkEpEventVersionTask_ExecuteReturn = await epSdkEpEventVersionTask.execute('xContextId'); + EventVersionId = epSdkEpEventVersionTask_ExecuteReturn.epObject.id; + } catch (e) { + expect(e instanceof ApiError, TestLogger.createNotApiErrorMessage(e.message)).to.be.true; + expect(false, TestLogger.createApiTestFailMessage("failed", e)).to.be.true; + } + }); + + it(`${scriptName}: create event api`, async () => { + try { + const epSdkEventApiTask = new EpSdkEventApiTask({ + epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, + applicationDomainId: ApplicationDomainId, + eventApiName: EventApiName, + eventApiObjectSettings: { shared: true }, + }); + const epSdkEventApiTask_ExecuteReturn: IEpSdkEventApiTask_ExecuteReturn = await epSdkEventApiTask.execute('xContextId'); + EventApiId = epSdkEventApiTask_ExecuteReturn.epObject.id; + } catch (e) { + expect(e instanceof ApiError, TestLogger.createNotApiErrorMessage(e.message)).to.be.true; + expect(false, TestLogger.createApiTestFailMessage("failed", e)).to.be.true; + } + }); + + it(`${scriptName}: create event api version`, async () => { + try { + const epSdkEventApiVersionTask = new EpSdkEventApiVersionTask({ + epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, + applicationDomainId: ApplicationDomainId, + eventApiId: EventApiId, + versionString: "0.1.0", + eventApiVersionSettings: { + stateId: EpSdkStatesService.releasedId, + description: "description", + displayName: "displayName", + producedEventVersionIds: [EventVersionId], + consumedEventVersionIds: [EventVersionId], + } + }); + const epSdkEventApiVersionTask_ExecuteReturn: IEpSdkEventApiVersionTask_ExecuteReturn = await epSdkEventApiVersionTask.execute('xContextId'); + EventApiVersionId = epSdkEventApiVersionTask_ExecuteReturn.epObject.id; + } catch (e) { + expect(e instanceof ApiError, TestLogger.createNotApiErrorMessage(e.message)).to.be.true; + expect(false, TestLogger.createApiTestFailMessage("failed", e)).to.be.true; + } + }); + + it(`${scriptName}: get event api async api`, async () => { + try { + const asyncApiStr: string = await EventApIsService.getAsyncApiForEventApiVersion({ + xContextId: 'xContextId', + eventApiVersionId: EventApiVersionId, + }); + // parse it + // get the zip file + } catch (e) { + expect(e instanceof ApiError, TestLogger.createNotApiErrorMessage(e.message)).to.be.true; + expect(false, TestLogger.createApiTestFailMessage("failed", e)).to.be.true; + } + }); + +}); diff --git a/packages/integration-tests/tsconfig.json b/packages/integration-tests/tsconfig.json new file mode 100644 index 000000000..96fb10a38 --- /dev/null +++ b/packages/integration-tests/tsconfig.json @@ -0,0 +1,31 @@ +{ + "compileOnSave": false, + "compilerOptions": { + "target":"es2021", + "module": "commonjs", + "lib": ["es2021", "dom"], + "declaration": true, + "strict": false, + "noImplicitAny": false, + "esModuleInterop": true, + "moduleResolution": "node", + "strictNullChecks": false, + "noImplicitThis": true, + "alwaysStrict": true, + "noUnusedLocals": false, + "noUnusedParameters": true, + "noImplicitReturns": false, + "noFallthroughCasesInSwitch": false, + "skipLibCheck": true, + "sourceMap": true, + "strictPropertyInitialization":false, + "resolveJsonModule": true, + "outDir": "dist", + "allowSyntheticDefaultImports": true, + "typeRoots": [ + "../node_modules/@types" + ] + }, + "include": ["src/**/*.ts"], + "exclude": ["node_modules"] +} From 3e7f1b30a71e5e030176e164da7f96ebd47575ea Mon Sep 17 00:00:00 2001 From: Ricardo Gomez_Ulmke Date: Sat, 4 Mar 2023 08:48:40 +0100 Subject: [PATCH 03/33] integration tests --- .changeset/ep-sdk.md | 8 +++++++ .changeset/wet-bananas-obey.md | 5 +++++ package.json | 1 + .../src/services/EpSdkSchemasService.ts | 2 ++ .../testLib/TestSolaceCloudApiConfigBase.ts | 4 +--- packages/tools/src/testLib/TestUtils.ts | 21 +++++++++++++++++++ turbo.json | 5 +++++ 7 files changed, 43 insertions(+), 3 deletions(-) create mode 100644 .changeset/ep-sdk.md create mode 100644 .changeset/wet-bananas-obey.md diff --git a/.changeset/ep-sdk.md b/.changeset/ep-sdk.md new file mode 100644 index 000000000..80ad13807 --- /dev/null +++ b/.changeset/ep-sdk.md @@ -0,0 +1,8 @@ +--- +"@solace-labs/ep-sdk": minor +--- + +added support for XML + +- new: `EEpSdkSchemaType.XSD` +- new: `EEpSdkSchemaContentType.APPLICATION_XML` diff --git a/.changeset/wet-bananas-obey.md b/.changeset/wet-bananas-obey.md new file mode 100644 index 000000000..44ba0f9d7 --- /dev/null +++ b/.changeset/wet-bananas-obey.md @@ -0,0 +1,5 @@ +--- +"@internal/tools": minor +--- + +added integration test functionality diff --git a/package.json b/package.json index dfc5cef59..1e3970fa1 100644 --- a/package.json +++ b/package.json @@ -14,6 +14,7 @@ "build": "turbo run build && yarn typedoc && ./docs/make.sh", "build:test": "turbo run build:test", "test": "turbo run test", + "test:x": "turbo run test:x", "dev:watch": "turbo run dev:watch", "lint": "turbo run lint", "lint:deprecated": "turbo run lint:deprecated", diff --git a/packages/ep-sdk/src/services/EpSdkSchemasService.ts b/packages/ep-sdk/src/services/EpSdkSchemasService.ts index 4cf66b63f..c3423812c 100644 --- a/packages/ep-sdk/src/services/EpSdkSchemasService.ts +++ b/packages/ep-sdk/src/services/EpSdkSchemasService.ts @@ -16,10 +16,12 @@ import { EpSdkServiceClass } from "./EpSdkService"; export enum EEpSdkSchemaType { JSON_SCHEMA = "jsonSchema", AVRO = "avro", + XSD = "xsd", } /** @category Services */ export enum EEpSdkSchemaContentType { APPLICATION_JSON = "json", + APPLICATION_XML = "xml" } /** @category Services */ diff --git a/packages/tools/src/testLib/TestSolaceCloudApiConfigBase.ts b/packages/tools/src/testLib/TestSolaceCloudApiConfigBase.ts index d54a683b4..700df14da 100644 --- a/packages/tools/src/testLib/TestSolaceCloudApiConfigBase.ts +++ b/packages/tools/src/testLib/TestSolaceCloudApiConfigBase.ts @@ -20,9 +20,7 @@ export class TestSolaceCloudApiConfigBase extends TestApiConfigBase { public initialize({ appId }:{ appId: string; }): void { - super.initialize({ - appId: appId, - }); + super.initialize({ appId: appId }); const _testConfig: ITestSolaceCloudApiConfigBase = { ...(this.testConfig as ITestApiConfigBase), apiBaseUrl: this.getOptionalEnvVarValueAsUrlWithDefault(this.createEnvVar({ envVarPartial: EEnvVarPartials.SOLACE_CLOUD_API_BASE_URL }), this.DEFAULT_SOLACE_CLOUD_API_BASE_URL), diff --git a/packages/tools/src/testLib/TestUtils.ts b/packages/tools/src/testLib/TestUtils.ts index 916ec211c..2549851ae 100644 --- a/packages/tools/src/testLib/TestUtils.ts +++ b/packages/tools/src/testLib/TestUtils.ts @@ -1,5 +1,7 @@ import { v4 as uuidv4 } from 'uuid'; import short from 'short-uuid'; +import fs from 'fs'; +import path from 'path'; // use with // @ts-ignore if getting Type instantiation is excessively deep and possibly infinite. TS2589 type DotPrefix = T extends "" ? "" : `.${T}`; @@ -26,4 +28,23 @@ export class TestUtils { throw new Error(`${logName}:${extLogName}: unexpected object: ${JSON.stringify(x)}`); } + public static validateFilePathWithReadPermission = (filePath: string): string => { + try { + const absoluteFilePath = path.resolve(filePath); + // console.log(`validateFilePathWithReadPermission: absoluteFilePath=${absoluteFilePath}`); + fs.accessSync(absoluteFilePath, fs.constants.R_OK); + return absoluteFilePath; + } catch (e) { + throw e; + // console.log(`validateFilePathWithReadPermission: filePath=${filePath}`); + // console.log(`e=${e}`); + + } + } + + public static readFile =(filePath: string): string => { + const validPath = TestUtils.validateFilePathWithReadPermission(filePath); + return fs.readFileSync(validPath, { encoding: 'utf8'}); + } + } \ No newline at end of file diff --git a/turbo.json b/turbo.json index 9311b8ccc..813482870 100644 --- a/turbo.json +++ b/turbo.json @@ -28,6 +28,11 @@ "outputs": ["logs/**"], "inputs": ["src/**/*.ts", "test/**/*.spec.ts", ".nycrc"] }, + "test:x": { + "dependsOn": ["build:test", "^test:x"], + "outputs": ["logs/**"], + "inputs": ["src/**/*.ts", "test/**/*.x-spec.ts"] + }, "dev:watch": { "dependsOn": ["^dev:watch"], "outputs": ["dist/**", "generated-src/**/*.ts"], From 553e1452ebcc6af1ab51e28b9b46a77e7e3809aa Mon Sep 17 00:00:00 2001 From: Ricardo Gomez_Ulmke Date: Sat, 4 Mar 2023 09:01:40 +0100 Subject: [PATCH 04/33] no build --- packages/integration-tests/package.json | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/packages/integration-tests/package.json b/packages/integration-tests/package.json index 898d166b7..b6ef2a97f 100644 --- a/packages/integration-tests/package.json +++ b/packages/integration-tests/package.json @@ -6,10 +6,8 @@ "license": "Apache-2.0", "private": true, "scripts": { - "compile": "tsc", - "build": "tsc", "clean": "rm -rf dist && rm -rf .turbo", - "build:test": "yarn build", + "build:test": "yarn tsc", "test:x": "yarn build:test && . ./source.env.sh && mocha --config .mocharc.yml src/**/**.x-spec.ts && unset_source_env" }, "dependencies": {}, From d2d5f3c73546aa4865127d38277e85f38678ff9c Mon Sep 17 00:00:00 2001 From: Ricardo Gomez_Ulmke Date: Sat, 11 Mar 2023 09:42:07 +0100 Subject: [PATCH 05/33] multi-domain --- packages/ep-async-api-importer/.gitignore | 1 + packages/ep-async-api-importer/package.json | 1 + .../src/importers/CliEventApiImporter.ts | 8 +- .../test/lib/TestConfig.ts | 2 + .../ep-async-api-importer/test/setup.spec.ts | 24 +- .../test/specs/multi-domain.x-spec.ts | 507 ++++++++++++++++++ .../specs/tasks/schemaVersionTask.spec.ts | 9 +- packages/integration-tests/.gitignore | 1 + packages/integration-tests/package.json | 6 +- packages/integration-tests/src/decs.d.ts | 1 + .../xml-schema-parse.xsd-spec.ts | 81 +++ packages/tools/src/testLib/TestConfigBase.ts | 7 + yarn.lock | 101 +++- 13 files changed, 711 insertions(+), 38 deletions(-) create mode 100644 packages/ep-async-api-importer/test/specs/multi-domain.x-spec.ts create mode 100644 packages/integration-tests/src/decs.d.ts create mode 100644 packages/integration-tests/src/specs/ep-xml-schema/xml-schema-parse.xsd-spec.ts diff --git a/packages/ep-async-api-importer/.gitignore b/packages/ep-async-api-importer/.gitignore index 71554dbed..c22356926 100644 --- a/packages/ep-async-api-importer/.gitignore +++ b/packages/ep-async-api-importer/.gitignore @@ -2,4 +2,5 @@ dist node_modules _todo* logs +tmp output diff --git a/packages/ep-async-api-importer/package.json b/packages/ep-async-api-importer/package.json index 7b9c0e202..c6aad3d42 100644 --- a/packages/ep-async-api-importer/package.json +++ b/packages/ep-async-api-importer/package.json @@ -33,6 +33,7 @@ "clean": "rm -rf dist && rm -rf test/logs && rm -rf .turbo", "build:test": "yarn build", "test": "yarn build:test && . ./test/source.env.sh && nyc mocha --config test/.mocharc.yml test/**/**.spec.ts && unset_source_env", + "test:x": "yarn build:test && . ./test/source.env.sh && nyc mocha --config test/.mocharc.yml test/**/**.x-spec.ts && unset_source_env", "dev:watch": "yarn build --watch", "lint": "eslint .", "lint:deprecated": "yarn lint | grep deprecated", diff --git a/packages/ep-async-api-importer/src/importers/CliEventApiImporter.ts b/packages/ep-async-api-importer/src/importers/CliEventApiImporter.ts index db3f00a8b..7c8c81f36 100644 --- a/packages/ep-async-api-importer/src/importers/CliEventApiImporter.ts +++ b/packages/ep-async-api-importer/src/importers/CliEventApiImporter.ts @@ -489,12 +489,8 @@ export class CliEventApiImporter extends CliAssetsImporter { assetOutputRootDir, "schemas" ); - const asyncApiSpecFileNameJson = - assetOutputRootDir + - "/" + - epAsyncApiDocument.getTitleAsFileName("json"); - const asyncApiSpecFileNameYaml = - assetOutputRootDir + "/" + epAsyncApiDocument.getTitleAsFileName("yml"); + const asyncApiSpecFileNameJson = assetOutputRootDir + "/" + epAsyncApiDocument.getTitleAsFileName("json"); + const asyncApiSpecFileNameYaml = assetOutputRootDir + "/" + epAsyncApiDocument.getTitleAsFileName("yml"); CliLogger.trace(CliLogger.createLogEntry(logName, { code: ECliStatusCodes.GENERATING_ASSETS_OUTPUT, details: { applicationDomainNameAsFilePath: applicationDomainNameAsFilePath, apiTitleAsFilePath: apiTitleAsFilePath, diff --git a/packages/ep-async-api-importer/test/lib/TestConfig.ts b/packages/ep-async-api-importer/test/lib/TestConfig.ts index ad759ebb0..3ec35c4bd 100644 --- a/packages/ep-async-api-importer/test/lib/TestConfig.ts +++ b/packages/ep-async-api-importer/test/lib/TestConfig.ts @@ -10,6 +10,7 @@ enum EEnvVarPartials { export interface ITestConfig extends ITestSolaceCloudApiConfigBase { dataRootDir: string; + tmpDir: string; epSdkLogLevel: EEpSdkLogLevel; } @@ -21,6 +22,7 @@ class TestConfig extends TestSolaceCloudApiConfigBase { const _testConfig: ITestConfig = { ...(this.testConfig as ITestSolaceCloudApiConfigBase), dataRootDir: this.getValidatedReadDir(`${scriptDir}/data`), + tmpDir: this.createReadWriteDir(`${scriptDir}/tmp`), epSdkLogLevel: this.getMandatoryEnvVarValueAsNumber( this.createEnvVar({ envVarPartial: EEnvVarPartials.EP_SDK_LOG_LEVEL }) ), diff --git a/packages/ep-async-api-importer/test/setup.spec.ts b/packages/ep-async-api-importer/test/setup.spec.ts index e02e53dc2..00a0ab70c 100644 --- a/packages/ep-async-api-importer/test/setup.spec.ts +++ b/packages/ep-async-api-importer/test/setup.spec.ts @@ -60,19 +60,11 @@ describe(`${scriptName}`, () => { ); EpSdkLogger.initialize({ epSdkLoggerInstance: epSdkConsoleLogger }); EpSdkConfig.initialize(TestConfig.getAppId()); - console.log( - TestLogger.createLogMessage("TestConfig", { - TestConfig: TestConfig.getConfig(), - }) - ); + console.log(TestLogger.createLogMessage("TestConfig", { + TestConfig: TestConfig.getConfig(), + })); } catch (e) { - expect( - false, - TestLogger.createTestFailMessageForError( - "intitializing test config failed", - e - ) - ).to.be.true; + expect(false, TestLogger.createTestFailMessageForError("intitializing test config failed", e)).to.be.true; } }); @@ -104,12 +96,8 @@ describe(`${scriptName}`, () => { // DEBUG // expect(false, TestLogger.createLogMessage('OpenApi', OpenAPI )).to.be.true; } catch (e) { - expect( - e instanceof CliError, - TestLogger.createNotCliErrorMesssage(e.message) - ).to.be.true; - expect(false, TestLogger.createTestFailMessageWithCliError("failed", e)) - .to.be.true; + expect(e instanceof CliError, TestLogger.createNotCliErrorMesssage(e.message)).to.be.true; + expect(false, TestLogger.createTestFailMessageWithCliError("failed", e)).to.be.true; } }); }); diff --git a/packages/ep-async-api-importer/test/specs/multi-domain.x-spec.ts b/packages/ep-async-api-importer/test/specs/multi-domain.x-spec.ts new file mode 100644 index 000000000..26a0975d5 --- /dev/null +++ b/packages/ep-async-api-importer/test/specs/multi-domain.x-spec.ts @@ -0,0 +1,507 @@ +import "mocha"; +import { expect } from "chai"; +import path from "path"; +import { + EventApi, + EventApIsService, + EventApiVersion, +} from "@solace-labs/ep-openapi-node"; +import { + EEpSdkTask_TargetState, + EpSdkApplicationDomainTask, + EpSdkEnumTask, + EpSdkEnumVersionTask, + EpSdkSchemaTask, + EpSdkSchemaVersionTask, + EpSdkStatesService, + IEpSdkApplicationDomainTask_ExecuteReturn, + IEpSdkEnumTask_ExecuteReturn, + IEpSdkEnumVersionTask_ExecuteReturn, + IEpSdkSchemaTask_ExecuteReturn, + IEpSdkSchemaVersionTask_ExecuteReturn, + EpSdkEpEventTask, + EpSdkBrokerTypes, + IEpSdkEpEventTask_ExecuteReturn, + EpSdkEpEventVersionTask, + IEpSdkEpEventVersionTask_ExecuteReturn, + EpSdkEventApiTask, + IEpSdkEventApiTask_ExecuteReturn, + EpSdkEventApiVersionTask, + IEpSdkEventApiVersionTask_ExecuteReturn, + EpSdkApplicationTask, + IEpSdkApplicationTask_ExecuteReturn, + EpSdkApplicationVersionTask, + IEpSdkApplicationVersionTask_ExecuteReturn, + EpSdkEventApiVersionsService, +} from "@solace-labs/ep-sdk"; +import { TestContext, TestUtils } from "@internal/tools/src"; +import { + TestConfig, + TestLogger, +} from "../lib"; +import { + CliUtils, +} from "../../src/cli-components"; +import { EpAsyncApiDocument, EpAsyncApiDocumentService } from "@solace-labs/ep-asyncapi"; + +const scriptName: string = path.basename(__filename); +const TestSpecName = scriptName; +const TestSpecId = TestUtils.getShortUUID(); +TestLogger.logMessage(scriptName, ">>> starting ..."); + +// TEST expects only 1 api file, not a list of api files. +let FileList: Array = []; +let AsyncApiSpecFile: string; +let AsyncApiSpecFile_X_EpApplicationDomainName: string; +let AsyncApiSpecFile_X_EpAssetApplicationDomainName: string; + + +let ApplicationDomain_Events_1_Name: string; +let ApplicationDomain_Events_1_Id: string | undefined; +let ApplicationDomain_Events_2_Name: string; +let ApplicationDomain_Events_2_Id: string | undefined; +let ApplicationDomain_Main_Name: string; +let ApplicationDomain_Main_Id: string | undefined; + +let Schema_1_Name: string; +let Schema_1_Id: string | undefined; +let SchemaVersion_1_Id: string | undefined; +let Schema_2_Name: string; +let Schema_2_Id: string | undefined; +let SchemaVersion_2_Id: string | undefined; +const SchemaContent = ` +{ + "description": "Generic message header.", + "type": "object", + "properties": { + "sentAt": { + "type": "string", + "format": "date-time", + "description": "Date and time when the message was sent." + }, + "transactionId": { + "type": "string", + "description": "The transaction id." + }, + "storeId": { + "type": "string", + "description": "The store id." + } + }, + "required": [ + "sentAt", + "transactionId", + "storeId" + ] +} +`; + +let Enum_1_Name: string; +let Enum_1_Id: string | undefined; +let EnumVersion_1_Id: string | undefined; +let Enum_2_Name: string; +let Enum_2_Id: string | undefined; +let EnumVersion_2_Id: string | undefined; +const EnumValues = ['value1', 'value2']; + +let Event_1_Name: string; +let Event_1_Id: string | undefined; +let EventVersion_1_Id: string | undefined; +let Event_2_Name: string; +let Event_2_Id: string | undefined; +let EventVersion_2_Id: string | undefined; +let TopicString_1: string; +let TopicString_2: string; + +let EventApi_Name: string; +let EventApi_Id: string | undefined; +let EventApiVersion_Id: string | undefined; +let EventApiSpec: any; + +let App_Name: string; +let App_Id: string | undefined; +let AppVersion_Id: string | undefined; + +let ApplicationDomain_Copy_Name: string; +let ApplicationDomain_Copy_Id: string; + +const initializeGlobals = () => { + ApplicationDomain_Events_1_Name = `${TestConfig.getAppId()}/${TestSpecName}/ApplicationDomain_Events_1_Name`; + ApplicationDomain_Events_2_Name = `${TestConfig.getAppId()}/${TestSpecName}/ApplicationDomain_Events_2_Name`; + ApplicationDomain_Main_Name = `${TestConfig.getAppId()}/${TestSpecName}/ApplicationDomain_Main_Name`; + ApplicationDomain_Copy_Name = `${TestConfig.getAppId()}/${TestSpecName}/ApplicationDomain_Copy_Name`; + + Schema_1_Name = 'Schema_1_Name'; + Schema_2_Name = 'Schema_2_Name'; + + Enum_1_Name = 'Enum_1_Name'; + Enum_2_Name = 'Enum_2_Name'; + + Event_1_Name = 'Event_1_Name'; + Event_2_Name = 'Event_2_Name'; + TopicString_1 = 'topic/{Enum_1_Name}/_1_'; + TopicString_2 = 'topic/{Enum_2_Name}/_2_'; + + EventApi_Name = "EventApi_Name"; + App_Name = "App_Name"; + // AsyncApiSpecFile = TestService.validateFilePathWithReadPermission(`${TestConfig.getConfig().dataRootDir}/individual-tests/asset-domain/asset-domain-1.spec.yml`); + // FileList.push(AsyncApiSpecFile); + // // set test specific importer options + // CliConfig.getCliImporterManagerOptions().asyncApiFileList = FileList; + // CliConfig.getCliImporterManagerOptions().cliImporterManagerMode = ECliImporterManagerMode.RELEASE_MODE; + // // CliConfig.getCliImporterManagerOptions().runId = scriptName; + // // // DEBUG + // // CliConfig.getCliImporterManagerOptions().cliImporterManagerMode = ECliImporterManagerMode.TEST_MODE_KEEP; + // // CliConfig.getCliImporterManagerOptions().applicationDomainName = 'release_mode'; + // CliConfig.getCliImporterManagerOptions().createEventApiApplication = false; + // CliConfig.getCliImporterManagerOptions().cliImporterOptions.cliAssetImport_BrokerType = undefined; + // CliConfig.getCliImporterManagerOptions().cliImporterOptions.cliAssetImport_ChannelDelimiter = undefined; +}; + +const applicationDomainTasks = async(epSdkTask_TargetState: EEpSdkTask_TargetState) => { + const task_1 = new EpSdkApplicationDomainTask({ + applicationDomainName: ApplicationDomain_Events_1_Name, + epSdkTask_TargetState: epSdkTask_TargetState + }); + const task1_ExecuteReturn: IEpSdkApplicationDomainTask_ExecuteReturn = await task_1.execute('xContextId'); + ApplicationDomain_Events_1_Id = task1_ExecuteReturn.epObject.id; + + const task_2 = new EpSdkApplicationDomainTask({ + applicationDomainName: ApplicationDomain_Events_2_Name, + epSdkTask_TargetState: epSdkTask_TargetState + }); + const task2_ExecuteReturn: IEpSdkApplicationDomainTask_ExecuteReturn = await task_2.execute('xContextId'); + ApplicationDomain_Events_2_Id = task2_ExecuteReturn.epObject.id; + + const task_3 = new EpSdkApplicationDomainTask({ + applicationDomainName: ApplicationDomain_Main_Name, + epSdkTask_TargetState: epSdkTask_TargetState + }); + const task3_ExecuteReturn: IEpSdkApplicationDomainTask_ExecuteReturn = await task_3.execute('xContextId'); + ApplicationDomain_Main_Id = task3_ExecuteReturn.epObject.id; + + const task_4 = new EpSdkApplicationDomainTask({ + applicationDomainName: ApplicationDomain_Copy_Name, + epSdkTask_TargetState: epSdkTask_TargetState + }); + const task4_ExecuteReturn: IEpSdkApplicationDomainTask_ExecuteReturn = await task_4.execute('xContextId'); + ApplicationDomain_Copy_Id = task4_ExecuteReturn.epObject.id; +} + +describe(`${scriptName}`, () => { + before(async () => { + TestContext.newItId(); + initializeGlobals(); + }); + + beforeEach(() => { + TestContext.newItId(); + }); + + after(async () => { + TestContext.newItId(); + }); + + it(`${scriptName}: should setup the domains`, async () => { + try { + await applicationDomainTasks(EEpSdkTask_TargetState.ABSENT); + await applicationDomainTasks(EEpSdkTask_TargetState.PRESENT); + } catch (e) { + expect(false, TestLogger.createApiTestFailMessage("failed", e)).to.be.true; + } + }); + + it(`${scriptName}: should create the schemas & versions`, async () => { + try { + const task_1 = new EpSdkSchemaTask({ + epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, + applicationDomainId: ApplicationDomain_Events_1_Id, + schemaName: Schema_1_Name, + schemaObjectSettings: { + shared: true, + }, + }); + const task_1_ExecuteReturn: IEpSdkSchemaTask_ExecuteReturn = await task_1.execute(); + Schema_1_Id = task_1_ExecuteReturn.epObject.id; + + const task_1_1 = new EpSdkSchemaVersionTask({ + epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, + applicationDomainId: ApplicationDomain_Events_1_Id, + schemaId: Schema_1_Id, + versionString: "1.0.0", + schemaVersionSettings: { + stateId: EpSdkStatesService.releasedId, + displayName: 'Schema_1_Id', + description: 'Schema_1_Id', + content: SchemaContent, + }, + }); + const task_1_1_ExecuteReturn: IEpSdkSchemaVersionTask_ExecuteReturn = await task_1_1.execute(); + SchemaVersion_1_Id = task_1_1_ExecuteReturn.epObject.id; + + const task_2 = new EpSdkSchemaTask({ + epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, + applicationDomainId: ApplicationDomain_Events_2_Id, + schemaName: Schema_2_Name, + schemaObjectSettings: { + shared: true, + }, + }); + const task_2_ExecuteReturn: IEpSdkSchemaTask_ExecuteReturn = await task_2.execute(); + Schema_2_Id = task_2_ExecuteReturn.epObject.id; + + const task_2_1 = new EpSdkSchemaVersionTask({ + epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, + applicationDomainId: ApplicationDomain_Events_2_Id, + schemaId: Schema_2_Id, + versionString: "1.0.0", + schemaVersionSettings: { + stateId: EpSdkStatesService.releasedId, + displayName: 'Schema_2_Id', + description: 'Schema_2_Id', + content: SchemaContent, + }, + }); + const task_2_1_ExecuteReturn: IEpSdkSchemaVersionTask_ExecuteReturn = await task_2_1.execute(); + SchemaVersion_2_Id = task_2_1_ExecuteReturn.epObject.id; + } catch (e) { + expect(false, TestLogger.createApiTestFailMessage("failed", e)).to.be.true; + } + }); + + it(`${scriptName}: should create the enums & versions`, async () => { + try { + const task_1 = new EpSdkEnumTask({ + epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, + applicationDomainId: ApplicationDomain_Events_1_Id, + enumName: Enum_1_Name, + enumObjectSettings: { + shared: true, + } + }); + const task_1_ExecuteReturn: IEpSdkEnumTask_ExecuteReturn = await task_1.execute(); + Enum_1_Id = task_1_ExecuteReturn.epObject.id; + const task_1_1 = new EpSdkEnumVersionTask({ + epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, + applicationDomainId: ApplicationDomain_Events_1_Id, + enumId: Enum_1_Id, + versionString: "1.0.0", + enumVersionSettings: { + stateId: EpSdkStatesService.releasedId, + displayName: 'Enum_1_Id', + description: 'Enum_1_Id', + }, + enumValues: EnumValues + }); + const task_1_1_ExecuteReturn: IEpSdkEnumVersionTask_ExecuteReturn = await task_1_1.execute(); + EnumVersion_1_Id = task_1_1_ExecuteReturn.epObject.id; + + const task_2 = new EpSdkEnumTask({ + epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, + applicationDomainId: ApplicationDomain_Events_2_Id, + enumName: Enum_2_Name, + enumObjectSettings: { + shared: true, + } + }); + const task_2_ExecuteReturn: IEpSdkEnumTask_ExecuteReturn = await task_2.execute(); + Enum_2_Id = task_2_ExecuteReturn.epObject.id; + const task_2_1 = new EpSdkEnumVersionTask({ + epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, + applicationDomainId: ApplicationDomain_Events_2_Id, + enumId: Enum_2_Id, + versionString: "1.0.0", + enumVersionSettings: { + stateId: EpSdkStatesService.releasedId, + displayName: 'Enum_2_Id', + description: 'Enum_2_Id', + }, + enumValues: EnumValues + }); + const task_2_1_ExecuteReturn: IEpSdkEnumVersionTask_ExecuteReturn = await task_2_1.execute(); + EnumVersion_2_Id = task_2_1_ExecuteReturn.epObject.id; + + } catch (e) { + expect(false, TestLogger.createApiTestFailMessage("failed", e)).to.be.true; + } + }); + + it(`${scriptName}: should create the events & versions`, async () => { + try { + const task_1 = new EpSdkEpEventTask({ + epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, + applicationDomainId: ApplicationDomain_Events_1_Id, + eventName: Event_1_Name, + eventObjectSettings: { + brokerType: EpSdkBrokerTypes.Solace, + shared: true + } + }); + const task_1_ExecuteReturn: IEpSdkEpEventTask_ExecuteReturn = await task_1.execute(); + Event_1_Id = task_1_ExecuteReturn.epObject.id; + const task_1_1 = new EpSdkEpEventVersionTask({ + epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, + applicationDomainId: ApplicationDomain_Events_1_Id, + eventId: Event_1_Id, + versionString: "1.0.0", + eventVersionSettings: { + displayName: 'Event_1_Id', + description: 'Event_1_Id', + schemaVersionId: SchemaVersion_1_Id, + stateId: EpSdkStatesService.releasedId, + }, + topicString: TopicString_1 + }); + const task_1_1_ExecuteReturn: IEpSdkEpEventVersionTask_ExecuteReturn = await task_1_1.execute(); + EventVersion_1_Id = task_1_1_ExecuteReturn.epObject.id; + + const task_2 = new EpSdkEpEventTask({ + epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, + applicationDomainId: ApplicationDomain_Events_2_Id, + eventName: Event_2_Name, + eventObjectSettings: { + brokerType: EpSdkBrokerTypes.Solace, + shared: true + } + }); + const task_2_ExecuteReturn: IEpSdkEpEventTask_ExecuteReturn = await task_2.execute(); + Event_2_Id = task_2_ExecuteReturn.epObject.id; + const task_2_1 = new EpSdkEpEventVersionTask({ + epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, + applicationDomainId: ApplicationDomain_Events_2_Id, + eventId: Event_2_Id, + versionString: "1.0.0", + eventVersionSettings: { + displayName: 'Event_2_Id', + description: 'Event_2_Id', + schemaVersionId: SchemaVersion_2_Id, + stateId: EpSdkStatesService.releasedId, + }, + topicString: TopicString_2 + }); + const task_2_1_ExecuteReturn: IEpSdkEpEventVersionTask_ExecuteReturn = await task_2_1.execute(); + EventVersion_2_Id = task_2_1_ExecuteReturn.epObject.id; + + } catch (e) { + expect(false, TestLogger.createApiTestFailMessage("failed", e)).to.be.true; + } + }); + + it(`${scriptName}: should create the event api & version`, async () => { + try { + const task_1 = new EpSdkEventApiTask({ + epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, + applicationDomainId: ApplicationDomain_Main_Id, + eventApiName: EventApi_Name, + eventApiObjectSettings: { + brokerType: EventApi.brokerType.SOLACE, + shared: true + } + }); + const task_1_ExecuteReturn: IEpSdkEventApiTask_ExecuteReturn = await task_1.execute(); + EventApi_Id = task_1_ExecuteReturn.epObject.id; + const task_1_1 = new EpSdkEventApiVersionTask({ + epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, + applicationDomainId: ApplicationDomain_Main_Id, + eventApiId: EventApi_Id, + versionString: "1.0.0", + eventApiVersionSettings: { + stateId: EpSdkStatesService.releasedId, + displayName: 'EventApi_Id', + description: 'EventApi_Id', + consumedEventVersionIds: [EventVersion_1_Id], + producedEventVersionIds: [EventVersion_2_Id], + } + }); + const task_1_1_ExecuteReturn: IEpSdkEventApiVersionTask_ExecuteReturn = await task_1_1.execute(); + EventApiVersion_Id = task_1_1_ExecuteReturn.epObject.id; + } catch (e) { + expect(false, TestLogger.createApiTestFailMessage("failed", e)).to.be.true; + } + }); + + it(`${scriptName}: should create the app & version`, async () => { + try { + const task_1 = new EpSdkApplicationTask({ + epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, + applicationDomainId: ApplicationDomain_Main_Id, + applicationName: App_Name, + applicationObjectSettings: { + brokerType: EventApi.brokerType.SOLACE, + applicationType: "standard", + } + }); + const task_1_ExecuteReturn: IEpSdkApplicationTask_ExecuteReturn = await task_1.execute(); + App_Id = task_1_ExecuteReturn.epObject.id; + const task_1_1 = new EpSdkApplicationVersionTask({ + epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, + applicationDomainId: ApplicationDomain_Main_Id, + applicationId: App_Id, + versionString: "1.0.0", + applicationVersionSettings: { + displayName: 'App_Id', + description: 'App_Id', + declaredConsumedEventVersionIds: [EventVersion_2_Id], + declaredProducedEventVersionIds: [EventVersion_1_Id], + stateId: EpSdkStatesService.releasedId, + } + }); + const task_1_1_ExecuteReturn: IEpSdkApplicationVersionTask_ExecuteReturn = await task_1_1.execute(); + AppVersion_Id = task_1_1_ExecuteReturn.epObject.id; + } catch (e) { + expect(false, TestLogger.createApiTestFailMessage("failed", e)).to.be.true; + } + }); + + it(`${scriptName}: should get the event api spec`, async () => { + try { + EventApiSpec = await EventApIsService.getAsyncApiForEventApiVersion({ + eventApiVersionId: EventApiVersion_Id, + }); + // console.log(`EventApiSpec = ${JSON.stringify(EventApiSpec, null, 2)}`); + } catch (e) { + expect(false, TestLogger.createApiTestFailMessage("failed", e)).to.be.true; + } + }); + + it(`${scriptName}: should parse the event api spec and save it to file`, async () => { + try { + const epAsyncApiDocument: EpAsyncApiDocument = await EpAsyncApiDocumentService.createFromAny({ + anySpec: EventApiSpec + }); + const applicationDomainName = epAsyncApiDocument.getApplicationDomainName(); + const assetsApplicationDomainName = epAsyncApiDocument.getAssetsApplicationDomainName(); + + const asyncApiSpecFileNameJson = TestConfig.getConfig().tmpDir + "/" + epAsyncApiDocument.getTitleAsFileName("json"); + CliUtils.saveContents2File({ + filePath: asyncApiSpecFileNameJson, + content: JSON.stringify(epAsyncApiDocument.getOriginalSpecAsJson(), null, 2 ), + }); + + + // console.log(`applicationDomainName = ${JSON.stringify(applicationDomainName)}`); + // console.log(`assetsApplicationDomainName = ${JSON.stringify(assetsApplicationDomainName)}`); + } catch (e) { + expect(false, TestLogger.createApiTestFailMessage("failed", e)).to.be.true; + } + }); + + it(`${scriptName}: should deep copy event api version`, async () => { + try { + const copiedEventApiVersion: EventApiVersion | undefined = await EpSdkEventApiVersionsService.deepCopyLastestVersionById_IfNotExists({ + eventApiName: EventApi_Name, + fromApplicationDomainId: ApplicationDomain_Main_Id, + toApplicationDomainId: ApplicationDomain_Copy_Id, + }); + // const copiedApplicationVersion: ApplicationVersion | undefined = await EpSdkApplicationVersionsService.deepCopyLastestVersionById_IfNotExists({ + // eventApiName: EventApi_Name, + // fromApplicationDomainId: ApplicationDomain_Main_Id, + // toApplicationDomainId: ApplicationDomain_Copy_Id, + // }); + expect(false, 'did the copy work?').to.be.true; + } catch (e) { + expect(false, TestLogger.createApiTestFailMessage("failed", e)).to.be.true; + } + }); + +}); diff --git a/packages/ep-sdk/test/specs/tasks/schemaVersionTask.spec.ts b/packages/ep-sdk/test/specs/tasks/schemaVersionTask.spec.ts index 8cefdd8d7..b2fe55a7b 100644 --- a/packages/ep-sdk/test/specs/tasks/schemaVersionTask.spec.ts +++ b/packages/ep-sdk/test/specs/tasks/schemaVersionTask.spec.ts @@ -152,12 +152,9 @@ describe(`${scriptName}`, () => { // // DEBUG // expect(false, message).to.be.true; } catch (e) { - if (e instanceof ApiError) - expect(false, TestLogger.createApiTestFailMessage("failed")).to.be.true; - expect(e instanceof EpSdkError, TestLogger.createNotEpSdkErrorMessage(e)) - .to.be.true; - expect(false, TestLogger.createEpSdkTestFailMessage("failed", e)).to.be - .true; + if (e instanceof ApiError) expect(false, TestLogger.createApiTestFailMessage("failed")).to.be.true; + expect(e instanceof EpSdkError, TestLogger.createNotEpSdkErrorMessage(e)).to.be.true; + expect(false, TestLogger.createEpSdkTestFailMessage("failed", e)).to.be.true; } }); diff --git a/packages/integration-tests/.gitignore b/packages/integration-tests/.gitignore index de4d1f007..2c109005a 100644 --- a/packages/integration-tests/.gitignore +++ b/packages/integration-tests/.gitignore @@ -1,2 +1,3 @@ dist node_modules +private diff --git a/packages/integration-tests/package.json b/packages/integration-tests/package.json index b6ef2a97f..6a578676f 100644 --- a/packages/integration-tests/package.json +++ b/packages/integration-tests/package.json @@ -8,12 +8,14 @@ "scripts": { "clean": "rm -rf dist && rm -rf .turbo", "build:test": "yarn tsc", - "test:x": "yarn build:test && . ./source.env.sh && mocha --config .mocharc.yml src/**/**.x-spec.ts && unset_source_env" + "test:x": "yarn build:test && . ./source.env.sh && mocha --config .mocharc.yml src/**/**.x-spec.ts && unset_source_env", + "test:xsd": "yarn build:test && . ./source.env.sh && mocha --config .mocharc.yml src/**/**.xsd-spec.ts && unset_source_env" }, "dependencies": {}, "devDependencies": { + "@solace-labs/ep-asyncapi": "0.53.2", "@solace-labs/ep-openapi-node": "^2.53.0", "@solace-labs/ep-sdk": "0.56.1", - "@solace-labs/ep-asyncapi": "0.53.2" + "libxmljs2-xsd": "^0.30.1" } } diff --git a/packages/integration-tests/src/decs.d.ts b/packages/integration-tests/src/decs.d.ts new file mode 100644 index 000000000..64afdd416 --- /dev/null +++ b/packages/integration-tests/src/decs.d.ts @@ -0,0 +1 @@ +declare module "libxmljs2-xsd"; \ No newline at end of file diff --git a/packages/integration-tests/src/specs/ep-xml-schema/xml-schema-parse.xsd-spec.ts b/packages/integration-tests/src/specs/ep-xml-schema/xml-schema-parse.xsd-spec.ts new file mode 100644 index 000000000..b7dd60b41 --- /dev/null +++ b/packages/integration-tests/src/specs/ep-xml-schema/xml-schema-parse.xsd-spec.ts @@ -0,0 +1,81 @@ +import "mocha"; +import { expect } from "chai"; +import path from "path"; +import fs from 'fs'; +import { TestContext, TestUtils } from "@internal/tools/src"; +import { TestLogger, TestConfig, TestService } from "../../lib"; +import { + ApiError, + EventApIsService +} from "@solace-labs/ep-openapi-node"; +import { + EEpSdkSchemaContentType, + EEpSdkSchemaType, + EEpSdkTask_TargetState, + EpSdkEpEventTask, + EpSdkEpEventVersionTask, + EpSdkSchemaTask, + EpSdkSchemaVersionTask, + EpSdkStatesService, + IEpSdkEpEventTask_ExecuteReturn, + IEpSdkEpEventVersionTask_ExecuteReturn, + IEpSdkSchemaTask_ExecuteReturn, + IEpSdkSchemaVersionTask_ExecuteReturn, + EpSdkEventApiTask, + IEpSdkEventApiTask_ExecuteReturn, + EpSdkEventApiVersionTask, + IEpSdkEventApiVersionTask_ExecuteReturn +} from "@solace-labs/ep-sdk"; + +import xsd from 'libxmljs2-xsd'; +var libxmljs = xsd.libxmljs; + +const scriptName: string = path.basename(__filename); +TestLogger.logMessage(scriptName, ">>> starting ..."); +const TestSpecName = scriptName; +const TestSpecId = TestUtils.getShortUUID(); + + +const scriptDir: string = path.dirname(__filename); + + +const initializeGlobals = () => { +} + +describe(`${scriptName}`, () => { + + before(async() => { + TestContext.newItId(); + initializeGlobals(); + }); + + beforeEach(() => { + TestContext.newItId(); + }); + + after(async() => { + TestContext.newItId(); + }); + + it(`${scriptName}: should parse schema`, async () => { + try { + + const schemaDir = `${scriptDir}/data/private/navcan.CAATS.xsd`; + const schemaFilePath = TestUtils.validateFilePathWithReadPermission(`${schemaDir}/caats_external_flight_data.xsd`); + + process.chdir(schemaDir); + + console.log(`process.cwd = ${process.cwd()}`) + const schema = xsd.parseFile(schemaFilePath); + + console.log(`schema = ${JSON.stringify(schema, null, 2)}`); + + + } catch (e) { + console.log(JSON.stringify(e, null, 2)); + expect(false, TestLogger.createTestFailMessageForError("failed", e)).to.be.true; + } + }); + + +}); diff --git a/packages/tools/src/testLib/TestConfigBase.ts b/packages/tools/src/testLib/TestConfigBase.ts index 83ac4bafa..06ca32596 100644 --- a/packages/tools/src/testLib/TestConfigBase.ts +++ b/packages/tools/src/testLib/TestConfigBase.ts @@ -27,6 +27,13 @@ export class TestConfigBase { return absoluteDir; } + protected createReadWriteDir = (baseDir: string, subDir?: string): string => { + const absoluteDir = subDir ? path.resolve(baseDir, subDir) : path.resolve(baseDir); + if(!fs.existsSync(absoluteDir)) fs.mkdirSync(absoluteDir, { recursive: true }); + fs.accessSync(absoluteDir, fs.constants.W_OK); + return absoluteDir; + } + protected getMandatoryEnvVarValueAsString = (envVarName: string): string => { const value: string | undefined = process.env[envVarName]; if (!value) throw new Error(`mandatory env var missing: ${envVarName}`); diff --git a/yarn.lock b/yarn.lock index 1a92956fc..daab767c5 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1294,6 +1294,21 @@ globby "^11.0.0" read-yaml-file "^1.1.0" +"@mapbox/node-pre-gyp@^1.0.9": + version "1.0.10" + resolved "https://registry.yarnpkg.com/@mapbox/node-pre-gyp/-/node-pre-gyp-1.0.10.tgz#8e6735ccebbb1581e5a7e652244cadc8a844d03c" + integrity sha512-4ySo4CjzStuprMwk35H5pPbkymjv1SF3jGLj6rAHp/xT/RF7TL7bd9CTm1xDY49K2qF7jmR/g7k+SkLETP6opA== + dependencies: + detect-libc "^2.0.0" + https-proxy-agent "^5.0.0" + make-dir "^3.1.0" + node-fetch "^2.6.7" + nopt "^5.0.0" + npmlog "^5.0.1" + rimraf "^3.0.2" + semver "^7.3.5" + tar "^6.1.11" + "@nodelib/fs.scandir@2.1.5": version "2.1.5" resolved "https://registry.yarnpkg.com/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz#7619c2eb21b25483f6d167548b4cfd5a7488c3d5" @@ -2109,6 +2124,14 @@ archy@^1.0.0: resolved "https://registry.yarnpkg.com/archy/-/archy-1.0.0.tgz#f9c8c13757cc1dd7bc379ac77b2c62a5c2868c40" integrity sha512-Xg+9RwCg/0p32teKdGMPTPnVXKD0w3DfHnFTficozsAgsvq2XenPJq/MYpzzQ/v8zrOyJn6Ds39VA4JIDwFfqw== +are-we-there-yet@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/are-we-there-yet/-/are-we-there-yet-2.0.0.tgz#372e0e7bd279d8e94c653aaa1f67200884bf3e1c" + integrity sha512-Ci/qENmwHnsYo9xKIcUJN5LeDKdJ6R1Z1j9V/J5wyq8nh/mYPEpIKJbBZXtZjG04HiK7zV/p6Vs9952MrMeUIw== + dependencies: + delegates "^1.0.0" + readable-stream "^3.6.0" + are-we-there-yet@^3.0.0: version "3.0.1" resolved "https://registry.yarnpkg.com/are-we-there-yet/-/are-we-there-yet-3.0.1.tgz#679df222b278c64f2cdba1175cdc00b0d96164bd" @@ -2252,6 +2275,13 @@ binary-extensions@^2.0.0: resolved "https://registry.yarnpkg.com/binary-extensions/-/binary-extensions-2.2.0.tgz#75f502eeaf9ffde42fc98829645be4ea76bd9e2d" integrity sha512-jDctJ/IVQbZoJykoeHbhXpOlNBqGNcwXJKJog42E5HDPUwQTSdjCHdihjj0DlnheQ7blbT6dHOafNAiS8ooQKA== +bindings@~1.5.0: + version "1.5.0" + resolved "https://registry.yarnpkg.com/bindings/-/bindings-1.5.0.tgz#10353c9e945334bc0511a6d90b38fbc7c9c504df" + integrity sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ== + dependencies: + file-uri-to-path "1.0.0" + bl@^4.0.3, bl@^4.1.0: version "4.1.0" resolved "https://registry.yarnpkg.com/bl/-/bl-4.1.0.tgz#451535264182bec2fbbc83a62ab98cf11d9f7b3a" @@ -2633,7 +2663,7 @@ color-name@~1.1.4: resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.4.tgz#c2a09a87acbde69543de6f63fa3995c826c536a2" integrity sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA== -color-support@^1.1.3: +color-support@^1.1.2, color-support@^1.1.3: version "1.1.3" resolved "https://registry.yarnpkg.com/color-support/-/color-support-1.1.3.tgz#93834379a1cc9a0c61f82f52f0d04322251bd5a2" integrity sha512-qiBjkpbMLO/HL68y+lh4q0/O1MZFj2RX6X/KmMa3+gJD3z+WwI1ZzDHysvqHGS3mP6mznPckpXmw1nI9cJjyRg== @@ -2714,7 +2744,7 @@ config-chain@^1.1.12: ini "^1.3.4" proto-list "~1.2.1" -console-control-strings@^1.1.0: +console-control-strings@^1.0.0, console-control-strings@^1.1.0: version "1.1.0" resolved "https://registry.yarnpkg.com/console-control-strings/-/console-control-strings-1.1.0.tgz#3d7cf4464db6446ea644bf4b39507f9851008e8e" integrity sha512-ty/fTekppD2fIwRvnZAVdeOiGd1c7YXEixbgJTNzqcxJWKQnjJ/V1bNEEE6hygpM3WjwHFUVK6HTjWSzV4a8sQ== @@ -3001,6 +3031,11 @@ detect-indent@^6.0.0: resolved "https://registry.yarnpkg.com/detect-indent/-/detect-indent-6.1.0.tgz#592485ebbbf6b3b1ab2be175c8393d04ca0d57e6" integrity sha512-reYkTUJAZb9gUuZ2RvVCNhVHdg62RHnJ7WJl8ftMi4diZ6NWlciOzQN88pUhSELEwflJht4oQDv0F0BMlwaYtA== +detect-libc@^2.0.0: + version "2.0.1" + resolved "https://registry.yarnpkg.com/detect-libc/-/detect-libc-2.0.1.tgz#e1897aa88fa6ad197862937fbc0441ef352ee0cd" + integrity sha512-463v3ZeIrcWtdgIg6vI6XUncguvr2TnGl4SzDXinkt9mSLpBJKXT3mW6xT3VQdDN11+WVs29pgvivTc4Lp8v+w== + dezalgo@^1.0.0, dezalgo@^1.0.4: version "1.0.4" resolved "https://registry.yarnpkg.com/dezalgo/-/dezalgo-1.0.4.tgz#751235260469084c132157dfa857f386d4c33d81" @@ -3584,6 +3619,11 @@ file-entry-cache@^6.0.1: dependencies: flat-cache "^3.0.4" +file-uri-to-path@1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz#553a7b8446ff6f684359c445f1e37a05dacc33dd" + integrity sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw== + filelist@^1.0.1: version "1.0.4" resolved "https://registry.yarnpkg.com/filelist/-/filelist-1.0.4.tgz#f78978a1e944775ff9e62e744424f215e58352b5" @@ -3781,6 +3821,21 @@ functions-have-names@^1.2.2: resolved "https://registry.yarnpkg.com/functions-have-names/-/functions-have-names-1.2.3.tgz#0404fe4ee2ba2f607f0e0ec3c80bae994133b834" integrity sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ== +gauge@^3.0.0: + version "3.0.2" + resolved "https://registry.yarnpkg.com/gauge/-/gauge-3.0.2.tgz#03bf4441c044383908bcfa0656ad91803259b395" + integrity sha512-+5J6MS/5XksCuXq++uFRsnUd7Ovu1XenbeuIuNRJxYWjgQbPuFhT14lAvsWfqfAmnwluf1OwMjz39HjfLPci0Q== + dependencies: + aproba "^1.0.3 || ^2.0.0" + color-support "^1.1.2" + console-control-strings "^1.0.0" + has-unicode "^2.0.1" + object-assign "^4.1.1" + signal-exit "^3.0.0" + string-width "^4.2.3" + strip-ansi "^6.0.1" + wide-align "^1.1.2" + gauge@^4.0.3: version "4.0.4" resolved "https://registry.yarnpkg.com/gauge/-/gauge-4.0.4.tgz#52ff0652f2bbf607a989793d53b751bef2328dce" @@ -4833,6 +4888,25 @@ libnpmpublish@^6.0.4: semver "^7.3.7" ssri "^9.0.0" +libxmljs2-xsd@^0.30.1: + version "0.30.1" + resolved "https://registry.yarnpkg.com/libxmljs2-xsd/-/libxmljs2-xsd-0.30.1.tgz#e91345e858909706dcf3e7bee9578f0cd573833f" + integrity sha512-SdGtrW2nrLYUf2dPRQx6CDcAPLSUjlVzJRXq8aMMEn0FCmrGI1/u+12B9j8pIKQ6IWjlX8zYnlJrw5dCPfcmeA== + dependencies: + "@mapbox/node-pre-gyp" "^1.0.9" + bindings "~1.5.0" + libxmljs2 "^0.30.1" + nan "~2.15.0" + +libxmljs2@^0.30.1: + version "0.30.1" + resolved "https://registry.yarnpkg.com/libxmljs2/-/libxmljs2-0.30.1.tgz#a7e468facbde8ef57076d1f1f379375b30d3f212" + integrity sha512-Upgf6LnbDZV8oYrG2cONazKjnUPV2v8TbAKP951flkCsyyrEuMYBe8IgYtrcm5bXFOmQnKsbFeZwMwVvVNZLpg== + dependencies: + "@mapbox/node-pre-gyp" "^1.0.9" + bindings "~1.5.0" + nan "~2.15.0" + lilconfig@^2.0.5: version "2.0.6" resolved "https://registry.yarnpkg.com/lilconfig/-/lilconfig-2.0.6.tgz#32a384558bd58af3d4c6e077dd1ad1d397bc69d4" @@ -5002,7 +5076,7 @@ make-dir@^2.1.0: pify "^4.0.1" semver "^5.6.0" -make-dir@^3.0.0, make-dir@^3.0.2: +make-dir@^3.0.0, make-dir@^3.0.2, make-dir@^3.1.0: version "3.1.0" resolved "https://registry.yarnpkg.com/make-dir/-/make-dir-3.1.0.tgz#415e967046b3a7f1d185277d84aa58203726a13f" integrity sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw== @@ -5336,6 +5410,11 @@ mz@^2.7.0: object-assign "^4.0.1" thenify-all "^1.0.0" +nan@~2.15.0: + version "2.15.0" + resolved "https://registry.yarnpkg.com/nan/-/nan-2.15.0.tgz#3f34a473ff18e15c1b5626b62903b5ad6e665fee" + integrity sha512-8ZtvEnA2c5aYCZYd1cvgdnU6cqwixRoYg70xPLWUws5ORTa/lnw+u4amixRS/Ac5U5mQVgp9pnlSUnbNWFaWZQ== + nanoid@3.1.20: version "3.1.20" resolved "https://registry.yarnpkg.com/nanoid/-/nanoid-3.1.20.tgz#badc263c6b1dcf14b71efaa85f6ab4c1d6cfc788" @@ -5561,6 +5640,16 @@ npm-run-path@^4.0.1: dependencies: path-key "^3.0.0" +npmlog@^5.0.1: + version "5.0.1" + resolved "https://registry.yarnpkg.com/npmlog/-/npmlog-5.0.1.tgz#f06678e80e29419ad67ab964e0fa69959c1eb8b0" + integrity sha512-AqZtDUWOMKs1G/8lwylVjrdYgqA4d9nu8hc+0gzRxlDb1I10+FHBGMXs6aiQHFdCUUlqH99MUMuLfzWDNDtfxw== + dependencies: + are-we-there-yet "^2.0.0" + console-control-strings "^1.1.0" + gauge "^3.0.0" + set-blocking "^2.0.0" + npmlog@^6.0.0, npmlog@^6.0.2: version "6.0.2" resolved "https://registry.yarnpkg.com/npmlog/-/npmlog-6.0.2.tgz#c8166017a42f2dea92d6453168dd865186a70830" @@ -5645,7 +5734,7 @@ nyc@^15.1.0: test-exclude "^6.0.0" yargs "^15.0.2" -object-assign@^4.0.1: +object-assign@^4.0.1, object-assign@^4.1.1: version "4.1.1" resolved "https://registry.yarnpkg.com/object-assign/-/object-assign-4.1.1.tgz#2109adc7965887cfc05cbbd442cac8bfbb360863" integrity sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg== @@ -6644,7 +6733,7 @@ side-channel@^1.0.4: get-intrinsic "^1.0.2" object-inspect "^1.9.0" -signal-exit@^3.0.2, signal-exit@^3.0.3, signal-exit@^3.0.7: +signal-exit@^3.0.0, signal-exit@^3.0.2, signal-exit@^3.0.3, signal-exit@^3.0.7: version "3.0.7" resolved "https://registry.yarnpkg.com/signal-exit/-/signal-exit-3.0.7.tgz#a9a1767f8af84155114eaabd73f99273c8f59ad9" integrity sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ== @@ -7554,7 +7643,7 @@ wide-align@1.1.3: dependencies: string-width "^1.0.2 || 2" -wide-align@^1.1.5: +wide-align@^1.1.2, wide-align@^1.1.5: version "1.1.5" resolved "https://registry.yarnpkg.com/wide-align/-/wide-align-1.1.5.tgz#df1d4c206854369ecf3c9a4898f1b23fbd9d15d3" integrity sha512-eDMORYaPNZ4sQIuuYPDHdQvf4gyCF9rEEV/yPxGfwPkRodwEgiMUUXTx/dex+Me0wxx53S+NgUHaP7y3MGlDmg== From fd826cc6c16a3ad21c298b6987868ce3fcfc076c Mon Sep 17 00:00:00 2001 From: Ricardo Gomez_Ulmke Date: Sat, 11 Mar 2023 12:37:12 +0100 Subject: [PATCH 06/33] added custom attribute with source app domain on copy objects --- packages/ep-async-api-importer/package.json | 2 +- .../test/lib/TestLogger.ts | 3 + .../test/specs/multi-domain.x-spec.ts | 124 +++++++++++++----- packages/ep-sdk/src/constants/constants.ts | 3 +- .../services/EpSdkCustomAttributesService.ts | 9 +- .../src/services/EpSdkEnumVersionsService.ts | 22 +++- .../ep-sdk/src/services/EpSdkEnumsService.ts | 63 ++++++++- .../services/EpSdkEpEventVersionsService.ts | 14 +- .../src/services/EpSdkEpEventsService.ts | 9 +- .../services/EpSdkEventApiVersionsService.ts | 12 +- .../src/services/EpSdkEventApisService.ts | 60 +++++++++ .../services/EpSdkSchemaVersionsService.ts | 57 ++++---- .../src/services/EpSdkSchemasService.ts | 123 ++++++++++------- .../specs/services/enumVersionCopy.spec.ts | 57 ++++---- .../test/specs/tasks/schemaTask.spec.ts | 9 +- packages/ep-sdk/tsconfig.json | 1 + 16 files changed, 392 insertions(+), 176 deletions(-) diff --git a/packages/ep-async-api-importer/package.json b/packages/ep-async-api-importer/package.json index c6aad3d42..46dd5c156 100644 --- a/packages/ep-async-api-importer/package.json +++ b/packages/ep-async-api-importer/package.json @@ -33,7 +33,7 @@ "clean": "rm -rf dist && rm -rf test/logs && rm -rf .turbo", "build:test": "yarn build", "test": "yarn build:test && . ./test/source.env.sh && nyc mocha --config test/.mocharc.yml test/**/**.spec.ts && unset_source_env", - "test:x": "yarn build:test && . ./test/source.env.sh && nyc mocha --config test/.mocharc.yml test/**/**.x-spec.ts && unset_source_env", + "test:x": "yarn build:test && . ./test/source.env.sh && mocha --config test/.mocharc.yml test/**/**.x-spec.ts && unset_source_env", "dev:watch": "yarn build --watch", "lint": "eslint .", "lint:deprecated": "yarn lint | grep deprecated", diff --git a/packages/ep-async-api-importer/test/lib/TestLogger.ts b/packages/ep-async-api-importer/test/lib/TestLogger.ts index f05df4e8b..4fb509607 100644 --- a/packages/ep-async-api-importer/test/lib/TestLogger.ts +++ b/packages/ep-async-api-importer/test/lib/TestLogger.ts @@ -38,4 +38,7 @@ export class TestLogger extends TestLoggerBase { ): string => { return `[${TestContext.getItId()}]: message=${message}, epSdkError=${epSdkError}`; }; + public static createNotEpSdkErrorMessage = (e: Error): string => { + return `[${TestContext.getItId()}]: error is not an instance of EpSdkError, name=${e.name}, message=${e.message}`; + } } diff --git a/packages/ep-async-api-importer/test/specs/multi-domain.x-spec.ts b/packages/ep-async-api-importer/test/specs/multi-domain.x-spec.ts index 26a0975d5..52e37bcac 100644 --- a/packages/ep-async-api-importer/test/specs/multi-domain.x-spec.ts +++ b/packages/ep-async-api-importer/test/specs/multi-domain.x-spec.ts @@ -2,6 +2,7 @@ import "mocha"; import { expect } from "chai"; import path from "path"; import { + ApiError, EventApi, EventApIsService, EventApiVersion, @@ -33,6 +34,7 @@ import { EpSdkApplicationVersionTask, IEpSdkApplicationVersionTask_ExecuteReturn, EpSdkEventApiVersionsService, + EpSdkError, } from "@solace-labs/ep-sdk"; import { TestContext, TestUtils } from "@internal/tools/src"; import { @@ -159,33 +161,64 @@ const initializeGlobals = () => { }; const applicationDomainTasks = async(epSdkTask_TargetState: EEpSdkTask_TargetState) => { - const task_1 = new EpSdkApplicationDomainTask({ - applicationDomainName: ApplicationDomain_Events_1_Name, - epSdkTask_TargetState: epSdkTask_TargetState - }); - const task1_ExecuteReturn: IEpSdkApplicationDomainTask_ExecuteReturn = await task_1.execute('xContextId'); - ApplicationDomain_Events_1_Id = task1_ExecuteReturn.epObject.id; - - const task_2 = new EpSdkApplicationDomainTask({ - applicationDomainName: ApplicationDomain_Events_2_Name, - epSdkTask_TargetState: epSdkTask_TargetState - }); - const task2_ExecuteReturn: IEpSdkApplicationDomainTask_ExecuteReturn = await task_2.execute('xContextId'); - ApplicationDomain_Events_2_Id = task2_ExecuteReturn.epObject.id; - - const task_3 = new EpSdkApplicationDomainTask({ - applicationDomainName: ApplicationDomain_Main_Name, - epSdkTask_TargetState: epSdkTask_TargetState - }); - const task3_ExecuteReturn: IEpSdkApplicationDomainTask_ExecuteReturn = await task_3.execute('xContextId'); - ApplicationDomain_Main_Id = task3_ExecuteReturn.epObject.id; - - const task_4 = new EpSdkApplicationDomainTask({ - applicationDomainName: ApplicationDomain_Copy_Name, - epSdkTask_TargetState: epSdkTask_TargetState - }); - const task4_ExecuteReturn: IEpSdkApplicationDomainTask_ExecuteReturn = await task_4.execute('xContextId'); - ApplicationDomain_Copy_Id = task4_ExecuteReturn.epObject.id; + // reverse the order for absent / present + if(epSdkTask_TargetState === EEpSdkTask_TargetState.PRESENT) { + const task_1 = new EpSdkApplicationDomainTask({ + applicationDomainName: ApplicationDomain_Events_1_Name, + epSdkTask_TargetState: epSdkTask_TargetState + }); + const task1_ExecuteReturn: IEpSdkApplicationDomainTask_ExecuteReturn = await task_1.execute('xContextId'); + ApplicationDomain_Events_1_Id = task1_ExecuteReturn.epObject.id; + + const task_2 = new EpSdkApplicationDomainTask({ + applicationDomainName: ApplicationDomain_Events_2_Name, + epSdkTask_TargetState: epSdkTask_TargetState + }); + const task2_ExecuteReturn: IEpSdkApplicationDomainTask_ExecuteReturn = await task_2.execute('xContextId'); + ApplicationDomain_Events_2_Id = task2_ExecuteReturn.epObject.id; + + const task_3 = new EpSdkApplicationDomainTask({ + applicationDomainName: ApplicationDomain_Main_Name, + epSdkTask_TargetState: epSdkTask_TargetState + }); + const task3_ExecuteReturn: IEpSdkApplicationDomainTask_ExecuteReturn = await task_3.execute('xContextId'); + ApplicationDomain_Main_Id = task3_ExecuteReturn.epObject.id; + + const task_4 = new EpSdkApplicationDomainTask({ + applicationDomainName: ApplicationDomain_Copy_Name, + epSdkTask_TargetState: epSdkTask_TargetState + }); + const task4_ExecuteReturn: IEpSdkApplicationDomainTask_ExecuteReturn = await task_4.execute('xContextId'); + ApplicationDomain_Copy_Id = task4_ExecuteReturn.epObject.id; + } else { + const task_4 = new EpSdkApplicationDomainTask({ + applicationDomainName: ApplicationDomain_Copy_Name, + epSdkTask_TargetState: epSdkTask_TargetState + }); + const task4_ExecuteReturn: IEpSdkApplicationDomainTask_ExecuteReturn = await task_4.execute('xContextId'); + ApplicationDomain_Copy_Id = task4_ExecuteReturn.epObject ? task4_ExecuteReturn.epObject.id : undefined; + + const task_3 = new EpSdkApplicationDomainTask({ + applicationDomainName: ApplicationDomain_Main_Name, + epSdkTask_TargetState: epSdkTask_TargetState + }); + const task3_ExecuteReturn: IEpSdkApplicationDomainTask_ExecuteReturn = await task_3.execute('xContextId'); + ApplicationDomain_Main_Id = task3_ExecuteReturn.epObject ? task3_ExecuteReturn.epObject.id : undefined; + + const task_2 = new EpSdkApplicationDomainTask({ + applicationDomainName: ApplicationDomain_Events_2_Name, + epSdkTask_TargetState: epSdkTask_TargetState + }); + const task2_ExecuteReturn: IEpSdkApplicationDomainTask_ExecuteReturn = await task_2.execute('xContextId'); + ApplicationDomain_Events_2_Id = task2_ExecuteReturn.epObject ? task2_ExecuteReturn.epObject.id : undefined; + + const task_1 = new EpSdkApplicationDomainTask({ + applicationDomainName: ApplicationDomain_Events_1_Name, + epSdkTask_TargetState: epSdkTask_TargetState + }); + const task1_ExecuteReturn: IEpSdkApplicationDomainTask_ExecuteReturn = await task_1.execute('xContextId'); + ApplicationDomain_Events_1_Id = task1_ExecuteReturn.epObject ? task1_ExecuteReturn.epObject.id : undefined; + } } describe(`${scriptName}`, () => { @@ -207,7 +240,9 @@ describe(`${scriptName}`, () => { await applicationDomainTasks(EEpSdkTask_TargetState.ABSENT); await applicationDomainTasks(EEpSdkTask_TargetState.PRESENT); } catch (e) { - expect(false, TestLogger.createApiTestFailMessage("failed", e)).to.be.true; + if (e instanceof ApiError) expect(false, TestLogger.createApiTestFailMessage("failed")).to.be.true; + expect(e instanceof EpSdkError, TestLogger.createNotEpSdkErrorMessage(e)).to.be.true; + expect(false, TestLogger.createEpSdkTestFailMessage("failed", e)).to.be.true; } }); @@ -265,7 +300,9 @@ describe(`${scriptName}`, () => { const task_2_1_ExecuteReturn: IEpSdkSchemaVersionTask_ExecuteReturn = await task_2_1.execute(); SchemaVersion_2_Id = task_2_1_ExecuteReturn.epObject.id; } catch (e) { - expect(false, TestLogger.createApiTestFailMessage("failed", e)).to.be.true; + if (e instanceof ApiError) expect(false, TestLogger.createApiTestFailMessage("failed")).to.be.true; + expect(e instanceof EpSdkError, TestLogger.createNotEpSdkErrorMessage(e)).to.be.true; + expect(false, TestLogger.createEpSdkTestFailMessage("failed", e)).to.be.true; } }); @@ -322,7 +359,9 @@ describe(`${scriptName}`, () => { EnumVersion_2_Id = task_2_1_ExecuteReturn.epObject.id; } catch (e) { - expect(false, TestLogger.createApiTestFailMessage("failed", e)).to.be.true; + if (e instanceof ApiError) expect(false, TestLogger.createApiTestFailMessage("failed")).to.be.true; + expect(e instanceof EpSdkError, TestLogger.createNotEpSdkErrorMessage(e)).to.be.true; + expect(false, TestLogger.createEpSdkTestFailMessage("failed", e)).to.be.true; } }); @@ -383,7 +422,9 @@ describe(`${scriptName}`, () => { EventVersion_2_Id = task_2_1_ExecuteReturn.epObject.id; } catch (e) { - expect(false, TestLogger.createApiTestFailMessage("failed", e)).to.be.true; + if (e instanceof ApiError) expect(false, TestLogger.createApiTestFailMessage("failed")).to.be.true; + expect(e instanceof EpSdkError, TestLogger.createNotEpSdkErrorMessage(e)).to.be.true; + expect(false, TestLogger.createEpSdkTestFailMessage("failed", e)).to.be.true; } }); @@ -416,7 +457,9 @@ describe(`${scriptName}`, () => { const task_1_1_ExecuteReturn: IEpSdkEventApiVersionTask_ExecuteReturn = await task_1_1.execute(); EventApiVersion_Id = task_1_1_ExecuteReturn.epObject.id; } catch (e) { - expect(false, TestLogger.createApiTestFailMessage("failed", e)).to.be.true; + if (e instanceof ApiError) expect(false, TestLogger.createApiTestFailMessage("failed")).to.be.true; + expect(e instanceof EpSdkError, TestLogger.createNotEpSdkErrorMessage(e)).to.be.true; + expect(false, TestLogger.createEpSdkTestFailMessage("failed", e)).to.be.true; } }); @@ -449,7 +492,9 @@ describe(`${scriptName}`, () => { const task_1_1_ExecuteReturn: IEpSdkApplicationVersionTask_ExecuteReturn = await task_1_1.execute(); AppVersion_Id = task_1_1_ExecuteReturn.epObject.id; } catch (e) { - expect(false, TestLogger.createApiTestFailMessage("failed", e)).to.be.true; + if (e instanceof ApiError) expect(false, TestLogger.createApiTestFailMessage("failed")).to.be.true; + expect(e instanceof EpSdkError, TestLogger.createNotEpSdkErrorMessage(e)).to.be.true; + expect(false, TestLogger.createEpSdkTestFailMessage("failed", e)).to.be.true; } }); @@ -460,7 +505,9 @@ describe(`${scriptName}`, () => { }); // console.log(`EventApiSpec = ${JSON.stringify(EventApiSpec, null, 2)}`); } catch (e) { - expect(false, TestLogger.createApiTestFailMessage("failed", e)).to.be.true; + if (e instanceof ApiError) expect(false, TestLogger.createApiTestFailMessage("failed")).to.be.true; + expect(e instanceof EpSdkError, TestLogger.createNotEpSdkErrorMessage(e)).to.be.true; + expect(false, TestLogger.createEpSdkTestFailMessage("failed", e)).to.be.true; } }); @@ -482,7 +529,9 @@ describe(`${scriptName}`, () => { // console.log(`applicationDomainName = ${JSON.stringify(applicationDomainName)}`); // console.log(`assetsApplicationDomainName = ${JSON.stringify(assetsApplicationDomainName)}`); } catch (e) { - expect(false, TestLogger.createApiTestFailMessage("failed", e)).to.be.true; + if (e instanceof ApiError) expect(false, TestLogger.createApiTestFailMessage("failed")).to.be.true; + expect(e instanceof EpSdkError, TestLogger.createNotEpSdkErrorMessage(e)).to.be.true; + expect(false, TestLogger.createEpSdkTestFailMessage("failed", e)).to.be.true; } }); @@ -500,7 +549,10 @@ describe(`${scriptName}`, () => { // }); expect(false, 'did the copy work?').to.be.true; } catch (e) { - expect(false, TestLogger.createApiTestFailMessage("failed", e)).to.be.true; + TestLogger.logMessageWithId(TestLogger.createTestFailMessageForError('error', e)); + if (e instanceof ApiError) expect(false, TestLogger.createApiTestFailMessage("failed")).to.be.true; + expect(e instanceof EpSdkError, TestLogger.createNotEpSdkErrorMessage(e)).to.be.true; + expect(false, TestLogger.createEpSdkTestFailMessage("failed", e)).to.be.true; } }); diff --git a/packages/ep-sdk/src/constants/constants.ts b/packages/ep-sdk/src/constants/constants.ts index c7cab8710..4ad151626 100644 --- a/packages/ep-sdk/src/constants/constants.ts +++ b/packages/ep-sdk/src/constants/constants.ts @@ -1 +1,2 @@ -export const EpApiMaxPageSize = 100; \ No newline at end of file +export const EpApiMaxPageSize = 100; +export const EpSdkCustomAttributeNameSourceApplicationDomainId = "x-ep-sdk-source-application-domain-id"; \ No newline at end of file diff --git a/packages/ep-sdk/src/services/EpSdkCustomAttributesService.ts b/packages/ep-sdk/src/services/EpSdkCustomAttributesService.ts index f5b96f32b..3ab309287 100644 --- a/packages/ep-sdk/src/services/EpSdkCustomAttributesService.ts +++ b/packages/ep-sdk/src/services/EpSdkCustomAttributesService.ts @@ -1,5 +1,5 @@ import { - CustomAttribute, + CustomAttribute, CustomAttributeDefinition, } from "@solace-labs/ep-openapi-node"; import { EpSdkApiContentError @@ -22,11 +22,12 @@ export class EpSdkCustomAttributesServiceClass { * Returns full custom attributes including existing & new ones. * Ensures any missing definitions are created or their entity types added. */ - public async createCustomAttributesWithNew({ xContextId, existingCustomAttributes, epSdkCustomAttributeList, epSdkCustomAttributeEntityType }:{ + public async createCustomAttributesWithNew({ xContextId, existingCustomAttributes, epSdkCustomAttributeList, epSdkCustomAttributeEntityType, scope }:{ xContextId?: string; existingCustomAttributes?: Array; epSdkCustomAttributeList: TEpSdkCustomAttributeList; epSdkCustomAttributeEntityType: EEpSdkCustomAttributeEntityTypes; + scope?: CustomAttributeDefinition.scope; }): Promise> { const funcName = 'createCustomAttributesWithNew'; const logName = `${EpSdkCustomAttributesServiceClass.name}.${funcName}()`; @@ -34,7 +35,6 @@ export class EpSdkCustomAttributesServiceClass { const customAttributeList: Array = []; for(const epSdkCustomAttribute of epSdkCustomAttributeList) { - const associatedEntityTypes: Array = await EpSdkCustomAttributeDefinitionsService.presentAssociatedEntityType({ xContextId: xContextId, attributeName: epSdkCustomAttribute.name, @@ -45,7 +45,8 @@ export class EpSdkCustomAttributesServiceClass { epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, attributeName: epSdkCustomAttribute.name, customAttributeDefinitionObjectSettings: { - associatedEntityTypes: associatedEntityTypes + associatedEntityTypes: associatedEntityTypes, + scope: scope ? scope : CustomAttributeDefinition.scope.ORGANIZATION }, }); const epSdkCustomAttributeDefinitionTask_ExecuteReturn: IEpSdkCustomAttributeDefinitionTask_ExecuteReturn = await epSdkCustomAttributeDefinitionTask.execute(xContextId); diff --git a/packages/ep-sdk/src/services/EpSdkEnumVersionsService.ts b/packages/ep-sdk/src/services/EpSdkEnumVersionsService.ts index 59e1535d6..d5ef5a317 100644 --- a/packages/ep-sdk/src/services/EpSdkEnumVersionsService.ts +++ b/packages/ep-sdk/src/services/EpSdkEnumVersionsService.ts @@ -1,4 +1,5 @@ import { + CustomAttributeDefinition, EnumsService, Pagination, StateChangeRequestResponse, @@ -11,7 +12,7 @@ import { EpSdkApiContentError } from "../utils"; import { - EpApiMaxPageSize + EpApiMaxPageSize, EpSdkCustomAttributeNameSourceApplicationDomainId } from '../constants'; import { EpSdkEnumTask, @@ -20,13 +21,18 @@ import { EEpSdkTask_TargetState, EpSdkEnumVersionTask, IEpSdkEnumVersionTask_ExecuteReturn, - EEpSdk_VersionTaskStrategy + EEpSdk_VersionTaskStrategy, + EpSdkCustomAttributeDefinitionTask, + IEpSdkCustomAttributeDefinitionTask_ExecuteReturn } from "../tasks"; import EpSdkEnumsService from "./EpSdkEnumsService"; import { EpSdkVersionServiceClass } from "./EpSdkVersionService"; +import { EEpSdkCustomAttributeEntityTypes } from '../types'; +import { EpSdkCustomAttributesService } from '.'; /** @category Services */ export class EpSdkEnumVersionsServiceClass extends EpSdkVersionServiceClass { + private readonly CustomAttributeEntityType = EEpSdkCustomAttributeEntityTypes.ENUM_VERSION; public getVersionByVersion = async ({ xContextId, enumId, enumVersionString }: { xContextId?: string; @@ -258,6 +264,15 @@ export class EpSdkEnumVersionsServiceClass extends EpSdkVersionServiceClass { }); if(targetTopicAddressEnumVersion !== undefined) return targetTopicAddressEnumVersion; } + // add the source application domain id to custom attribute + await EpSdkEnumsService.setCustomAttributes({ + xContextId: xContextId, + enumId: epSdkEnumTask_ExecuteReturn.epObjectKeys.epObjectId, + scope: CustomAttributeDefinition.scope.APPLICATION_DOMAIN, + epSdkCustomAttributeList: [ + { name: EpSdkCustomAttributeNameSourceApplicationDomainId, value: fromApplicationDomainId } + ] + }); // create target enum version const epSdkEnumVersionTask = new EpSdkEnumVersionTask({ epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, @@ -268,14 +283,13 @@ export class EpSdkEnumVersionsServiceClass extends EpSdkVersionServiceClass { enumVersionSettings: { stateId: fromTopicAddressEnumVersion.stateId, displayName: fromTopicAddressEnumVersion.displayName ? fromTopicAddressEnumVersion.displayName : fromTopicAddressEnum.name, - description: fromTopicAddressEnumVersion.description + description: fromTopicAddressEnumVersion.description, }, enumValues: fromTopicAddressEnumVersion.values.map( (x) => { return x.value; }), }); const epSdkEnumVersionTask_ExecuteReturn: IEpSdkEnumVersionTask_ExecuteReturn = await epSdkEnumVersionTask.execute(xContextId); return epSdkEnumVersionTask_ExecuteReturn.epObject; } - } /** @category Services */ diff --git a/packages/ep-sdk/src/services/EpSdkEnumsService.ts b/packages/ep-sdk/src/services/EpSdkEnumsService.ts index c73482c10..2754f4369 100644 --- a/packages/ep-sdk/src/services/EpSdkEnumsService.ts +++ b/packages/ep-sdk/src/services/EpSdkEnumsService.ts @@ -1,21 +1,81 @@ import { + CustomAttribute, + CustomAttributeDefinition, EnumsService, TopicAddressEnum, TopicAddressEnumResponse, TopicAddressEnumsResponse, } from '@solace-labs/ep-openapi-node'; +import { EEpSdkCustomAttributeEntityTypes, TEpSdkCustomAttributeList } from '../types'; import { EpSdkApiContentError, EpSdkServiceError, EpSdkLogger, EEpSdkLoggerCodes, } from '../utils'; +import EpSdkCustomAttributesService from './EpSdkCustomAttributesService'; import { EpSdkServiceClass } from './EpSdkService'; /** @category Services */ export class EpSdkEnumsServiceClass extends EpSdkServiceClass { + private async updateEnum({ xContextId, update }:{ + xContextId?: string; + update: TopicAddressEnum; + }): Promise { + const funcName = 'updateEnum'; + const logName = `${EpSdkEnumsServiceClass.name}.${funcName}()`; + /* istanbul ignore next */ + if(update.id === undefined) throw new EpSdkApiContentError(logName, this.constructor.name, 'update.id === undefined', { + update: update + }); + const topicAddressEnumResponse: TopicAddressEnumResponse = await EnumsService.updateEnum({ + xContextId, + id: update.id, + requestBody: update + }); + /* istanbul ignore next */ + if(topicAddressEnumResponse.data === undefined) throw new EpSdkApiContentError(logName, this.constructor.name, 'topicAddressEnumResponse.data === undefined', { + topicAddressEnumResponse: topicAddressEnumResponse + }); + return topicAddressEnumResponse.data; + } + + /** + * Sets the custom attributes in the list on the event api product. + * Creates attribute definitions / adds entity type 'eventApiProduct' if it doesn't exist. + */ + public async setCustomAttributes({ xContextId, enumId, epSdkCustomAttributeList, scope}:{ + xContextId?: string; + enumId: string; + epSdkCustomAttributeList: TEpSdkCustomAttributeList; + scope?: CustomAttributeDefinition.scope; + }): Promise { + const funcName = 'setCustomAttributes'; + const logName = `${EpSdkEnumsServiceClass.name}.${funcName}()`; + const topicAddressEnum: TopicAddressEnum = await this.getById({ + xContextId, + enumId: enumId, + }); + scope; + const customAttributes: Array = await EpSdkCustomAttributesService.createCustomAttributesWithNew({ + xContextId, + existingCustomAttributes: topicAddressEnum.customAttributes, + epSdkCustomAttributeList: epSdkCustomAttributeList, + epSdkCustomAttributeEntityType: EEpSdkCustomAttributeEntityTypes.ENUM, + // note: adding scope if not organization currently causes EP to return an internal server error + // scope: scope + }); + return await this.updateEnum({ + xContextId, + update: { + ...topicAddressEnum, + customAttributes: customAttributes, + } + }); + } + public getByName = async ({ xContextId, enumName, applicationDomainId }: { xContextId?: string; enumName: string; @@ -47,11 +107,10 @@ export class EpSdkEnumsServiceClass extends EpSdkServiceClass { public getById = async ({ xContextId, enumId, applicationDomainId }: { xContextId?: string; enumId: string; - applicationDomainId: string; + applicationDomainId?: string; }): Promise => { const funcName = 'getById'; const logName = `${EpSdkEnumsServiceClass.name}.${funcName}()`; - applicationDomainId; const topicAddressEnumResponse: TopicAddressEnumResponse = await EnumsService.getEnum({ xContextId: xContextId, diff --git a/packages/ep-sdk/src/services/EpSdkEpEventVersionsService.ts b/packages/ep-sdk/src/services/EpSdkEpEventVersionsService.ts index f1a2745b0..778cfed22 100644 --- a/packages/ep-sdk/src/services/EpSdkEpEventVersionsService.ts +++ b/packages/ep-sdk/src/services/EpSdkEpEventVersionsService.ts @@ -11,7 +11,8 @@ import { EventsResponse, Pagination, EventResponse, - StateChangeRequestResponse + StateChangeRequestResponse, + CustomAttributeDefinition } from '@solace-labs/ep-openapi-node'; import { EpSdkApiContentError, @@ -22,7 +23,7 @@ import { EpSdkPagination } from "../types"; import { - EpApiMaxPageSize + EpApiMaxPageSize, EpSdkCustomAttributeNameSourceApplicationDomainId } from '../constants'; import { EpSdkEpEventTask, @@ -479,6 +480,15 @@ export class EpSdkEpEventVersionsServiceClass extends EpSdkVersionServiceClass { }); if(targetEventVersion !== undefined) return targetEventVersion; } + // add the source application domain id to custom attribute + await EpSdkEpEventsService.setCustomAttributes({ + xContextId: xContextId, + eventId: epSdkEpEventTask_ExecuteReturn.epObjectKeys.epObjectId, + scope: CustomAttributeDefinition.scope.APPLICATION_DOMAIN, + epSdkCustomAttributeList: [ + { name: EpSdkCustomAttributeNameSourceApplicationDomainId, value: fromApplicationDomainId } + ] + }); // create target event version const epSdkEpEventVersionTask = new EpSdkEpEventVersionTask({ epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, diff --git a/packages/ep-sdk/src/services/EpSdkEpEventsService.ts b/packages/ep-sdk/src/services/EpSdkEpEventsService.ts index b3eb130d2..c27f4d5bc 100644 --- a/packages/ep-sdk/src/services/EpSdkEpEventsService.ts +++ b/packages/ep-sdk/src/services/EpSdkEpEventsService.ts @@ -1,6 +1,7 @@ import { ApiError, CustomAttribute, + CustomAttributeDefinition, Event as EPEvent, EventResponse, EventsResponse, @@ -62,20 +63,24 @@ export class EpSdkEpEventsServiceClass extends EpSdkServiceClass { * @param param0 * @returns */ - public async setCustomAttributes({ xContextId, eventId, epSdkCustomAttributeList}:{ + public async setCustomAttributes({ xContextId, eventId, epSdkCustomAttributeList, scope}:{ xContextId?: string; eventId: string; epSdkCustomAttributeList: TEpSdkCustomAttributeList; + scope?: CustomAttributeDefinition.scope; }): Promise { const epSdkEvent: EpSdkEvent = await this.getById({ xContextId, eventId: eventId }); + scope; const customAttributes: Array = await EpSdkCustomAttributesService.createCustomAttributesWithNew({ xContextId, existingCustomAttributes: epSdkEvent.customAttributes, epSdkCustomAttributeList: epSdkCustomAttributeList, - epSdkCustomAttributeEntityType: EEpSdkCustomAttributeEntityTypes.EVENT + epSdkCustomAttributeEntityType: EEpSdkCustomAttributeEntityTypes.EVENT, + // note: adding scope if not organization currently causes EP to return an internal server error + // scope: scope }); return await this.updateEpEvent({ xContextId, diff --git a/packages/ep-sdk/src/services/EpSdkEventApiVersionsService.ts b/packages/ep-sdk/src/services/EpSdkEventApiVersionsService.ts index d21832e8c..3d1ceec2d 100644 --- a/packages/ep-sdk/src/services/EpSdkEventApiVersionsService.ts +++ b/packages/ep-sdk/src/services/EpSdkEventApiVersionsService.ts @@ -10,13 +10,14 @@ import { StateChangeRequestResponse, EventApiResponse, Pagination, + CustomAttributeDefinition, } from '@solace-labs/ep-openapi-node'; import { EpSdkApiContentError, EpSdkValidationError } from "../utils"; import { - EpApiMaxPageSize + EpApiMaxPageSize, EpSdkCustomAttributeNameSourceApplicationDomainId } from '../constants'; import { EEpSdkObjectTypes @@ -404,6 +405,15 @@ export class EpSdkEventApiVersionsServiceClass extends EpSdkVersionServiceClass // }); // if(targetEventApiVersion !== undefined) return targetEventApiVersion; // } + // add the source application domain id to custom attribute + await EpSdkEventApisService.setCustomAttributes({ + xContextId: xContextId, + eventApiId: epSdkEventApiTask_ExecuteReturn.epObjectKeys.epObjectId, + scope: CustomAttributeDefinition.scope.APPLICATION_DOMAIN, + epSdkCustomAttributeList: [ + { name: EpSdkCustomAttributeNameSourceApplicationDomainId, value: fromApplicationDomainId } + ] + }); // create target event api version const epSdkEventApiVersionTask = new EpSdkEventApiVersionTask({ epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, diff --git a/packages/ep-sdk/src/services/EpSdkEventApisService.ts b/packages/ep-sdk/src/services/EpSdkEventApisService.ts index acefb41e5..1ba65a900 100644 --- a/packages/ep-sdk/src/services/EpSdkEventApisService.ts +++ b/packages/ep-sdk/src/services/EpSdkEventApisService.ts @@ -1,21 +1,81 @@ import { + CustomAttribute, + CustomAttributeDefinition, EventApi, EventApiResponse, EventApisResponse, EventApIsService, } from '@solace-labs/ep-openapi-node'; +import { EEpSdkCustomAttributeEntityTypes, TEpSdkCustomAttributeList } from '../types'; import { EpSdkApiContentError, EpSdkServiceError, EpSdkLogger, EEpSdkLoggerCodes } from '../utils'; +import EpSdkCustomAttributesService from './EpSdkCustomAttributesService'; import { EpSdkServiceClass } from './EpSdkService'; /** @category Services */ export class EpSdkEventApisServiceClass extends EpSdkServiceClass { + private async updateEventApi({ xContextId, update }:{ + xContextId?: string; + update: EventApi; + }): Promise { + const funcName = 'updateEpEvent'; + const logName = `${EpSdkEventApisServiceClass.name}.${funcName}()`; + /* istanbul ignore next */ + if(update.id === undefined) throw new EpSdkApiContentError(logName, this.constructor.name, 'update.id === undefined', { + update: update + }); + const eventApiResponse: EventApiResponse = await EventApIsService.updateEventApi({ + xContextId, + id: update.id, + requestBody: update + }); + /* istanbul ignore next */ + if(eventApiResponse.data === undefined) throw new EpSdkApiContentError(logName, this.constructor.name, 'eventApiResponse.data === undefined', { + eventApiResponse: eventApiResponse + }); + return eventApiResponse.data; + } + + /** + * Sets the custom attributes in the list on the application. + * Creates attribute definitions / adds entity type 'application' if it doesn't exist. + * @param param0 + * @returns + */ + public async setCustomAttributes({ xContextId, eventApiId, epSdkCustomAttributeList, scope}:{ + xContextId?: string; + eventApiId: string; + epSdkCustomAttributeList: TEpSdkCustomAttributeList; + scope?: CustomAttributeDefinition.scope; + }): Promise { + const eventApi: EventApi = await this.getById({ + xContextId, + eventApiId: eventApiId + }); + scope; + const customAttributes: Array = await EpSdkCustomAttributesService.createCustomAttributesWithNew({ + xContextId, + existingCustomAttributes: eventApi.customAttributes, + epSdkCustomAttributeList: epSdkCustomAttributeList, + epSdkCustomAttributeEntityType: EEpSdkCustomAttributeEntityTypes.EVENT_API, + // note: adding scope if not organization currently causes EP to return an internal server error + // scope: scope + }); + return await this.updateEventApi({ + xContextId, + update: { + ...eventApi, + customAttributes: customAttributes, + } + }); + } + public getByName = async({ xContextId, eventApiName, applicationDomainId }:{ xContextId?: string; eventApiName: string; diff --git a/packages/ep-sdk/src/services/EpSdkSchemaVersionsService.ts b/packages/ep-sdk/src/services/EpSdkSchemaVersionsService.ts index 276e4f5b0..f9de5040e 100644 --- a/packages/ep-sdk/src/services/EpSdkSchemaVersionsService.ts +++ b/packages/ep-sdk/src/services/EpSdkSchemaVersionsService.ts @@ -1,4 +1,5 @@ import { + CustomAttributeDefinition, Pagination, SchemaObject, SchemasService, @@ -8,7 +9,7 @@ import { StateChangeRequestResponse, } from "@solace-labs/ep-openapi-node"; import { EpSdkApiContentError, EpSdkServiceError } from "../utils"; -import { EpApiMaxPageSize } from "../constants"; +import { EpApiMaxPageSize, EpSdkCustomAttributeNameSourceApplicationDomainId } from "../constants"; import { EEpSdkTask_Action, EEpSdkTask_TargetState, @@ -320,39 +321,20 @@ export class EpSdkSchemaVersionsServiceClass extends EpSdkVersionServiceClass { const logName = `${EpSdkSchemaVersionsServiceClass.name}.${funcName}()`; // get the source schema version - const fromSchemaVersionResponse: SchemaVersionResponse = - await SchemasService.getSchemaVersion({ - xContextId, - versionId: schemaVersionId, - }); - if (fromSchemaVersionResponse.data === undefined) - throw new EpSdkServiceError( - logName, - this.constructor.name, - "fromSchemaVersionResponse.data === undefined", - { - fromSchemaVersionResponse: fromSchemaVersionResponse, - } - ); + const fromSchemaVersionResponse: SchemaVersionResponse = await SchemasService.getSchemaVersion({ + xContextId, + versionId: schemaVersionId, + }); + if (fromSchemaVersionResponse.data === undefined) throw new EpSdkServiceError(logName, this.constructor.name, "fromSchemaVersionResponse.data === undefined", { + fromSchemaVersionResponse: fromSchemaVersionResponse, + }); const fromSchemaVersion: SchemaVersion = fromSchemaVersionResponse.data; - if (fromSchemaVersion.stateId === undefined) - throw new EpSdkServiceError( - logName, - this.constructor.name, - "fromSchemaVersion.stateId === undefined", - { - fromSchemaVersion: fromSchemaVersion, - } - ); - if (fromSchemaVersion.content === undefined) - throw new EpSdkServiceError( - logName, - this.constructor.name, - "fromSchemaVersion.content === undefined", - { - fromSchemaVersion: fromSchemaVersion, - } - ); + if (fromSchemaVersion.stateId === undefined) throw new EpSdkServiceError(logName, this.constructor.name, "fromSchemaVersion.stateId === undefined", { + fromSchemaVersion: fromSchemaVersion, + }); + if (fromSchemaVersion.content === undefined) throw new EpSdkServiceError(logName, this.constructor.name, "fromSchemaVersion.content === undefined", { + fromSchemaVersion: fromSchemaVersion, + }); // get the source schema object const fromSchemaObject: SchemaObject = await EpSdkSchemasService.getById({ xContextId, @@ -380,6 +362,15 @@ export class EpSdkSchemaVersionsServiceClass extends EpSdkVersionServiceClass { }); if (targetSchemaVersion !== undefined) return targetSchemaVersion; } + // add the source application domain id to custom attribute + await EpSdkSchemasService.setCustomAttributes({ + xContextId: xContextId, + schemaId: epSdkSchemaTask_ExecuteReturn.epObjectKeys.epObjectId, + scope: CustomAttributeDefinition.scope.APPLICATION_DOMAIN, + epSdkCustomAttributeList: [ + { name: EpSdkCustomAttributeNameSourceApplicationDomainId, value: fromApplicationDomainId } + ] + }); // create target schema version const epSdkSchemaVersionTask = new EpSdkSchemaVersionTask({ epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, diff --git a/packages/ep-sdk/src/services/EpSdkSchemasService.ts b/packages/ep-sdk/src/services/EpSdkSchemasService.ts index c3423812c..093adce43 100644 --- a/packages/ep-sdk/src/services/EpSdkSchemasService.ts +++ b/packages/ep-sdk/src/services/EpSdkSchemasService.ts @@ -1,15 +1,19 @@ import { + CustomAttribute, + CustomAttributeDefinition, SchemaObject, SchemaResponse, SchemasResponse, SchemasService, } from "@solace-labs/ep-openapi-node"; +import { EEpSdkCustomAttributeEntityTypes, TEpSdkCustomAttributeList } from "../types"; import { EpSdkApiContentError, EpSdkServiceError, EpSdkLogger, EEpSdkLoggerCodes, } from "../utils"; +import EpSdkCustomAttributesService from "./EpSdkCustomAttributesService"; import { EpSdkServiceClass } from "./EpSdkService"; /** @category Services */ @@ -26,6 +30,61 @@ export enum EEpSdkSchemaContentType { /** @category Services */ export class EpSdkSchemasServiceClass extends EpSdkServiceClass { + + private async updateSchema({ xContextId, update }:{ + xContextId?: string; + update: SchemaObject; + }): Promise { + const funcName = 'updateSchema'; + const logName = `${EpSdkSchemasServiceClass.name}.${funcName}()`; + /* istanbul ignore next */ + if(update.id === undefined) throw new EpSdkApiContentError(logName, this.constructor.name, 'update.id === undefined', { + update: update + }); + const schemaResponse: SchemaResponse = await SchemasService.updateSchema({ + xContextId, + id: update.id, + requestBody: update + }); + /* istanbul ignore next */ + if(schemaResponse.data === undefined) throw new EpSdkApiContentError(logName, this.constructor.name, 'schemaResponse.data === undefined', { + schemaResponse: schemaResponse + }); + return schemaResponse.data; + } + + /** + * Sets the custom attributes in the list on the event api product. + * Creates attribute definitions / adds entity type 'eventApiProduct' if it doesn't exist. + */ + public async setCustomAttributes({ xContextId, schemaId, epSdkCustomAttributeList, scope}:{ + xContextId?: string; + schemaId: string; + epSdkCustomAttributeList: TEpSdkCustomAttributeList; + scope?: CustomAttributeDefinition.scope; + }): Promise { + const schemaObject: SchemaObject = await this.getById({ + xContextId, + schemaId: schemaId, + }); + scope; + const customAttributes: Array = await EpSdkCustomAttributesService.createCustomAttributesWithNew({ + xContextId, + existingCustomAttributes: schemaObject.customAttributes, + epSdkCustomAttributeList: epSdkCustomAttributeList, + epSdkCustomAttributeEntityType: EEpSdkCustomAttributeEntityTypes.SCHEMA_OBJECT, + // note: adding scope if not organization currently causes EP to return an internal server error + // scope: scope + }); + return await this.updateSchema({ + xContextId, + update: { + ...schemaObject, + customAttributes: customAttributes, + } + }); + } + public getByName = async ({ xContextId, schemaName, applicationDomainId }: { xContextId?: string; schemaName: string; @@ -33,77 +92,43 @@ export class EpSdkSchemasServiceClass extends EpSdkServiceClass { }): Promise => { const funcName = "getByName"; const logName = `${EpSdkSchemasServiceClass.name}.${funcName}()`; - const schemasResponse: SchemasResponse = await SchemasService.getSchemas({ xContextId, applicationDomainId: applicationDomainId, name: schemaName, }); - - EpSdkLogger.trace( - EpSdkLogger.createLogEntry(logName, { - code: EEpSdkLoggerCodes.SERVICE_GET, - module: this.constructor.name, - details: { - schemasResponse: schemasResponse, - }, - }) - ); - - if (schemasResponse.data === undefined || schemasResponse.data.length === 0) - return undefined; + EpSdkLogger.trace(EpSdkLogger.createLogEntry(logName, { code: EEpSdkLoggerCodes.SERVICE_GET, module: this.constructor.name, details: { + schemasResponse: schemasResponse, + }})); + if (schemasResponse.data === undefined || schemasResponse.data.length === 0) return undefined; /* istanbul ignore next */ - if (schemasResponse.data.length > 1) - throw new EpSdkApiContentError( - logName, - this.constructor.name, - "schemasResponse.data.length > 1", - { - schemasResponse: schemasResponse, - } - ); + if (schemasResponse.data.length > 1) throw new EpSdkApiContentError(logName, this.constructor.name, "schemasResponse.data.length > 1", { + schemasResponse: schemasResponse, + }); const epSchemaObject: SchemaObject = schemasResponse.data[0]; return epSchemaObject; }; - public getById = async ({ - xContextId, - schemaId, - applicationDomainId, - }: { + public getById = async ({ xContextId, schemaId, applicationDomainId }: { xContextId?: string; schemaId: string; - applicationDomainId: string; + applicationDomainId?: string; }): Promise => { const funcName = "getById"; const logName = `${EpSdkSchemasServiceClass.name}.${funcName}()`; - applicationDomainId; - const schemaResponse: SchemaResponse = await SchemasService.getSchema({ xContextId, id: schemaId, }); - EpSdkLogger.trace( - EpSdkLogger.createLogEntry(logName, { - code: EEpSdkLoggerCodes.SERVICE_GET, - module: this.constructor.name, - details: { - schemaResponse: schemaResponse, - }, - }) - ); - + EpSdkLogger.trace(EpSdkLogger.createLogEntry(logName, { code: EEpSdkLoggerCodes.SERVICE_GET, module: this.constructor.name, details: { + schemaResponse: schemaResponse, + }})); if (schemaResponse.data === undefined) { /* istanbul ignore next */ - throw new EpSdkApiContentError( - logName, - this.constructor.name, - "schemaResponse.data === undefined", - { - schemaId: schemaId, - } - ); + throw new EpSdkApiContentError(logName, this.constructor.name, "schemaResponse.data === undefined", { + schemaId: schemaId, + }); } const epSchemaObject: SchemaObject = schemaResponse.data; return epSchemaObject; diff --git a/packages/ep-sdk/test/specs/services/enumVersionCopy.spec.ts b/packages/ep-sdk/test/specs/services/enumVersionCopy.spec.ts index 0ad588c2e..f8191ca1e 100644 --- a/packages/ep-sdk/test/specs/services/enumVersionCopy.spec.ts +++ b/packages/ep-sdk/test/specs/services/enumVersionCopy.spec.ts @@ -178,54 +178,41 @@ describe(`${scriptName}`, () => { try { for (const enumInfo of EnumInfoList) { // get latest source version - const latestSourceTopicAddressEnumVersion: TopicAddressEnumVersion = - await EpSdkEnumVersionsService.getLatestVersionForEnumId({ - applicationDomainId: SourceApplicationDomainId, - enumId: enumInfo.sourceEnumId, - }); + const latestSourceTopicAddressEnumVersion: TopicAddressEnumVersion = await EpSdkEnumVersionsService.getLatestVersionForEnumId({ + applicationDomainId: SourceApplicationDomainId, + enumId: enumInfo.sourceEnumId, + }); // copy - const copiedTopicAddressEnumVersion: TopicAddressEnumVersion = - await EpSdkEnumVersionsService.copyLastestVersionById_IfNotExists({ - enumVersionId: latestSourceTopicAddressEnumVersion.id, - fromApplicationDomainId: SourceApplicationDomainId, - toApplicationDomainId: TargetApplicationDomainId, - }); + const copiedTopicAddressEnumVersion: TopicAddressEnumVersion = await EpSdkEnumVersionsService.copyLastestVersionById_IfNotExists({ + enumVersionId: latestSourceTopicAddressEnumVersion.id, + fromApplicationDomainId: SourceApplicationDomainId, + toApplicationDomainId: TargetApplicationDomainId, + }); enumInfo.targetEnumId = copiedTopicAddressEnumVersion.enumId; // get latest target version - const latestTargetTopicAddressEnumVersion: TopicAddressEnumVersion = - await EpSdkEnumVersionsService.getLatestVersionForEnumId({ - applicationDomainId: TargetApplicationDomainId, - enumId: copiedTopicAddressEnumVersion.enumId, - }); + const latestTargetTopicAddressEnumVersion: TopicAddressEnumVersion = await EpSdkEnumVersionsService.getLatestVersionForEnumId({ + applicationDomainId: TargetApplicationDomainId, + enumId: copiedTopicAddressEnumVersion.enumId, + }); let message = TestLogger.createLogMessage("source & target", { - latestSourceTopicAddressEnumVersion: - latestSourceTopicAddressEnumVersion, - latestTargetTopicAddressEnumVersion: - latestTargetTopicAddressEnumVersion, + latestSourceTopicAddressEnumVersion: latestSourceTopicAddressEnumVersion, + latestTargetTopicAddressEnumVersion: latestTargetTopicAddressEnumVersion, }); - const sourceCompare: Partial = - createCompareObject(latestSourceTopicAddressEnumVersion); - const targetCompare: Partial = - createCompareObject(latestTargetTopicAddressEnumVersion); + const sourceCompare: Partial = createCompareObject(latestSourceTopicAddressEnumVersion); + const targetCompare: Partial = createCompareObject(latestTargetTopicAddressEnumVersion); expect(sourceCompare, message).to.be.deep.equal(targetCompare); message = TestLogger.createLogMessage("copied & latest", { copiedTopicAddressEnumVersion: copiedTopicAddressEnumVersion, - latestTargetTopicAddressEnumVersion: - latestTargetTopicAddressEnumVersion, + latestTargetTopicAddressEnumVersion: latestTargetTopicAddressEnumVersion, }); - expect(copiedTopicAddressEnumVersion, message).to.be.deep.equal( - latestTargetTopicAddressEnumVersion - ); + expect(copiedTopicAddressEnumVersion, message).to.be.deep.equal(latestTargetTopicAddressEnumVersion); // // DEBUG // expect(false, message).to.be.true; } } catch (e) { - if (e instanceof ApiError) - expect(false, TestLogger.createApiTestFailMessage("failed")).to.be.true; - expect(e instanceof EpSdkError, TestLogger.createNotEpSdkErrorMessage(e)) - .to.be.true; - expect(false, TestLogger.createEpSdkTestFailMessage("failed", e)).to.be - .true; + if (e instanceof ApiError) expect(false, TestLogger.createApiTestFailMessage("failed")).to.be.true; + expect(e instanceof EpSdkError, TestLogger.createNotEpSdkErrorMessage(e)).to.be.true; + expect(false, TestLogger.createEpSdkTestFailMessage("failed", e)).to.be.true; } }); diff --git a/packages/ep-sdk/test/specs/tasks/schemaTask.spec.ts b/packages/ep-sdk/test/specs/tasks/schemaTask.spec.ts index c6283687a..fd43de0b9 100644 --- a/packages/ep-sdk/test/specs/tasks/schemaTask.spec.ts +++ b/packages/ep-sdk/test/specs/tasks/schemaTask.spec.ts @@ -138,12 +138,9 @@ describe(`${scriptName}`, () => { // // DEBUG // expect(false, message).to.be.true; } catch (e) { - if (e instanceof ApiError) - expect(false, TestLogger.createApiTestFailMessage("failed")).to.be.true; - expect(e instanceof EpSdkError, TestLogger.createNotEpSdkErrorMessage(e)) - .to.be.true; - expect(false, TestLogger.createEpSdkTestFailMessage("failed", e)).to.be - .true; + if (e instanceof ApiError) expect(false, TestLogger.createApiTestFailMessage("failed")).to.be.true; + expect(e instanceof EpSdkError, TestLogger.createNotEpSdkErrorMessage(e)).to.be.true; + expect(false, TestLogger.createEpSdkTestFailMessage("failed", e)).to.be.true; } }); diff --git a/packages/ep-sdk/tsconfig.json b/packages/ep-sdk/tsconfig.json index 42f5a43a3..c22a23e52 100644 --- a/packages/ep-sdk/tsconfig.json +++ b/packages/ep-sdk/tsconfig.json @@ -14,6 +14,7 @@ "skipLibCheck": true, "forceConsistentCasingInFileNames": true, "strictPropertyInitialization": false, + "noUnusedParameters": true, "sourceMap": true, "rootDir": "./src" }, From be8cb847f0aea34f535c475be0517894db5e95d7 Mon Sep 17 00:00:00 2001 From: Ricardo Gomez_Ulmke Date: Sat, 11 Mar 2023 12:40:12 +0100 Subject: [PATCH 07/33] changeset --- .changeset/ep-sdk.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.changeset/ep-sdk.md b/.changeset/ep-sdk.md index 80ad13807..373f6e294 100644 --- a/.changeset/ep-sdk.md +++ b/.changeset/ep-sdk.md @@ -6,3 +6,9 @@ added support for XML - new: `EEpSdkSchemaType.XSD` - new: `EEpSdkSchemaContentType.APPLICATION_XML` + +added source application domain id as attribute on copy + +- objects: enums, schemas, events, event apis +- name: x-ep-sdk-source-application-domain-id + value: the source application domain id From 44a323dfc59fc0967ce864ac5f0577d8c87db63d Mon Sep 17 00:00:00 2001 From: Ricardo Gomez_Ulmke Date: Sat, 11 Mar 2023 13:18:08 +0100 Subject: [PATCH 08/33] tests --- packages/ep-sdk/test/lib/TestHelpers.ts | 35 +++++++------------ .../specs/services/schemasService.spec.ts | 17 ++++----- 2 files changed, 19 insertions(+), 33 deletions(-) diff --git a/packages/ep-sdk/test/lib/TestHelpers.ts b/packages/ep-sdk/test/lib/TestHelpers.ts index 51be41362..33952887d 100644 --- a/packages/ep-sdk/test/lib/TestHelpers.ts +++ b/packages/ep-sdk/test/lib/TestHelpers.ts @@ -23,37 +23,26 @@ import { import { TestLogger } from "./TestLogger"; export class TestHelpers { - public static applicationDomainAbsent = async ({ - applicationDomainName, - }: { + + public static applicationDomainAbsent = async ({ applicationDomainName }: { applicationDomainName: string; }): Promise => { const funcName = "applicationDomainAbsent"; const logName = `${TestHelpers.name}.${funcName}()`; try { - const applicationDomainsResponse: ApplicationDomainsResponse = - await ApplicationDomainsService.getApplicationDomains({ - name: applicationDomainName, - }); - if (applicationDomainsResponse.data === undefined) - throw new Error(`${logName}: applicationDomainsResponse.data`); - if (applicationDomainsResponse.data.length > 1) - throw new Error( - `${logName}: applicationDomainsResponse.data.length > 1` - ); + const applicationDomainsResponse: ApplicationDomainsResponse = await ApplicationDomainsService.getApplicationDomains({ + name: applicationDomainName, + }); + if (applicationDomainsResponse.data === undefined) throw new Error(`${logName}: applicationDomainsResponse.data`); + if (applicationDomainsResponse.data.length > 1) throw new Error(`${logName}: applicationDomainsResponse.data.length > 1`); if (applicationDomainsResponse.data.length === 1) { - const xvoid: void = - await ApplicationDomainsService.deleteApplicationDomain({ - id: applicationDomainsResponse.data[0].id, - }); + const xvoid: void = await ApplicationDomainsService.deleteApplicationDomain({ + id: applicationDomainsResponse.data[0].id, + }); } } catch (e) { - expect( - e instanceof ApiError, - TestLogger.createNotApiErrorMessage(e.message) - ).to.be.true; - expect(false, TestLogger.createApiTestFailMessage("failed", e)).to.be - .true; + expect(e instanceof ApiError, TestLogger.createNotApiErrorMessage(e.message)).to.be.true; + expect(false, TestLogger.createApiTestFailMessage("failed", e)).to.be.true; } }; diff --git a/packages/ep-sdk/test/specs/services/schemasService.spec.ts b/packages/ep-sdk/test/specs/services/schemasService.spec.ts index 4d15ea2b7..3c06f9d3a 100644 --- a/packages/ep-sdk/test/specs/services/schemasService.spec.ts +++ b/packages/ep-sdk/test/specs/services/schemasService.spec.ts @@ -2,7 +2,7 @@ import "mocha"; import { expect } from "chai"; import path from "path"; import { TestContext, TestUtils } from "@internal/tools/src"; -import { TestLogger, TestConfig } from "../../lib"; +import { TestLogger, TestConfig, TestHelpers } from "../../lib"; import { ApiError, ApplicationDomainResponse, @@ -38,12 +38,11 @@ describe(`${scriptName}`, () => { before(async () => { initializeGlobals(); TestContext.newItId(); - const applicationDomainResponse: ApplicationDomainResponse = - await ApplicationDomainsService.createApplicationDomain({ - requestBody: { - name: ApplicationDomainName, - }, - }); + TestHelpers.applicationDomainAbsent({ applicationDomainName: ApplicationDomainName }); + const applicationDomainResponse: ApplicationDomainResponse = await ApplicationDomainsService.createApplicationDomain({ + requestBody: { + name: ApplicationDomainName, + }}); ApplicationDomainId = applicationDomainResponse.data.id; }); @@ -54,9 +53,7 @@ describe(`${scriptName}`, () => { after(async () => { TestContext.newItId(); // delete application domain - await EpSdkApplicationDomainsService.deleteById({ - applicationDomainId: ApplicationDomainId, - }); + await EpSdkApplicationDomainsService.deleteById({applicationDomainId: ApplicationDomainId }); }); it(`${scriptName}: should create schema`, async () => { From 6a6effae71e13ce433b9d916285c3e310aeede1a Mon Sep 17 00:00:00 2001 From: Ricardo Gomez_Ulmke Date: Sat, 11 Mar 2023 13:35:07 +0100 Subject: [PATCH 09/33] test --- .../test/specs/multi-domain.x-spec.ts | 13 +++++++++++++ packages/ep-sdk/src/index.ts | 1 + .../test/specs/services/schemasService.spec.ts | 2 +- 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/packages/ep-async-api-importer/test/specs/multi-domain.x-spec.ts b/packages/ep-async-api-importer/test/specs/multi-domain.x-spec.ts index 52e37bcac..c1355e7bf 100644 --- a/packages/ep-async-api-importer/test/specs/multi-domain.x-spec.ts +++ b/packages/ep-async-api-importer/test/specs/multi-domain.x-spec.ts @@ -35,6 +35,9 @@ import { IEpSdkApplicationVersionTask_ExecuteReturn, EpSdkEventApiVersionsService, EpSdkError, + EpSdkEpEventsService, + EpSdkEvent, + EpSdkCustomAttributeNameSourceApplicationDomainId } from "@solace-labs/ep-sdk"; import { TestContext, TestUtils } from "@internal/tools/src"; import { @@ -119,6 +122,7 @@ let EventApi_Name: string; let EventApi_Id: string | undefined; let EventApiVersion_Id: string | undefined; let EventApiSpec: any; +let CopiedEventApi_Id: string | undefined; let App_Name: string; let App_Id: string | undefined; @@ -146,6 +150,7 @@ const initializeGlobals = () => { EventApi_Name = "EventApi_Name"; App_Name = "App_Name"; + // AsyncApiSpecFile = TestService.validateFilePathWithReadPermission(`${TestConfig.getConfig().dataRootDir}/individual-tests/asset-domain/asset-domain-1.spec.yml`); // FileList.push(AsyncApiSpecFile); // // set test specific importer options @@ -542,6 +547,14 @@ describe(`${scriptName}`, () => { fromApplicationDomainId: ApplicationDomain_Main_Id, toApplicationDomainId: ApplicationDomain_Copy_Id, }); + expect(copiedEventApiVersion, 'copy failed').to.not.be.undefined; + CopiedEventApi_Id = copiedEventApiVersion.id; + expect(CopiedEventApi_Id, 'api content error').to.not.be.undefined; + // check that the attribute is set on the EventApi object + const epSdkEvent: EpSdkEvent = await EpSdkEpEventsService.getById({ eventId: copiedEventApiVersion.eventApiId }); + const customAttributesStr = JSON.stringify(epSdkEvent.customAttributes); + expect(customAttributesStr, 'source attribute not found').to.include(EpSdkCustomAttributeNameSourceApplicationDomainId) + // const copiedApplicationVersion: ApplicationVersion | undefined = await EpSdkApplicationVersionsService.deepCopyLastestVersionById_IfNotExists({ // eventApiName: EventApi_Name, // fromApplicationDomainId: ApplicationDomain_Main_Id, diff --git a/packages/ep-sdk/src/index.ts b/packages/ep-sdk/src/index.ts index bc9ed7055..12d78f775 100644 --- a/packages/ep-sdk/src/index.ts +++ b/packages/ep-sdk/src/index.ts @@ -2,3 +2,4 @@ export * from './utils'; export * from './types'; export * from './tasks'; export * from './services'; +export * from './constants'; diff --git a/packages/ep-sdk/test/specs/services/schemasService.spec.ts b/packages/ep-sdk/test/specs/services/schemasService.spec.ts index 3c06f9d3a..96a764d53 100644 --- a/packages/ep-sdk/test/specs/services/schemasService.spec.ts +++ b/packages/ep-sdk/test/specs/services/schemasService.spec.ts @@ -38,7 +38,7 @@ describe(`${scriptName}`, () => { before(async () => { initializeGlobals(); TestContext.newItId(); - TestHelpers.applicationDomainAbsent({ applicationDomainName: ApplicationDomainName }); + await TestHelpers.applicationDomainAbsent({ applicationDomainName: ApplicationDomainName }); const applicationDomainResponse: ApplicationDomainResponse = await ApplicationDomainsService.createApplicationDomain({ requestBody: { name: ApplicationDomainName, From af8c368cc9416497299060e2a727d98fe1db90bf Mon Sep 17 00:00:00 2001 From: Ricardo Gomez_Ulmke Date: Sat, 11 Mar 2023 15:11:23 +0100 Subject: [PATCH 10/33] enum displayname extension --- .changeset/ep-asyncapi.md | 10 ++ .../test/specs/multi-domain.x-spec.ts | 111 +++++++------ .../ep-asyncapi/src/constants/ep-xtensions.ts | 15 ++ packages/ep-asyncapi/src/constants/index.ts | 1 + .../documents/EpAsyncApiChannelDocument.ts | 24 +-- .../EpAsyncApiChannelParameterDocument.ts | 7 +- packages/ep-asyncapi/src/index.ts | 3 +- .../test/data/ep-downloads/EventApi-Name.json | 152 ++++++++++++++++++ .../ep-sdk/src/tasks/EpSdkEnumVersionTask.ts | 10 +- 9 files changed, 261 insertions(+), 72 deletions(-) create mode 100644 .changeset/ep-asyncapi.md create mode 100644 packages/ep-asyncapi/src/constants/ep-xtensions.ts create mode 100644 packages/ep-asyncapi/src/constants/index.ts create mode 100644 packages/ep-asyncapi/test/data/ep-downloads/EventApi-Name.json diff --git a/.changeset/ep-asyncapi.md b/.changeset/ep-asyncapi.md new file mode 100644 index 000000000..13be866b0 --- /dev/null +++ b/.changeset/ep-asyncapi.md @@ -0,0 +1,10 @@ +--- +"@solace-labs/ep-asyncapi": minor +--- + +added ep extensions + +- when parsing the document ep extensions are taken into consideration + - priority: + - existing extensions + - ep extensions diff --git a/packages/ep-async-api-importer/test/specs/multi-domain.x-spec.ts b/packages/ep-async-api-importer/test/specs/multi-domain.x-spec.ts index c1355e7bf..584e42a8b 100644 --- a/packages/ep-async-api-importer/test/specs/multi-domain.x-spec.ts +++ b/packages/ep-async-api-importer/test/specs/multi-domain.x-spec.ts @@ -37,7 +37,8 @@ import { EpSdkError, EpSdkEpEventsService, EpSdkEvent, - EpSdkCustomAttributeNameSourceApplicationDomainId + EpSdkCustomAttributeNameSourceApplicationDomainId, + EpSdkEventApisService } from "@solace-labs/ep-sdk"; import { TestContext, TestUtils } from "@internal/tools/src"; import { @@ -45,7 +46,13 @@ import { TestLogger, } from "../lib"; import { + CliConfig, + CliError, + CliImporterManager, + CliRunSummary, CliUtils, + ECliImporterManagerMode, + ICliRunSummary_Base, } from "../../src/cli-components"; import { EpAsyncApiDocument, EpAsyncApiDocumentService } from "@solace-labs/ep-asyncapi"; @@ -54,13 +61,6 @@ const TestSpecName = scriptName; const TestSpecId = TestUtils.getShortUUID(); TestLogger.logMessage(scriptName, ">>> starting ..."); -// TEST expects only 1 api file, not a list of api files. -let FileList: Array = []; -let AsyncApiSpecFile: string; -let AsyncApiSpecFile_X_EpApplicationDomainName: string; -let AsyncApiSpecFile_X_EpAssetApplicationDomainName: string; - - let ApplicationDomain_Events_1_Name: string; let ApplicationDomain_Events_1_Id: string | undefined; let ApplicationDomain_Events_2_Name: string; @@ -131,6 +131,13 @@ let AppVersion_Id: string | undefined; let ApplicationDomain_Copy_Name: string; let ApplicationDomain_Copy_Id: string; +let AsyncApiSpecFileNameJson: string; +// let AsyncApiSpecFile_X_EpApplicationDomainName: string; +// let AsyncApiSpecFile_X_EpAssetApplicationDomainName: string; + + + + const initializeGlobals = () => { ApplicationDomain_Events_1_Name = `${TestConfig.getAppId()}/${TestSpecName}/ApplicationDomain_Events_1_Name`; ApplicationDomain_Events_2_Name = `${TestConfig.getAppId()}/${TestSpecName}/ApplicationDomain_Events_2_Name`; @@ -151,18 +158,6 @@ const initializeGlobals = () => { EventApi_Name = "EventApi_Name"; App_Name = "App_Name"; - // AsyncApiSpecFile = TestService.validateFilePathWithReadPermission(`${TestConfig.getConfig().dataRootDir}/individual-tests/asset-domain/asset-domain-1.spec.yml`); - // FileList.push(AsyncApiSpecFile); - // // set test specific importer options - // CliConfig.getCliImporterManagerOptions().asyncApiFileList = FileList; - // CliConfig.getCliImporterManagerOptions().cliImporterManagerMode = ECliImporterManagerMode.RELEASE_MODE; - // // CliConfig.getCliImporterManagerOptions().runId = scriptName; - // // // DEBUG - // // CliConfig.getCliImporterManagerOptions().cliImporterManagerMode = ECliImporterManagerMode.TEST_MODE_KEEP; - // // CliConfig.getCliImporterManagerOptions().applicationDomainName = 'release_mode'; - // CliConfig.getCliImporterManagerOptions().createEventApiApplication = false; - // CliConfig.getCliImporterManagerOptions().cliImporterOptions.cliAssetImport_BrokerType = undefined; - // CliConfig.getCliImporterManagerOptions().cliImporterOptions.cliAssetImport_ChannelDelimiter = undefined; }; const applicationDomainTasks = async(epSdkTask_TargetState: EEpSdkTask_TargetState) => { @@ -468,6 +463,34 @@ describe(`${scriptName}`, () => { } }); + it(`${scriptName}: should deep copy event api version`, async () => { + try { + const copiedEventApiVersion: EventApiVersion | undefined = await EpSdkEventApiVersionsService.deepCopyLastestVersionById_IfNotExists({ + eventApiName: EventApi_Name, + fromApplicationDomainId: ApplicationDomain_Main_Id, + toApplicationDomainId: ApplicationDomain_Copy_Id, + }); + expect(copiedEventApiVersion, 'copy failed').to.not.be.undefined; + CopiedEventApi_Id = copiedEventApiVersion.id; + expect(CopiedEventApi_Id, 'api content error').to.not.be.undefined; + // check that the attribute is set on the EventApi object + const eventApi: EventApi = await EpSdkEventApisService.getById({ eventApiId: copiedEventApiVersion.eventApiId }); + expect(eventApi, 'EventApi is undefined').to.not.be.undefined; + const customAttributesStr = JSON.stringify(eventApi.customAttributes); + expect(customAttributesStr, 'source attribute not found in eventApi').to.include(EpSdkCustomAttributeNameSourceApplicationDomainId) + // const copiedApplicationVersion: ApplicationVersion | undefined = await EpSdkApplicationVersionsService.deepCopyLastestVersionById_IfNotExists({ + // eventApiName: EventApi_Name, + // fromApplicationDomainId: ApplicationDomain_Main_Id, + // toApplicationDomainId: ApplicationDomain_Copy_Id, + // }); + } catch (e) { + TestLogger.logMessageWithId(TestLogger.createTestFailMessageForError('error', e)); + if (e instanceof ApiError) expect(false, TestLogger.createApiTestFailMessage("failed")).to.be.true; + expect(e instanceof EpSdkError, TestLogger.createNotEpSdkErrorMessage(e)).to.be.true; + expect(false, TestLogger.createEpSdkTestFailMessage("failed", e)).to.be.true; + } + }); + it(`${scriptName}: should create the app & version`, async () => { try { const task_1 = new EpSdkApplicationTask({ @@ -524,15 +547,11 @@ describe(`${scriptName}`, () => { const applicationDomainName = epAsyncApiDocument.getApplicationDomainName(); const assetsApplicationDomainName = epAsyncApiDocument.getAssetsApplicationDomainName(); - const asyncApiSpecFileNameJson = TestConfig.getConfig().tmpDir + "/" + epAsyncApiDocument.getTitleAsFileName("json"); + AsyncApiSpecFileNameJson = TestConfig.getConfig().tmpDir + "/" + epAsyncApiDocument.getTitleAsFileName("json"); CliUtils.saveContents2File({ - filePath: asyncApiSpecFileNameJson, + filePath: AsyncApiSpecFileNameJson, content: JSON.stringify(epAsyncApiDocument.getOriginalSpecAsJson(), null, 2 ), }); - - - // console.log(`applicationDomainName = ${JSON.stringify(applicationDomainName)}`); - // console.log(`assetsApplicationDomainName = ${JSON.stringify(assetsApplicationDomainName)}`); } catch (e) { if (e instanceof ApiError) expect(false, TestLogger.createApiTestFailMessage("failed")).to.be.true; expect(e instanceof EpSdkError, TestLogger.createNotEpSdkErrorMessage(e)).to.be.true; @@ -540,29 +559,29 @@ describe(`${scriptName}`, () => { } }); - it(`${scriptName}: should deep copy event api version`, async () => { + it(`${scriptName}: should import event api spec with test`, async () => { try { - const copiedEventApiVersion: EventApiVersion | undefined = await EpSdkEventApiVersionsService.deepCopyLastestVersionById_IfNotExists({ - eventApiName: EventApi_Name, - fromApplicationDomainId: ApplicationDomain_Main_Id, - toApplicationDomainId: ApplicationDomain_Copy_Id, - }); - expect(copiedEventApiVersion, 'copy failed').to.not.be.undefined; - CopiedEventApi_Id = copiedEventApiVersion.id; - expect(CopiedEventApi_Id, 'api content error').to.not.be.undefined; - // check that the attribute is set on the EventApi object - const epSdkEvent: EpSdkEvent = await EpSdkEpEventsService.getById({ eventId: copiedEventApiVersion.eventApiId }); - const customAttributesStr = JSON.stringify(epSdkEvent.customAttributes); - expect(customAttributesStr, 'source attribute not found').to.include(EpSdkCustomAttributeNameSourceApplicationDomainId) - - // const copiedApplicationVersion: ApplicationVersion | undefined = await EpSdkApplicationVersionsService.deepCopyLastestVersionById_IfNotExists({ - // eventApiName: EventApi_Name, - // fromApplicationDomainId: ApplicationDomain_Main_Id, - // toApplicationDomainId: ApplicationDomain_Copy_Id, - // }); - expect(false, 'did the copy work?').to.be.true; + CliConfig.getCliImporterManagerOptions().asyncApiFileList = [AsyncApiSpecFileNameJson]; + CliConfig.getCliImporterManagerOptions().cliImporterManagerMode = ECliImporterManagerMode.RELEASE_MODE; + // CliConfig.getCliImporterManagerOptions().runId = scriptName; + // // DEBUG + // CliConfig.getCliImporterManagerOptions().cliImporterManagerMode = ECliImporterManagerMode.TEST_MODE_KEEP; + // CliConfig.getCliImporterManagerOptions().applicationDomainName = 'release_mode'; + CliConfig.getCliImporterManagerOptions().createEventApiApplication = true; + CliConfig.getCliImporterManagerOptions().cliImporterOptions.cliAssetImport_BrokerType = undefined; + CliConfig.getCliImporterManagerOptions().cliImporterOptions.cliAssetImport_ChannelDelimiter = undefined; + + const cliImporter = new CliImporterManager(CliConfig.getCliImporterManagerOptions()); + const xvoid: void = await cliImporter.run(); + // // DEBUG + // const cliRunSummaryList: Array = CliRunSummary.getSummaryLogList(); + // expect(false, JSON.stringify(cliRunSummaryList, null, 2)).to.be.true; + + expect(false, "not idempotent - needs to respect source app domains of all objects").to.be.true; } catch (e) { TestLogger.logMessageWithId(TestLogger.createTestFailMessageForError('error', e)); + expect( e instanceof CliError, TestLogger.createNotCliErrorMesssage(e.message)).to.be.true; + expect(false, TestLogger.createTestFailMessageWithCliError("failed", e)).to.be.true; if (e instanceof ApiError) expect(false, TestLogger.createApiTestFailMessage("failed")).to.be.true; expect(e instanceof EpSdkError, TestLogger.createNotEpSdkErrorMessage(e)).to.be.true; expect(false, TestLogger.createEpSdkTestFailMessage("failed", e)).to.be.true; diff --git a/packages/ep-asyncapi/src/constants/ep-xtensions.ts b/packages/ep-asyncapi/src/constants/ep-xtensions.ts new file mode 100644 index 000000000..aea519603 --- /dev/null +++ b/packages/ep-asyncapi/src/constants/ep-xtensions.ts @@ -0,0 +1,15 @@ +export enum EpAsyncApiParameterExtensions { + xEpEnumName = "x-ep-enum-name", + xEpParameterName = "x-ep-parameter-name", + xEpEnumVersionDisplayName = "x-ep-enum-version-displayname", +} + +export enum EpAsyncApiMessageExtensions { + xEpEventName = "x-ep-event-name", + xEpEventVersionDisplayName = "x-ep-event-version-displayname", +} + +export enum EpAsyncApiSchemaExtensions { + xEpSchemaName = "x-ep-schema-name", + xEpSchemaVersionDisplayName = "x-ep-schema-version-displayname", +} diff --git a/packages/ep-asyncapi/src/constants/index.ts b/packages/ep-asyncapi/src/constants/index.ts new file mode 100644 index 000000000..c02e10da9 --- /dev/null +++ b/packages/ep-asyncapi/src/constants/index.ts @@ -0,0 +1 @@ +export * from './ep-xtensions'; \ No newline at end of file diff --git a/packages/ep-asyncapi/src/documents/EpAsyncApiChannelDocument.ts b/packages/ep-asyncapi/src/documents/EpAsyncApiChannelDocument.ts index 864b23435..4b135ce4b 100644 --- a/packages/ep-asyncapi/src/documents/EpAsyncApiChannelDocument.ts +++ b/packages/ep-asyncapi/src/documents/EpAsyncApiChannelDocument.ts @@ -49,7 +49,9 @@ export class EpAsyncApiChannelDocument { if (this.epEventName !== undefined) return; const xEpEventName: string | undefined = this.get_X_EpEventName(); if (xEpEventName !== undefined) this.epEventName = xEpEventName; - else this.epEventName = this.asyncApiChannelKey; + else { + this.epEventName = this.asyncApiChannelKey; + } // Note: message name must NOT contain slashes '/', otherwise exported async api channel will reference a message which will NOT be found. //eslint-disable-next-line this.epEventName = this.epEventName.replaceAll(/[^0-9a-zA-Z\._]+/g, "-"); @@ -185,15 +187,11 @@ export class EpAsyncApiChannelDocument { } } // channel operations - const epAsynApiChannelPublishOperation: - | EpAsynApiChannelPublishOperation - | undefined = this.getEpAsyncApiChannelPublishOperation(); + const epAsynApiChannelPublishOperation: EpAsynApiChannelPublishOperation | undefined = this.getEpAsyncApiChannelPublishOperation(); if (epAsynApiChannelPublishOperation !== undefined) { epAsynApiChannelPublishOperation.validate(); } - const epAsynApiChannelSubscribeOperation: - | EpAsyncApiChannelSubscribeOperation - | undefined = this.getEpAsyncApiChannelSubscribeOperation(); + const epAsynApiChannelSubscribeOperation: EpAsyncApiChannelSubscribeOperation | undefined = this.getEpAsyncApiChannelSubscribeOperation(); if (epAsynApiChannelSubscribeOperation !== undefined) { epAsynApiChannelSubscribeOperation.validate(); } @@ -203,9 +201,7 @@ export class EpAsyncApiChannelDocument { // add best practices validations for channel here // channel parameters - const epAsyncApiChannelParameterDocumentMap: - | T_EpAsyncApiChannelParameterDocumentMap - | undefined = this.getEpAsyncApiChannelParameterDocumentMap(); + const epAsyncApiChannelParameterDocumentMap: T_EpAsyncApiChannelParameterDocumentMap | undefined = this.getEpAsyncApiChannelParameterDocumentMap(); if (epAsyncApiChannelParameterDocumentMap !== undefined) { for (const [ parameterName, @@ -216,15 +212,11 @@ export class EpAsyncApiChannelDocument { } } // channel operations - const epAsynApiChannelPublishOperation: - | EpAsynApiChannelPublishOperation - | undefined = this.getEpAsyncApiChannelPublishOperation(); + const epAsynApiChannelPublishOperation: EpAsynApiChannelPublishOperation | undefined = this.getEpAsyncApiChannelPublishOperation(); if (epAsynApiChannelPublishOperation !== undefined) { epAsynApiChannelPublishOperation.validate_BestPractices(); } - const epAsynApiChannelSubscribeOperation: - | EpAsyncApiChannelSubscribeOperation - | undefined = this.getEpAsyncApiChannelSubscribeOperation(); + const epAsynApiChannelSubscribeOperation: EpAsyncApiChannelSubscribeOperation | undefined = this.getEpAsyncApiChannelSubscribeOperation(); if (epAsynApiChannelSubscribeOperation !== undefined) { epAsynApiChannelSubscribeOperation.validate_BestPractices(); } diff --git a/packages/ep-asyncapi/src/documents/EpAsyncApiChannelParameterDocument.ts b/packages/ep-asyncapi/src/documents/EpAsyncApiChannelParameterDocument.ts index 1cfea6725..e41c230df 100644 --- a/packages/ep-asyncapi/src/documents/EpAsyncApiChannelParameterDocument.ts +++ b/packages/ep-asyncapi/src/documents/EpAsyncApiChannelParameterDocument.ts @@ -2,6 +2,7 @@ import { ChannelParameter, Schema, } from '@asyncapi/parser'; +import { EpAsyncApiParameterExtensions } from '../constants'; export class EpAsyncApiChannelParameterDocument { private channelParameterName: string; @@ -28,7 +29,11 @@ export class EpAsyncApiChannelParameterDocument { return ''; } - public getDisplayName(): string { return this.channelParameterName; } + public getDisplayName(): string | undefined { + if(this.asyncApiChannelParameter.hasExtension(EpAsyncApiParameterExtensions.xEpEnumVersionDisplayName)) { + return this.asyncApiChannelParameter.extension(EpAsyncApiParameterExtensions.xEpEnumVersionDisplayName); + } + } public getParameterEnumValueList(): Array { const schema: Schema = this.asyncApiChannelParameter.schema(); diff --git a/packages/ep-asyncapi/src/index.ts b/packages/ep-asyncapi/src/index.ts index 71abd557d..9917f2495 100644 --- a/packages/ep-asyncapi/src/index.ts +++ b/packages/ep-asyncapi/src/index.ts @@ -1,3 +1,4 @@ export * from './documents'; export * from './services'; -export * from './utils'; \ No newline at end of file +export * from './utils'; +export * from './constants'; \ No newline at end of file diff --git a/packages/ep-asyncapi/test/data/ep-downloads/EventApi-Name.json b/packages/ep-asyncapi/test/data/ep-downloads/EventApi-Name.json new file mode 100644 index 000000000..4fafc4332 --- /dev/null +++ b/packages/ep-asyncapi/test/data/ep-downloads/EventApi-Name.json @@ -0,0 +1,152 @@ +{ + "components": { + "schemas": { + "Schema_2_Name": { + "x-ep-schema-version": "1.0.0", + "x-ep-schema-state-id": "2", + "x-ep-schema-version-id": "n00r9bespvj", + "x-ep-schema-id": "bx9070aj3mu", + "description": "Generic message header.", + "x-ep-schema-state-name": "RELEASED", + "x-ep-schema-name": "Schema_2_Name", + "type": "object", + "properties": { + "sentAt": { + "format": "date-time", + "description": "Date and time when the message was sent.", + "type": "string" + }, + "storeId": { + "description": "The store id.", + "type": "string" + }, + "transactionId": { + "description": "The transaction id.", + "type": "string" + } + }, + "required": ["sentAt", "transactionId", "storeId"], + "x-ep-schema-version-displayname": "Schema_2_Id" + }, + "Schema_1_Name": { + "x-ep-schema-version": "1.0.0", + "x-ep-schema-state-id": "2", + "x-ep-schema-version-id": "loyscnlazj5", + "x-ep-schema-id": "5e95l0jqxlt", + "description": "Generic message header.", + "x-ep-schema-state-name": "RELEASED", + "x-ep-schema-name": "Schema_1_Name", + "type": "object", + "properties": { + "sentAt": { + "format": "date-time", + "description": "Date and time when the message was sent.", + "type": "string" + }, + "storeId": { + "description": "The store id.", + "type": "string" + }, + "transactionId": { + "description": "The transaction id.", + "type": "string" + } + }, + "required": ["sentAt", "transactionId", "storeId"], + "x-ep-schema-version-displayname": "Schema_1_Id" + } + }, + "messages": { + "Event_2_Name": { + "x-ep-event-id": "oumr2wycciv", + "x-ep-event-version-displayname": "Event_2_Id", + "x-ep-event-version-id": "ifg6vpksml9", + "payload": { + "$ref": "#/components/schemas/Schema_2_Name" + }, + "x-ep-event-version": "1.0.0", + "x-ep-event-name": "Event_2_Name", + "description": "Event_2_Id", + "schemaFormat": "application/vnd.aai.asyncapi+json;version=2.0.0", + "contentType": "application/json", + "x-ep-event-state-id": "2", + "x-ep-event-state-name": "RELEASED" + }, + "Event_1_Name": { + "x-ep-event-id": "7jhc9d369ob", + "x-ep-event-version-displayname": "Event_1_Id", + "x-ep-event-version-id": "mvi0eewza58", + "payload": { + "$ref": "#/components/schemas/Schema_1_Name" + }, + "x-ep-event-version": "1.0.0", + "x-ep-event-name": "Event_1_Name", + "description": "Event_1_Id", + "schemaFormat": "application/vnd.aai.asyncapi+json;version=2.0.0", + "contentType": "application/json", + "x-ep-event-state-id": "2", + "x-ep-event-state-name": "RELEASED" + } + } + }, + "channels": { + "topic/{Enum_2_Name}/_2_": { + "publish": { + "message": { + "$ref": "#/components/messages/Event_2_Name" + } + }, + "parameters": { + "Enum_2_Name": { + "schema": { + "type": "string", + "enum": ["value1", "value2"] + }, + "x-ep-enum-version-displayname": "Enum_2_Id", + "x-ep-enum-version": "1.0.0", + "x-ep-enum-name": "Enum_2_Name", + "x-ep-enum-state-id": "2", + "x-ep-enum-version-id": "xix16gkl5a2", + "x-ep-enum-id": "dte6uczbac1", + "x-ep-parameter-name": "Enum_2_Name" + } + } + }, + "topic/{Enum_1_Name}/_1_": { + "subscribe": { + "message": { + "$ref": "#/components/messages/Event_1_Name" + } + }, + "parameters": { + "Enum_1_Name": { + "schema": { + "type": "string", + "enum": ["value1", "value2"] + }, + "x-ep-enum-version-displayname": "Enum_1_Id", + "x-ep-enum-version": "1.0.0", + "x-ep-enum-name": "Enum_1_Name", + "x-ep-enum-state-id": "2", + "x-ep-enum-version-id": "fg7m5qrcs4v", + "x-ep-enum-id": "7tsxzoiznu9", + "x-ep-parameter-name": "Enum_1_Name" + } + } + } + }, + "asyncapi": "2.5.0", + "info": { + "x-ep-event-api-version": "1.0.0", + "x-ep-event-api-id": "lp6umylv3v0", + "description": "EventApi_Id", + "x-ep-displayname": "EventApi_Id", + "x-ep-state-name": "RELEASED", + "title": "EventApi_Name", + "x-ep-application-domain-id": "9kf35bbrm4l", + "version": "1.0.0", + "x-ep-state-id": "2", + "x-ep-event-api-version-id": "ehl0ysygev4", + "x-ep-application-domain-name": "TEST_EP_ASYNC_API_IMPORTER/multi-domain.x-spec.ts/ApplicationDomain_Main_Name" + } +} diff --git a/packages/ep-sdk/src/tasks/EpSdkEnumVersionTask.ts b/packages/ep-sdk/src/tasks/EpSdkEnumVersionTask.ts index 17aafa188..d16be635f 100644 --- a/packages/ep-sdk/src/tasks/EpSdkEnumVersionTask.ts +++ b/packages/ep-sdk/src/tasks/EpSdkEnumVersionTask.ts @@ -28,14 +28,8 @@ import { } from "./EpSdkVersionTask"; /** @category Tasks */ -export type TEpSdkEnumVersionTask_Settings = Required< - Pick -> & - Pick; -type TEpSdkEnumVersionTask_CompareObject = - Partial & - Pick & - Partial>; +export type TEpSdkEnumVersionTask_Settings = Required> & Pick; +type TEpSdkEnumVersionTask_CompareObject = Partial & Pick & Partial>; /** @category Tasks */ export interface IEpSdkEnumVersionTask_Config extends IEpSdkVersionTask_Config { From b21e2980ff1415e9edb3ef0aaf5d2672cf6c568f Mon Sep 17 00:00:00 2001 From: Ricardo Gomez_Ulmke Date: Sat, 11 Mar 2023 15:44:47 +0100 Subject: [PATCH 11/33] schema name, displayname & description --- .../src/importers/CliAssetsImporter.ts | 68 ++++++------------- .../documents/EpAsyncApiChannelDocument.ts | 14 +--- .../documents/EpAsyncApiMessageDocument.ts | 20 ++++-- .../src/tasks/EpSdkEpEventVersionTask.ts | 2 +- .../src/tasks/EpSdkSchemaVersionTask.ts | 8 +-- packages/ep-sdk/src/tasks/EpSdkTask.ts | 3 +- 6 files changed, 41 insertions(+), 74 deletions(-) diff --git a/packages/ep-async-api-importer/src/importers/CliAssetsImporter.ts b/packages/ep-async-api-importer/src/importers/CliAssetsImporter.ts index a1ef1d5bc..ca2cf63ad 100644 --- a/packages/ep-async-api-importer/src/importers/CliAssetsImporter.ts +++ b/packages/ep-async-api-importer/src/importers/CliAssetsImporter.ts @@ -171,24 +171,13 @@ export abstract class CliAssetsImporter extends CliImporter { // CliRunContext.updateContext({ // runContext: rctxt // }); - CliLogger.debug( - CliLogger.createLogEntry(logName, { - code: ECliStatusCodes.IMPORTING_API_CHANNEL_MESSAGE, - details: { - epEventName: epEventName, - channelTopic: channelTopic, - }, - }) - ); - CliLogger.trace( - CliLogger.createLogEntry(logName, { - code: ECliStatusCodes.IMPORTING_API_CHANNEL_MESSAGE, - details: { - epAsyncApiMessageDocument: epAsyncApiMessageDocument, - }, - }) - ); - + CliLogger.debug(CliLogger.createLogEntry(logName, { code: ECliStatusCodes.IMPORTING_API_CHANNEL_MESSAGE, details: { + epEventName: epEventName, + channelTopic: channelTopic, + }})); + CliLogger.trace(CliLogger.createLogEntry(logName, { code: ECliStatusCodes.IMPORTING_API_CHANNEL_MESSAGE, details: { + epAsyncApiMessageDocument: epAsyncApiMessageDocument, + }})); // present event const epSdkEpEventTask = new EpSdkEpEventTask({ epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, @@ -266,7 +255,7 @@ export abstract class CliAssetsImporter extends CliImporter { schemaVersionSettings: { content: JSON.stringify(epAsyncApiMessageDocument.getSchemaAsSanitizedJson()), description: epAsyncApiMessageDocument.getDescription(), - displayName: epAsyncApiMessageDocument.getMessageName(), + displayName: epAsyncApiMessageDocument.getPayloadSchemaDisplayName(), stateId: this.get_EpSdkTask_StateId(), }, epSdkTask_TransactionConfig: this.get_IEpSdkTask_TransactionConfig(), @@ -305,26 +294,16 @@ export abstract class CliAssetsImporter extends CliImporter { }; CliRunContext.push(rctxt); - CliLogger.debug( - CliLogger.createLogEntry(logName, { - code: ECliStatusCodes.IMPORTING_API_CHANNEL_MESSAGE, - details: {}, - }) - ); - CliLogger.trace( - CliLogger.createLogEntry(logName, { - code: ECliStatusCodes.IMPORTING_API_CHANNEL_MESSAGE, - details: { - epAsyncApiMessageDocument: epAsyncApiMessageDocument, - }, - }) - ); + CliLogger.debug(CliLogger.createLogEntry(logName, { code: ECliStatusCodes.IMPORTING_API_CHANNEL_MESSAGE, details: {} })); + CliLogger.trace(CliLogger.createLogEntry(logName, { code: ECliStatusCodes.IMPORTING_API_CHANNEL_MESSAGE, details: { + epAsyncApiMessageDocument: epAsyncApiMessageDocument, + }})); // present schema const epSdkSchemaTask = new EpSdkSchemaTask({ epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, applicationDomainId: assetApplicationDomainId, - schemaName: epAsyncApiMessageDocument.getMessageName(), + schemaName: epAsyncApiMessageDocument.getPayloadSchemaName(), schemaObjectSettings: { contentType: CliAsyncApiDocumentService.map_MessageDocumentContentType_To_EpSchemaContentType( @@ -339,20 +318,13 @@ export abstract class CliAssetsImporter extends CliImporter { epSdkTask_TransactionConfig: this.get_IEpSdkTask_TransactionConfig(), checkmode: checkmode, }); - const epSdkSchemaTask_ExecuteReturn: IEpSdkSchemaTask_ExecuteReturn = - await this.executeTask({ - epSdkTask: epSdkSchemaTask, - expectNoAction: checkmode, - }); - CliLogger.trace( - CliLogger.createLogEntry(logName, { - code: ECliStatusCodes.IMPORTING_EP_SCHEMA, - details: { - epSdkSchemaTask_ExecuteReturn: epSdkSchemaTask_ExecuteReturn, - }, - }) - ); - + const epSdkSchemaTask_ExecuteReturn: IEpSdkSchemaTask_ExecuteReturn = await this.executeTask({ + epSdkTask: epSdkSchemaTask, + expectNoAction: checkmode, + }); + CliLogger.trace(CliLogger.createLogEntry(logName, { code: ECliStatusCodes.IMPORTING_EP_SCHEMA, details: { + epSdkSchemaTask_ExecuteReturn: epSdkSchemaTask_ExecuteReturn, + }})); // present the schema version const epSdkSchemaVersionTask_ExecuteReturn: IEpSdkSchemaVersionTask_ExecuteReturn = await this.run_present_schema_version({ diff --git a/packages/ep-asyncapi/src/documents/EpAsyncApiChannelDocument.ts b/packages/ep-asyncapi/src/documents/EpAsyncApiChannelDocument.ts index 4b135ce4b..46a0dc108 100644 --- a/packages/ep-asyncapi/src/documents/EpAsyncApiChannelDocument.ts +++ b/packages/ep-asyncapi/src/documents/EpAsyncApiChannelDocument.ts @@ -242,12 +242,7 @@ export class EpAsyncApiChannelDocument { this.createEpEventName(); this.validate_EpName(); } - if (this.epEventName === undefined) - throw new EpAsyncApiInternalError( - logName, - this.constructor.name, - "this.epEventName === undefined" - ); + if (this.epEventName === undefined) throw new EpAsyncApiInternalError(logName, this.constructor.name, "this.epEventName === undefined"); return this.epEventName; } @@ -258,12 +253,7 @@ export class EpAsyncApiChannelDocument { this.createEpEventVersionName(); this.validate_EpEventVersionName(); } - if (this.epEventVersionName === undefined) - throw new EpAsyncApiInternalError( - logName, - this.constructor.name, - "this.epEventVersionName === undefined" - ); + if (this.epEventVersionName === undefined) throw new EpAsyncApiInternalError(logName, this.constructor.name, "this.epEventVersionName === undefined"); return this.epEventVersionName; } diff --git a/packages/ep-asyncapi/src/documents/EpAsyncApiMessageDocument.ts b/packages/ep-asyncapi/src/documents/EpAsyncApiMessageDocument.ts index 53237a926..05cb01837 100644 --- a/packages/ep-asyncapi/src/documents/EpAsyncApiMessageDocument.ts +++ b/packages/ep-asyncapi/src/documents/EpAsyncApiMessageDocument.ts @@ -2,6 +2,7 @@ import { Message, Schema } from '@asyncapi/parser'; +import { EpAsyncApiSchemaExtensions } from '../constants'; import { EpAsyncApiUtils, EpAsyncApiMessageError, @@ -117,8 +118,6 @@ export class EpAsyncApiMessageDocument { } } - public getMessageKey(): string { return this.asyncApiMessageKey; } - public getMessageName(): string { // const funcName = 'getMessageName'; // const logName = `${EpAsyncApiMessageDocument.name}.${funcName}()`; @@ -142,12 +141,11 @@ export class EpAsyncApiMessageDocument { return JSON.stringify(schema.json()); } - public getDescription(): string { + public getDescription(): string | undefined { const description: string | null = this.asyncApiMessage.description(); const summary: string | null = this.asyncApiMessage.summary(); if(description) return description; if(summary) return summary; - return ''; } public getMessageNameAsFilePath(): string { @@ -157,8 +155,18 @@ export class EpAsyncApiMessageDocument { public getPayloadSchemaName(): string { const schema: Schema = this.asyncApiMessage.payload(); let name: string | undefined = schema.title(); - if(!name) name = this.getMessageName(); - return name; + if(name !== undefined) return name; + if(schema.hasExtension(EpAsyncApiSchemaExtensions.xEpSchemaName)) { + return schema.extension(EpAsyncApiSchemaExtensions.xEpSchemaName); + } + return this.getMessageName(); + } + + public getPayloadSchemaDisplayName(): string | undefined { + const schema: Schema = this.asyncApiMessage.payload(); + if(schema.hasExtension(EpAsyncApiSchemaExtensions.xEpSchemaVersionDisplayName)) { + return schema.extension(EpAsyncApiSchemaExtensions.xEpSchemaVersionDisplayName); + } } public getSchemaFileName(): string { diff --git a/packages/ep-sdk/src/tasks/EpSdkEpEventVersionTask.ts b/packages/ep-sdk/src/tasks/EpSdkEpEventVersionTask.ts index 70f815855..63a3b9f2d 100644 --- a/packages/ep-sdk/src/tasks/EpSdkEpEventVersionTask.ts +++ b/packages/ep-sdk/src/tasks/EpSdkEpEventVersionTask.ts @@ -37,7 +37,7 @@ import { /** @category Tasks */ export type TEpSdkEpEventVersionTask_Settings_DeliveryDescriptor = Pick; /** @category Tasks */ -export type TEpSdkEpEventVersionTask_Settings = Required> & TEpSdkEpEventVersionTask_Settings_DeliveryDescriptor; +export type TEpSdkEpEventVersionTask_Settings = Required> & Pick & TEpSdkEpEventVersionTask_Settings_DeliveryDescriptor; type TEpSdkEpEventVersionTask_CompareObject = Partial & Pick & Partial>; /** @category Tasks */ diff --git a/packages/ep-sdk/src/tasks/EpSdkSchemaVersionTask.ts b/packages/ep-sdk/src/tasks/EpSdkSchemaVersionTask.ts index 1e8a1f7aa..74a4f94ed 100644 --- a/packages/ep-sdk/src/tasks/EpSdkSchemaVersionTask.ts +++ b/packages/ep-sdk/src/tasks/EpSdkSchemaVersionTask.ts @@ -24,12 +24,8 @@ import { } from "./EpSdkVersionTask"; /** @category Tasks */ -export type TEpSdkSchemaVersionTask_Settings = Required< - Pick ->; -type TEpSdkSchemaVersionTask_CompareObject = - Partial & - Partial>; +export type TEpSdkSchemaVersionTask_Settings = Required> & Pick; +type TEpSdkSchemaVersionTask_CompareObject = Partial & Partial>; /** @category Tasks */ export interface IEpSdkSchemaVersionTask_Config diff --git a/packages/ep-sdk/src/tasks/EpSdkTask.ts b/packages/ep-sdk/src/tasks/EpSdkTask.ts index 0bc814142..7dc424801 100644 --- a/packages/ep-sdk/src/tasks/EpSdkTask.ts +++ b/packages/ep-sdk/src/tasks/EpSdkTask.ts @@ -156,7 +156,8 @@ export abstract class EpSdkTask { return epSdkTask_Config; } - protected truncate(str: string, maxLength: number | undefined): string { + protected truncate(str: string | undefined, maxLength: number | undefined): string| undefined { + if(str === undefined) return undefined; if (maxLength !== undefined && str.length > maxLength) return str.slice(0, maxLength - 4) + "..."; return str; From d8eb874825b3f361fda3f667875d3d7cc8ad2d6e Mon Sep 17 00:00:00 2001 From: Ricardo Gomez_Ulmke Date: Sat, 11 Mar 2023 15:52:34 +0100 Subject: [PATCH 12/33] lint --- packages/ep-asyncapi/src/documents/EpAsyncApiMessageDocument.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/ep-asyncapi/src/documents/EpAsyncApiMessageDocument.ts b/packages/ep-asyncapi/src/documents/EpAsyncApiMessageDocument.ts index 05cb01837..ad64df23e 100644 --- a/packages/ep-asyncapi/src/documents/EpAsyncApiMessageDocument.ts +++ b/packages/ep-asyncapi/src/documents/EpAsyncApiMessageDocument.ts @@ -154,7 +154,7 @@ export class EpAsyncApiMessageDocument { public getPayloadSchemaName(): string { const schema: Schema = this.asyncApiMessage.payload(); - let name: string | undefined = schema.title(); + const name: string | undefined = schema.title(); if(name !== undefined) return name; if(schema.hasExtension(EpAsyncApiSchemaExtensions.xEpSchemaName)) { return schema.extension(EpAsyncApiSchemaExtensions.xEpSchemaName); From 6b07d07d094648fb6d6076c5783e28fc9811cc6d Mon Sep 17 00:00:00 2001 From: Ricardo Gomez_Ulmke Date: Sat, 11 Mar 2023 16:06:57 +0100 Subject: [PATCH 13/33] tests --- .../test/specs/ep-idempotency.x-spec.ts | 524 ++++++++++++++++++ ...main.x-spec.ts => multi-domain.xx-spec.ts} | 0 packages/ep-asyncapi/.nycrc | 2 +- 3 files changed, 525 insertions(+), 1 deletion(-) create mode 100644 packages/ep-async-api-importer/test/specs/ep-idempotency.x-spec.ts rename packages/ep-async-api-importer/test/specs/{multi-domain.x-spec.ts => multi-domain.xx-spec.ts} (100%) diff --git a/packages/ep-async-api-importer/test/specs/ep-idempotency.x-spec.ts b/packages/ep-async-api-importer/test/specs/ep-idempotency.x-spec.ts new file mode 100644 index 000000000..01b2fef11 --- /dev/null +++ b/packages/ep-async-api-importer/test/specs/ep-idempotency.x-spec.ts @@ -0,0 +1,524 @@ +import "mocha"; +import { expect } from "chai"; +import path from "path"; +import { + ApiError, + EventApi, + EventApIsService, + EventApiVersion, +} from "@solace-labs/ep-openapi-node"; +import { + EEpSdkTask_TargetState, + EpSdkApplicationDomainTask, + EpSdkEnumTask, + EpSdkEnumVersionTask, + EpSdkSchemaTask, + EpSdkSchemaVersionTask, + EpSdkStatesService, + IEpSdkApplicationDomainTask_ExecuteReturn, + IEpSdkEnumTask_ExecuteReturn, + IEpSdkEnumVersionTask_ExecuteReturn, + IEpSdkSchemaTask_ExecuteReturn, + IEpSdkSchemaVersionTask_ExecuteReturn, + EpSdkEpEventTask, + EpSdkBrokerTypes, + IEpSdkEpEventTask_ExecuteReturn, + EpSdkEpEventVersionTask, + IEpSdkEpEventVersionTask_ExecuteReturn, + EpSdkEventApiTask, + IEpSdkEventApiTask_ExecuteReturn, + EpSdkEventApiVersionTask, + IEpSdkEventApiVersionTask_ExecuteReturn, + EpSdkApplicationTask, + IEpSdkApplicationTask_ExecuteReturn, + EpSdkApplicationVersionTask, + IEpSdkApplicationVersionTask_ExecuteReturn, + EpSdkEventApiVersionsService, + EpSdkError, + EpSdkCustomAttributeNameSourceApplicationDomainId, + EpSdkEventApisService, + EpSdkEnumVersionsService, + EpSdkSchemaVersionsService, + EpSdkEpEventVersionsService +} from "@solace-labs/ep-sdk"; +import { TestContext, TestUtils } from "@internal/tools/src"; +import { + TestConfig, + TestLogger, +} from "../lib"; +import { + CliConfig, + CliError, + CliImporterManager, + CliUtils, + ECliImporterManagerMode, +} from "../../src/cli-components"; +import { + EpAsyncApiDocument, + EpAsyncApiDocumentService +} from "@solace-labs/ep-asyncapi"; + +const scriptName: string = path.basename(__filename); +const TestSpecName = scriptName; +const TestSpecId = TestUtils.getShortUUID(); +TestLogger.logMessage(scriptName, ">>> starting ..."); + +let ApplicationDomain_Name: string; +let ApplicationDomain_Id: string | undefined; + +let Schema_1_Name: string; +let Schema_1_Id: string | undefined; +let SchemaVersion_1_Id: string | undefined; +let Schema_2_Name: string; +let Schema_2_Id: string | undefined; +let SchemaVersion_2_Id: string | undefined; +const SchemaContent = ` +{ + "description": "Generic message header.", + "type": "object", + "properties": { + "sentAt": { + "type": "string", + "format": "date-time", + "description": "Date and time when the message was sent." + }, + "transactionId": { + "type": "string", + "description": "The transaction id." + }, + "storeId": { + "type": "string", + "description": "The store id." + } + }, + "required": [ + "sentAt", + "transactionId", + "storeId" + ] +} +`; + +let Enum_1_Name: string; +let Enum_1_Id: string | undefined; +let EnumVersion_1_Id: string | undefined; +let Enum_2_Name: string; +let Enum_2_Id: string | undefined; +let EnumVersion_2_Id: string | undefined; +const EnumValues = ['value1', 'value2']; + +let Event_1_Name: string; +let Event_1_Id: string | undefined; +let EventVersion_1_Id: string | undefined; +let Event_2_Name: string; +let Event_2_Id: string | undefined; +let EventVersion_2_Id: string | undefined; +let TopicString_1: string; +let TopicString_2: string; + +let EventApi_Name: string; +let EventApi_Id: string | undefined; +let EventApiVersion_Id: string | undefined; +let EventApiSpec: any; +let CopiedEventApi_Id: string | undefined; + +let App_Name: string; +let App_Id: string | undefined; +let AppVersion_Id: string | undefined; + +let AsyncApiSpecFileNameJson: string; + +const initializeGlobals = () => { + ApplicationDomain_Name = `${TestConfig.getAppId()}/${TestSpecName}`; + + Schema_1_Name = 'Schema_1_Name'; + Schema_2_Name = 'Schema_2_Name'; + + Enum_1_Name = 'Enum_1_Name'; + Enum_2_Name = 'Enum_2_Name'; + + Event_1_Name = 'Event_1_Name'; + Event_2_Name = 'Event_2_Name'; + TopicString_1 = 'topic/{Enum_1_Name}/_1_'; + TopicString_2 = 'topic/{Enum_2_Name}/_2_'; + + EventApi_Name = "EventApi_Name"; + App_Name = "App_Name"; + +}; + +const applicationDomainTasks = async(epSdkTask_TargetState: EEpSdkTask_TargetState) => { + const task_1 = new EpSdkApplicationDomainTask({ + applicationDomainName: ApplicationDomain_Name, + epSdkTask_TargetState: epSdkTask_TargetState + }); + const task1_ExecuteReturn: IEpSdkApplicationDomainTask_ExecuteReturn = await task_1.execute('xContextId'); + ApplicationDomain_Id = task1_ExecuteReturn.epObject ? task1_ExecuteReturn.epObject.id : undefined; +} + +describe(`${scriptName}`, () => { + before(async () => { + TestContext.newItId(); + initializeGlobals(); + }); + + beforeEach(() => { + TestContext.newItId(); + }); + + after(async () => { + TestContext.newItId(); + }); + + it(`${scriptName}: should setup the domains`, async () => { + try { + await applicationDomainTasks(EEpSdkTask_TargetState.ABSENT); + await applicationDomainTasks(EEpSdkTask_TargetState.PRESENT); + } catch (e) { + if (e instanceof ApiError) expect(false, TestLogger.createApiTestFailMessage("failed")).to.be.true; + expect(e instanceof EpSdkError, TestLogger.createNotEpSdkErrorMessage(e)).to.be.true; + expect(false, TestLogger.createEpSdkTestFailMessage("failed", e)).to.be.true; + } + }); + + it(`${scriptName}: should create the schemas & versions`, async () => { + try { + const task_1 = new EpSdkSchemaTask({ + epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, + applicationDomainId: ApplicationDomain_Id, + schemaName: Schema_1_Name, + schemaObjectSettings: { + shared: true, + }, + }); + const task_1_ExecuteReturn: IEpSdkSchemaTask_ExecuteReturn = await task_1.execute(); + Schema_1_Id = task_1_ExecuteReturn.epObject.id; + + const task_1_1 = new EpSdkSchemaVersionTask({ + epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, + applicationDomainId: ApplicationDomain_Id, + schemaId: Schema_1_Id, + versionString: "1.0.0", + schemaVersionSettings: { + stateId: EpSdkStatesService.releasedId, + displayName: 'Schema_1_Id', + description: 'Schema_1_Id', + content: SchemaContent, + }, + }); + const task_1_1_ExecuteReturn: IEpSdkSchemaVersionTask_ExecuteReturn = await task_1_1.execute(); + SchemaVersion_1_Id = task_1_1_ExecuteReturn.epObject.id; + + const task_2 = new EpSdkSchemaTask({ + epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, + applicationDomainId: ApplicationDomain_Id, + schemaName: Schema_2_Name, + schemaObjectSettings: { + shared: true, + }, + }); + const task_2_ExecuteReturn: IEpSdkSchemaTask_ExecuteReturn = await task_2.execute(); + Schema_2_Id = task_2_ExecuteReturn.epObject.id; + + const task_2_1 = new EpSdkSchemaVersionTask({ + epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, + applicationDomainId: ApplicationDomain_Id, + schemaId: Schema_2_Id, + versionString: "1.0.0", + schemaVersionSettings: { + stateId: EpSdkStatesService.releasedId, + displayName: 'Schema_2_Id', + description: 'Schema_2_Id', + content: SchemaContent, + }, + }); + const task_2_1_ExecuteReturn: IEpSdkSchemaVersionTask_ExecuteReturn = await task_2_1.execute(); + SchemaVersion_2_Id = task_2_1_ExecuteReturn.epObject.id; + } catch (e) { + if (e instanceof ApiError) expect(false, TestLogger.createApiTestFailMessage("failed")).to.be.true; + expect(e instanceof EpSdkError, TestLogger.createNotEpSdkErrorMessage(e)).to.be.true; + expect(false, TestLogger.createEpSdkTestFailMessage("failed", e)).to.be.true; + } + }); + + it(`${scriptName}: should create the enums & versions`, async () => { + try { + const task_1 = new EpSdkEnumTask({ + epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, + applicationDomainId: ApplicationDomain_Id, + enumName: Enum_1_Name, + enumObjectSettings: { + shared: true, + } + }); + const task_1_ExecuteReturn: IEpSdkEnumTask_ExecuteReturn = await task_1.execute(); + Enum_1_Id = task_1_ExecuteReturn.epObject.id; + const task_1_1 = new EpSdkEnumVersionTask({ + epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, + applicationDomainId: ApplicationDomain_Id, + enumId: Enum_1_Id, + versionString: "1.0.0", + enumVersionSettings: { + stateId: EpSdkStatesService.releasedId, + displayName: 'Enum_1_Id', + description: 'Enum_1_Id', + }, + enumValues: EnumValues + }); + const task_1_1_ExecuteReturn: IEpSdkEnumVersionTask_ExecuteReturn = await task_1_1.execute(); + EnumVersion_1_Id = task_1_1_ExecuteReturn.epObject.id; + + const task_2 = new EpSdkEnumTask({ + epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, + applicationDomainId: ApplicationDomain_Id, + enumName: Enum_2_Name, + enumObjectSettings: { + shared: true, + } + }); + const task_2_ExecuteReturn: IEpSdkEnumTask_ExecuteReturn = await task_2.execute(); + Enum_2_Id = task_2_ExecuteReturn.epObject.id; + const task_2_1 = new EpSdkEnumVersionTask({ + epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, + applicationDomainId: ApplicationDomain_Id, + enumId: Enum_2_Id, + versionString: "1.0.0", + enumVersionSettings: { + stateId: EpSdkStatesService.releasedId, + displayName: 'Enum_2_Id', + description: 'Enum_2_Id', + }, + enumValues: EnumValues + }); + const task_2_1_ExecuteReturn: IEpSdkEnumVersionTask_ExecuteReturn = await task_2_1.execute(); + EnumVersion_2_Id = task_2_1_ExecuteReturn.epObject.id; + + } catch (e) { + if (e instanceof ApiError) expect(false, TestLogger.createApiTestFailMessage("failed")).to.be.true; + expect(e instanceof EpSdkError, TestLogger.createNotEpSdkErrorMessage(e)).to.be.true; + expect(false, TestLogger.createEpSdkTestFailMessage("failed", e)).to.be.true; + } + }); + + it(`${scriptName}: should create the events & versions`, async () => { + try { + const task_1 = new EpSdkEpEventTask({ + epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, + applicationDomainId: ApplicationDomain_Id, + eventName: Event_1_Name, + eventObjectSettings: { + brokerType: EpSdkBrokerTypes.Solace, + shared: true + } + }); + const task_1_ExecuteReturn: IEpSdkEpEventTask_ExecuteReturn = await task_1.execute(); + Event_1_Id = task_1_ExecuteReturn.epObject.id; + const task_1_1 = new EpSdkEpEventVersionTask({ + epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, + applicationDomainId: ApplicationDomain_Id, + eventId: Event_1_Id, + versionString: "1.0.0", + eventVersionSettings: { + displayName: 'Event_1_Id', + description: 'Event_1_Id', + schemaVersionId: SchemaVersion_1_Id, + stateId: EpSdkStatesService.releasedId, + }, + topicString: TopicString_1 + }); + const task_1_1_ExecuteReturn: IEpSdkEpEventVersionTask_ExecuteReturn = await task_1_1.execute(); + EventVersion_1_Id = task_1_1_ExecuteReturn.epObject.id; + + const task_2 = new EpSdkEpEventTask({ + epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, + applicationDomainId: ApplicationDomain_Id, + eventName: Event_2_Name, + eventObjectSettings: { + brokerType: EpSdkBrokerTypes.Solace, + shared: true + } + }); + const task_2_ExecuteReturn: IEpSdkEpEventTask_ExecuteReturn = await task_2.execute(); + Event_2_Id = task_2_ExecuteReturn.epObject.id; + const task_2_1 = new EpSdkEpEventVersionTask({ + epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, + applicationDomainId: ApplicationDomain_Id, + eventId: Event_2_Id, + versionString: "1.0.0", + eventVersionSettings: { + displayName: 'Event_2_Id', + description: 'Event_2_Id', + schemaVersionId: SchemaVersion_2_Id, + stateId: EpSdkStatesService.releasedId, + }, + topicString: TopicString_2 + }); + const task_2_1_ExecuteReturn: IEpSdkEpEventVersionTask_ExecuteReturn = await task_2_1.execute(); + EventVersion_2_Id = task_2_1_ExecuteReturn.epObject.id; + + } catch (e) { + if (e instanceof ApiError) expect(false, TestLogger.createApiTestFailMessage("failed")).to.be.true; + expect(e instanceof EpSdkError, TestLogger.createNotEpSdkErrorMessage(e)).to.be.true; + expect(false, TestLogger.createEpSdkTestFailMessage("failed", e)).to.be.true; + } + }); + + it(`${scriptName}: should create the event api & version`, async () => { + try { + const task_1 = new EpSdkEventApiTask({ + epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, + applicationDomainId: ApplicationDomain_Id, + eventApiName: EventApi_Name, + eventApiObjectSettings: { + brokerType: EventApi.brokerType.SOLACE, + shared: true + } + }); + const task_1_ExecuteReturn: IEpSdkEventApiTask_ExecuteReturn = await task_1.execute(); + EventApi_Id = task_1_ExecuteReturn.epObject.id; + const task_1_1 = new EpSdkEventApiVersionTask({ + epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, + applicationDomainId: ApplicationDomain_Id, + eventApiId: EventApi_Id, + versionString: "1.0.0", + eventApiVersionSettings: { + stateId: EpSdkStatesService.releasedId, + displayName: 'EventApi_Id', + description: 'EventApi_Id', + consumedEventVersionIds: [EventVersion_1_Id], + producedEventVersionIds: [EventVersion_2_Id], + } + }); + const task_1_1_ExecuteReturn: IEpSdkEventApiVersionTask_ExecuteReturn = await task_1_1.execute(); + EventApiVersion_Id = task_1_1_ExecuteReturn.epObject.id; + } catch (e) { + if (e instanceof ApiError) expect(false, TestLogger.createApiTestFailMessage("failed")).to.be.true; + expect(e instanceof EpSdkError, TestLogger.createNotEpSdkErrorMessage(e)).to.be.true; + expect(false, TestLogger.createEpSdkTestFailMessage("failed", e)).to.be.true; + } + }); + + it(`${scriptName}: should create the app & version`, async () => { + try { + const task_1 = new EpSdkApplicationTask({ + epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, + applicationDomainId: ApplicationDomain_Id, + applicationName: App_Name, + applicationObjectSettings: { + brokerType: EventApi.brokerType.SOLACE, + applicationType: "standard", + } + }); + const task_1_ExecuteReturn: IEpSdkApplicationTask_ExecuteReturn = await task_1.execute(); + App_Id = task_1_ExecuteReturn.epObject.id; + const task_1_1 = new EpSdkApplicationVersionTask({ + epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, + applicationDomainId: ApplicationDomain_Id, + applicationId: App_Id, + versionString: "1.0.0", + applicationVersionSettings: { + displayName: 'App_Id', + description: 'App_Id', + declaredConsumedEventVersionIds: [EventVersion_2_Id], + declaredProducedEventVersionIds: [EventVersion_1_Id], + stateId: EpSdkStatesService.releasedId, + } + }); + const task_1_1_ExecuteReturn: IEpSdkApplicationVersionTask_ExecuteReturn = await task_1_1.execute(); + AppVersion_Id = task_1_1_ExecuteReturn.epObject.id; + } catch (e) { + if (e instanceof ApiError) expect(false, TestLogger.createApiTestFailMessage("failed")).to.be.true; + expect(e instanceof EpSdkError, TestLogger.createNotEpSdkErrorMessage(e)).to.be.true; + expect(false, TestLogger.createEpSdkTestFailMessage("failed", e)).to.be.true; + } + }); + + it(`${scriptName}: should get the event api spec`, async () => { + try { + EventApiSpec = await EventApIsService.getAsyncApiForEventApiVersion({ + eventApiVersionId: EventApiVersion_Id, + }); + // console.log(`EventApiSpec = ${JSON.stringify(EventApiSpec, null, 2)}`); + } catch (e) { + if (e instanceof ApiError) expect(false, TestLogger.createApiTestFailMessage("failed")).to.be.true; + expect(e instanceof EpSdkError, TestLogger.createNotEpSdkErrorMessage(e)).to.be.true; + expect(false, TestLogger.createEpSdkTestFailMessage("failed", e)).to.be.true; + } + }); + + it(`${scriptName}: should parse the event api spec and save it to file`, async () => { + try { + const epAsyncApiDocument: EpAsyncApiDocument = await EpAsyncApiDocumentService.createFromAny({ + anySpec: EventApiSpec + }); + const applicationDomainName = epAsyncApiDocument.getApplicationDomainName(); + const assetsApplicationDomainName = epAsyncApiDocument.getAssetsApplicationDomainName(); + + AsyncApiSpecFileNameJson = TestConfig.getConfig().tmpDir + "/" + epAsyncApiDocument.getTitleAsFileName("json"); + CliUtils.saveContents2File({ + filePath: AsyncApiSpecFileNameJson, + content: JSON.stringify(epAsyncApiDocument.getOriginalSpecAsJson(), null, 2 ), + }); + } catch (e) { + if (e instanceof ApiError) expect(false, TestLogger.createApiTestFailMessage("failed")).to.be.true; + expect(e instanceof EpSdkError, TestLogger.createNotEpSdkErrorMessage(e)).to.be.true; + expect(false, TestLogger.createEpSdkTestFailMessage("failed", e)).to.be.true; + } + }); + + it(`${scriptName}: should import event api spec`, async () => { + try { + CliConfig.getCliImporterManagerOptions().asyncApiFileList = [AsyncApiSpecFileNameJson]; + CliConfig.getCliImporterManagerOptions().cliImporterManagerMode = ECliImporterManagerMode.RELEASE_MODE; + // CliConfig.getCliImporterManagerOptions().runId = scriptName; + // // DEBUG + // CliConfig.getCliImporterManagerOptions().cliImporterManagerMode = ECliImporterManagerMode.TEST_MODE_KEEP; + // CliConfig.getCliImporterManagerOptions().applicationDomainName = 'release_mode'; + CliConfig.getCliImporterManagerOptions().createEventApiApplication = true; + CliConfig.getCliImporterManagerOptions().cliImporterOptions.cliAssetImport_BrokerType = undefined; + CliConfig.getCliImporterManagerOptions().cliImporterOptions.cliAssetImport_ChannelDelimiter = undefined; + + const cliImporter = new CliImporterManager(CliConfig.getCliImporterManagerOptions()); + const xvoid: void = await cliImporter.run(); + // // DEBUG + // const cliRunSummaryList: Array = CliRunSummary.getSummaryLogList(); + // expect(false, JSON.stringify(cliRunSummaryList, null, 2)).to.be.true; + } catch (e) { + TestLogger.logMessageWithId(TestLogger.createTestFailMessageForError('error', e)); + expect( e instanceof CliError, TestLogger.createNotCliErrorMesssage(e.message)).to.be.true; + expect(false, TestLogger.createTestFailMessageWithCliError("failed", e)).to.be.true; + if (e instanceof ApiError) expect(false, TestLogger.createApiTestFailMessage("failed")).to.be.true; + expect(e instanceof EpSdkError, TestLogger.createNotEpSdkErrorMessage(e)).to.be.true; + expect(false, TestLogger.createEpSdkTestFailMessage("failed", e)).to.be.true; + } + }); + + it(`${scriptName}: should check no new version created`, async () => { + try { + const enum_1_id_versions = await EpSdkEnumVersionsService.getVersionsForEnumId({enumId: Enum_1_Id}); + expect(enum_1_id_versions.length,'enum_1_id_versions.length not 1').to.equal(1); + const enum_2_id_versions = await EpSdkEnumVersionsService.getVersionsForEnumId({enumId: Enum_2_Id}); + expect(enum_2_id_versions.length,'enum_2_id_versions.length not 1').to.equal(1); + + const schema_1_id_versions = await EpSdkSchemaVersionsService.getVersionsForSchemaId({ schemaId: Schema_1_Id }); + expect(schema_1_id_versions.length,'schema_1_id_versions.length not 1').to.equal(1); + const schema_2_id_versions = await EpSdkSchemaVersionsService.getVersionsForSchemaId({ schemaId: Schema_2_Id }); + expect(schema_2_id_versions.length,'schema_2_id_versions.length not 1').to.equal(1); + + const event_1_id_versions = await EpSdkEpEventVersionsService.getVersionsForEventId({ eventId: Event_1_Id }); + expect(event_1_id_versions.length,'event_1_id_versions.length not 1').to.equal(1); + const event_2_id_versions = await EpSdkEpEventVersionsService.getVersionsForEventId({ eventId: Event_2_Id }); + expect(event_2_id_versions.length,'event_2_id_versions.length not 1').to.equal(1); + + const event_api_versions = await EpSdkEventApiVersionsService.getVersionsForEventApiId({ eventApiId: EventApi_Id }); + expect(event_api_versions.length,'event_api_versions.length not 1').to.equal(1); + + } catch (e) { + TestLogger.logMessageWithId(TestLogger.createTestFailMessageForError('error', e)); + if (e instanceof ApiError) expect(false, TestLogger.createApiTestFailMessage("failed")).to.be.true; + expect(e instanceof EpSdkError, TestLogger.createNotEpSdkErrorMessage(e)).to.be.true; + expect(false, TestLogger.createEpSdkTestFailMessage("failed", e)).to.be.true; + } + }); + +}); diff --git a/packages/ep-async-api-importer/test/specs/multi-domain.x-spec.ts b/packages/ep-async-api-importer/test/specs/multi-domain.xx-spec.ts similarity index 100% rename from packages/ep-async-api-importer/test/specs/multi-domain.x-spec.ts rename to packages/ep-async-api-importer/test/specs/multi-domain.xx-spec.ts diff --git a/packages/ep-asyncapi/.nycrc b/packages/ep-asyncapi/.nycrc index 9ad5119cd..2b3f6031c 100644 --- a/packages/ep-asyncapi/.nycrc +++ b/packages/ep-asyncapi/.nycrc @@ -2,7 +2,7 @@ "all": true, "check-coverage": true, "statements": 79, - "branches": 70, + "branches": 69, "functions": 77, "lines": 80, "temp-dir": "./test/logs/nyc_output", From 42334e600c9b7b7504fc5b1276673bce9f03884d Mon Sep 17 00:00:00 2001 From: Ricardo Gomez_Ulmke Date: Sat, 11 Mar 2023 16:23:58 +0100 Subject: [PATCH 14/33] schema title error --- .../ep-asyncapi/src/documents/EpAsyncApiMessageDocument.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/packages/ep-asyncapi/src/documents/EpAsyncApiMessageDocument.ts b/packages/ep-asyncapi/src/documents/EpAsyncApiMessageDocument.ts index ad64df23e..6f7987dc0 100644 --- a/packages/ep-asyncapi/src/documents/EpAsyncApiMessageDocument.ts +++ b/packages/ep-asyncapi/src/documents/EpAsyncApiMessageDocument.ts @@ -154,8 +154,7 @@ export class EpAsyncApiMessageDocument { public getPayloadSchemaName(): string { const schema: Schema = this.asyncApiMessage.payload(); - const name: string | undefined = schema.title(); - if(name !== undefined) return name; + try { return schema.title(); } catch(e) {} if(schema.hasExtension(EpAsyncApiSchemaExtensions.xEpSchemaName)) { return schema.extension(EpAsyncApiSchemaExtensions.xEpSchemaName); } From f7a9ba04c20cb58235e9229b4c712bf4d1ac4352 Mon Sep 17 00:00:00 2001 From: Ricardo Gomez_Ulmke Date: Sat, 11 Mar 2023 16:32:43 +0100 Subject: [PATCH 15/33] lint --- .../src/importers/CliAssetsImporter.ts | 2 +- .../test/specs/ep-idempotency.x-spec.ts | 13 +++++-------- .../src/documents/EpAsyncApiMessageDocument.ts | 16 ++++++++++++---- .../src/services/EpSdkEnumVersionsService.ts | 3 --- .../ep-sdk/src/services/EpSdkEnumsService.ts | 4 ++-- 5 files changed, 20 insertions(+), 18 deletions(-) diff --git a/packages/ep-async-api-importer/src/importers/CliAssetsImporter.ts b/packages/ep-async-api-importer/src/importers/CliAssetsImporter.ts index ca2cf63ad..d03b635c5 100644 --- a/packages/ep-async-api-importer/src/importers/CliAssetsImporter.ts +++ b/packages/ep-async-api-importer/src/importers/CliAssetsImporter.ts @@ -254,7 +254,7 @@ export abstract class CliAssetsImporter extends CliImporter { versionStrategy: this.get_EEpSdk_VersionTaskStrategy(), schemaVersionSettings: { content: JSON.stringify(epAsyncApiMessageDocument.getSchemaAsSanitizedJson()), - description: epAsyncApiMessageDocument.getDescription(), + description: epAsyncApiMessageDocument.getPayloadSchemaDescription(), displayName: epAsyncApiMessageDocument.getPayloadSchemaDisplayName(), stateId: this.get_EpSdkTask_StateId(), }, diff --git a/packages/ep-async-api-importer/test/specs/ep-idempotency.x-spec.ts b/packages/ep-async-api-importer/test/specs/ep-idempotency.x-spec.ts index 01b2fef11..1e4b0fb52 100644 --- a/packages/ep-async-api-importer/test/specs/ep-idempotency.x-spec.ts +++ b/packages/ep-async-api-importer/test/specs/ep-idempotency.x-spec.ts @@ -5,7 +5,6 @@ import { ApiError, EventApi, EventApIsService, - EventApiVersion, } from "@solace-labs/ep-openapi-node"; import { EEpSdkTask_TargetState, @@ -35,8 +34,6 @@ import { IEpSdkApplicationVersionTask_ExecuteReturn, EpSdkEventApiVersionsService, EpSdkError, - EpSdkCustomAttributeNameSourceApplicationDomainId, - EpSdkEventApisService, EpSdkEnumVersionsService, EpSdkSchemaVersionsService, EpSdkEpEventVersionsService @@ -202,7 +199,7 @@ describe(`${scriptName}`, () => { schemaVersionSettings: { stateId: EpSdkStatesService.releasedId, displayName: 'Schema_1_Id', - description: 'Schema_1_Id', + // description: 'Schema_1_Id', content: SchemaContent, }, }); @@ -228,7 +225,7 @@ describe(`${scriptName}`, () => { schemaVersionSettings: { stateId: EpSdkStatesService.releasedId, displayName: 'Schema_2_Id', - description: 'Schema_2_Id', + // description: 'Schema_2_Id', content: SchemaContent, }, }); @@ -261,7 +258,7 @@ describe(`${scriptName}`, () => { enumVersionSettings: { stateId: EpSdkStatesService.releasedId, displayName: 'Enum_1_Id', - description: 'Enum_1_Id', + // description: 'Enum_1_Id', }, enumValues: EnumValues }); @@ -286,7 +283,7 @@ describe(`${scriptName}`, () => { enumVersionSettings: { stateId: EpSdkStatesService.releasedId, displayName: 'Enum_2_Id', - description: 'Enum_2_Id', + // description: 'Enum_2_Id', }, enumValues: EnumValues }); @@ -347,7 +344,7 @@ describe(`${scriptName}`, () => { versionString: "1.0.0", eventVersionSettings: { displayName: 'Event_2_Id', - description: 'Event_2_Id', + // description: 'Event_2_Id', schemaVersionId: SchemaVersion_2_Id, stateId: EpSdkStatesService.releasedId, }, diff --git a/packages/ep-asyncapi/src/documents/EpAsyncApiMessageDocument.ts b/packages/ep-asyncapi/src/documents/EpAsyncApiMessageDocument.ts index 6f7987dc0..0ce6e06d6 100644 --- a/packages/ep-asyncapi/src/documents/EpAsyncApiMessageDocument.ts +++ b/packages/ep-asyncapi/src/documents/EpAsyncApiMessageDocument.ts @@ -154,11 +154,14 @@ export class EpAsyncApiMessageDocument { public getPayloadSchemaName(): string { const schema: Schema = this.asyncApiMessage.payload(); - try { return schema.title(); } catch(e) {} - if(schema.hasExtension(EpAsyncApiSchemaExtensions.xEpSchemaName)) { - return schema.extension(EpAsyncApiSchemaExtensions.xEpSchemaName); + try { + return schema.title(); + } catch(e) { + if(schema.hasExtension(EpAsyncApiSchemaExtensions.xEpSchemaName)) { + return schema.extension(EpAsyncApiSchemaExtensions.xEpSchemaName); + } + return this.getMessageName(); } - return this.getMessageName(); } public getPayloadSchemaDisplayName(): string | undefined { @@ -168,6 +171,11 @@ export class EpAsyncApiMessageDocument { } } + public getPayloadSchemaDescription(): string | undefined { + const schema: Schema = this.asyncApiMessage.payload(); + try { return schema.description(); } catch(e) { return undefined; } + } + public getSchemaFileName(): string { if(this.getContentType() === E_EpAsyncApiContentTypes.APPLICATION_JSON) return `${this.getPayloadSchemaName()}.${"json"}`; return `${this.getMessageNameAsFilePath()}.${"xxx"}` diff --git a/packages/ep-sdk/src/services/EpSdkEnumVersionsService.ts b/packages/ep-sdk/src/services/EpSdkEnumVersionsService.ts index d5ef5a317..e7ffcbbba 100644 --- a/packages/ep-sdk/src/services/EpSdkEnumVersionsService.ts +++ b/packages/ep-sdk/src/services/EpSdkEnumVersionsService.ts @@ -22,13 +22,10 @@ import { EpSdkEnumVersionTask, IEpSdkEnumVersionTask_ExecuteReturn, EEpSdk_VersionTaskStrategy, - EpSdkCustomAttributeDefinitionTask, - IEpSdkCustomAttributeDefinitionTask_ExecuteReturn } from "../tasks"; import EpSdkEnumsService from "./EpSdkEnumsService"; import { EpSdkVersionServiceClass } from "./EpSdkVersionService"; import { EEpSdkCustomAttributeEntityTypes } from '../types'; -import { EpSdkCustomAttributesService } from '.'; /** @category Services */ export class EpSdkEnumVersionsServiceClass extends EpSdkVersionServiceClass { diff --git a/packages/ep-sdk/src/services/EpSdkEnumsService.ts b/packages/ep-sdk/src/services/EpSdkEnumsService.ts index 2754f4369..7c9e8a261 100644 --- a/packages/ep-sdk/src/services/EpSdkEnumsService.ts +++ b/packages/ep-sdk/src/services/EpSdkEnumsService.ts @@ -52,8 +52,8 @@ export class EpSdkEnumsServiceClass extends EpSdkServiceClass { epSdkCustomAttributeList: TEpSdkCustomAttributeList; scope?: CustomAttributeDefinition.scope; }): Promise { - const funcName = 'setCustomAttributes'; - const logName = `${EpSdkEnumsServiceClass.name}.${funcName}()`; + // const funcName = 'setCustomAttributes'; + // const logName = `${EpSdkEnumsServiceClass.name}.${funcName}()`; const topicAddressEnum: TopicAddressEnum = await this.getById({ xContextId, enumId: enumId, From 62e981052f45e2fa279c3ff26a7c7c4eff44e9d1 Mon Sep 17 00:00:00 2001 From: Ricardo Gomez_Ulmke Date: Sat, 11 Mar 2023 16:44:43 +0100 Subject: [PATCH 16/33] schema title error --- .../ep-asyncapi/src/documents/EpAsyncApiMessageDocument.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/ep-asyncapi/src/documents/EpAsyncApiMessageDocument.ts b/packages/ep-asyncapi/src/documents/EpAsyncApiMessageDocument.ts index 0ce6e06d6..3079e6dd3 100644 --- a/packages/ep-asyncapi/src/documents/EpAsyncApiMessageDocument.ts +++ b/packages/ep-asyncapi/src/documents/EpAsyncApiMessageDocument.ts @@ -155,7 +155,9 @@ export class EpAsyncApiMessageDocument { public getPayloadSchemaName(): string { const schema: Schema = this.asyncApiMessage.payload(); try { - return schema.title(); + const title = schema.title(); + if(title && title !== '') return title; + throw new Error('no title found'); } catch(e) { if(schema.hasExtension(EpAsyncApiSchemaExtensions.xEpSchemaName)) { return schema.extension(EpAsyncApiSchemaExtensions.xEpSchemaName); From 21393b3e4e45e70075face5b1b5a4e9c1c839064 Mon Sep 17 00:00:00 2001 From: Ricardo Gomez_Ulmke Date: Sat, 11 Mar 2023 17:03:21 +0100 Subject: [PATCH 17/33] tests --- packages/ep-asyncapi/.nycrc | 4 +- .../documents/EpAsyncApiMessageDocument.ts | 8 +- .../ep-sdk/src/tasks/EpSdkEnumVersionTask.ts | 96 ++++++------------- 3 files changed, 38 insertions(+), 70 deletions(-) diff --git a/packages/ep-asyncapi/.nycrc b/packages/ep-asyncapi/.nycrc index 2b3f6031c..c117dd721 100644 --- a/packages/ep-asyncapi/.nycrc +++ b/packages/ep-asyncapi/.nycrc @@ -1,8 +1,8 @@ { "all": true, "check-coverage": true, - "statements": 79, - "branches": 69, + "statements": 78, + "branches": 68, "functions": 77, "lines": 80, "temp-dir": "./test/logs/nyc_output", diff --git a/packages/ep-asyncapi/src/documents/EpAsyncApiMessageDocument.ts b/packages/ep-asyncapi/src/documents/EpAsyncApiMessageDocument.ts index 3079e6dd3..ce6db1312 100644 --- a/packages/ep-asyncapi/src/documents/EpAsyncApiMessageDocument.ts +++ b/packages/ep-asyncapi/src/documents/EpAsyncApiMessageDocument.ts @@ -175,7 +175,13 @@ export class EpAsyncApiMessageDocument { public getPayloadSchemaDescription(): string | undefined { const schema: Schema = this.asyncApiMessage.payload(); - try { return schema.description(); } catch(e) { return undefined; } + try { + const descr = schema.description(); + if(descr === "") return undefined; + return descr; + } catch(e) { + return undefined; + } } public getSchemaFileName(): string { diff --git a/packages/ep-sdk/src/tasks/EpSdkEnumVersionTask.ts b/packages/ep-sdk/src/tasks/EpSdkEnumVersionTask.ts index d16be635f..6b5262d4a 100644 --- a/packages/ep-sdk/src/tasks/EpSdkEnumVersionTask.ts +++ b/packages/ep-sdk/src/tasks/EpSdkEnumVersionTask.ts @@ -93,8 +93,7 @@ export class EpSdkEnumVersionTask extends EpSdkVersionTask { return enumValueList; } - private createObjectSettings(): Partial & - Pick { + private createObjectSettings(): Partial & Pick { return { ...this.Default_TEpSdkEnumVersionTask_Settings, ...this.getTaskConfig().enumVersionSettings, @@ -174,15 +173,9 @@ export class EpSdkEnumVersionTask extends EpSdkVersionTask { const funcName = "getFunc"; const logName = `${EpSdkEnumVersionTask.name}.${funcName}()`; - EpSdkLogger.trace( - EpSdkLogger.createLogEntry(logName, { - code: EEpSdkLoggerCodes.TASK_EXECUTE_START_GET, - module: this.constructor.name, - details: { - epSdkEnumVersionTask_Keys: epSdkEnumVersionTask_Keys, - }, - }) - ); + EpSdkLogger.trace(EpSdkLogger.createLogEntry(logName, { code: EEpSdkLoggerCodes.TASK_EXECUTE_START_GET, module: this.constructor.name, details: { + epSdkEnumVersionTask_Keys: epSdkEnumVersionTask_Keys, + }})); const enumVersion: TopicAddressEnumVersion | undefined = await EpSdkEnumVersionsService.getLatestVersionForEnumId({ xContextId: this.xContextId, @@ -190,32 +183,22 @@ export class EpSdkEnumVersionTask extends EpSdkVersionTask { enumId: epSdkEnumVersionTask_Keys.enumId, }); - EpSdkLogger.trace( - EpSdkLogger.createLogEntry(logName, { - code: EEpSdkLoggerCodes.TASK_EXECUTE_API_GET, - module: this.constructor.name, - details: { - epSdkEnumVersionTask_Keys: epSdkEnumVersionTask_Keys, - enumVersion: enumVersion ? enumVersion : "undefined", - }, - }) - ); + EpSdkLogger.trace(EpSdkLogger.createLogEntry(logName, { code: EEpSdkLoggerCodes.TASK_EXECUTE_API_GET, module: this.constructor.name, details: { + epSdkEnumVersionTask_Keys: epSdkEnumVersionTask_Keys, + enumVersion: enumVersion ? enumVersion : "undefined", + }})); - if (enumVersion === undefined) - return this.Empty_IEpSdkEnumVersionTask_GetFuncReturn; + if (enumVersion === undefined) return this.Empty_IEpSdkEnumVersionTask_GetFuncReturn; - const epSdkEnumVersionTask_GetFuncReturn: IEpSdkEnumVersionTask_GetFuncReturn = - { - epObjectKeys: this.getEpObjectKeys(enumVersion), - epObject: enumVersion, - epObjectExists: true, - }; + const epSdkEnumVersionTask_GetFuncReturn: IEpSdkEnumVersionTask_GetFuncReturn = { + epObjectKeys: this.getEpObjectKeys(enumVersion), + epObject: enumVersion, + epObjectExists: true, + }; return epSdkEnumVersionTask_GetFuncReturn; } - private createCompareEnumValueList_From_EP({ - epEnumValueList, - }: { + private createCompareEnumValueList_From_EP({ epEnumValueList }: { epEnumValueList?: Array; }): Array { if (epEnumValueList === undefined) return []; @@ -233,49 +216,28 @@ export class EpSdkEnumVersionTask extends EpSdkVersionTask { const funcName = "isUpdateRequired"; const logName = `${EpSdkEnumVersionTask.name}.${funcName}()`; - EpSdkLogger.trace( - EpSdkLogger.createLogEntry(logName, { - code: EEpSdkLoggerCodes.TASK_EXECUTE_START_IS_UPDATE_REQUIRED, - module: this.constructor.name, - details: { - epSdkEnumVersionTask_GetFuncReturn: - epSdkEnumVersionTask_GetFuncReturn, - }, - }) - ); + EpSdkLogger.trace(EpSdkLogger.createLogEntry(logName, { code: EEpSdkLoggerCodes.TASK_EXECUTE_START_IS_UPDATE_REQUIRED, module: this.constructor.name, details: { + epSdkEnumVersionTask_GetFuncReturn: epSdkEnumVersionTask_GetFuncReturn, + }})); - if (epSdkEnumVersionTask_GetFuncReturn.epObject === undefined) - throw new EpSdkInternalTaskError( - logName, - this.constructor.name, - "epSdkEnumVersionTask_GetFuncReturn.epObject === undefined" - ); + if (epSdkEnumVersionTask_GetFuncReturn.epObject === undefined) throw new EpSdkInternalTaskError(logName, this.constructor.name, + "epSdkEnumVersionTask_GetFuncReturn.epObject === undefined" + ); /* istanbul ignore next */ - if (epSdkEnumVersionTask_GetFuncReturn.epObject.version === undefined) - throw new EpSdkApiContentError( - logName, - this.constructor.name, - "epSdkEnumVersionTask_GetFuncReturn.epObject.version === undefined", - { - epObject: epSdkEnumVersionTask_GetFuncReturn.epObject, - } - ); + if (epSdkEnumVersionTask_GetFuncReturn.epObject.version === undefined) throw new EpSdkApiContentError(logName, this.constructor.name, "epSdkEnumVersionTask_GetFuncReturn.epObject.version === undefined", { + epObject: epSdkEnumVersionTask_GetFuncReturn.epObject, + }); - const existingObject: TopicAddressEnumVersion = - epSdkEnumVersionTask_GetFuncReturn.epObject; + const existingObject: TopicAddressEnumVersion = epSdkEnumVersionTask_GetFuncReturn.epObject; const existingCompareObject: TEpSdkEnumVersionTask_CompareObject = { - description: existingObject.description, + description: existingObject.description ? existingObject.description : undefined, displayName: existingObject.displayName, stateId: existingObject.stateId, - values: this.createCompareEnumValueList_From_EP({ - epEnumValueList: existingObject.values, - }), + values: this.createCompareEnumValueList_From_EP({ epEnumValueList: existingObject.values }), }; - const requestedCompareObject: TEpSdkEnumVersionTask_CompareObject = - this.createObjectSettings(); + const requestedCompareObject: TEpSdkEnumVersionTask_CompareObject = this.createObjectSettings(); if (this.versionStrategy === EEpSdk_VersionTaskStrategy.EXACT_VERSION) { - existingCompareObject.version = - epSdkEnumVersionTask_GetFuncReturn.epObject.version; + existingCompareObject.version = epSdkEnumVersionTask_GetFuncReturn.epObject.version; requestedCompareObject.version = this.versionString; } From 630879532008bfad21e8b3509db7ec58cd8a003a Mon Sep 17 00:00:00 2001 From: Ricardo Gomez_Ulmke Date: Sat, 11 Mar 2023 17:22:25 +0100 Subject: [PATCH 18/33] tests --- .../src/importers/CliAssetsImporter.ts | 50 ++++------- packages/ep-asyncapi/.nycrc | 4 +- .../EpAsyncApiChannelParameterDocument.ts | 5 +- .../ep-sdk/src/tasks/EpSdkEnumVersionTask.ts | 90 +++++-------------- 4 files changed, 45 insertions(+), 104 deletions(-) diff --git a/packages/ep-async-api-importer/src/importers/CliAssetsImporter.ts b/packages/ep-async-api-importer/src/importers/CliAssetsImporter.ts index d03b635c5..828da9e81 100644 --- a/packages/ep-async-api-importer/src/importers/CliAssetsImporter.ts +++ b/packages/ep-async-api-importer/src/importers/CliAssetsImporter.ts @@ -326,14 +326,13 @@ export abstract class CliAssetsImporter extends CliImporter { epSdkSchemaTask_ExecuteReturn: epSdkSchemaTask_ExecuteReturn, }})); // present the schema version - const epSdkSchemaVersionTask_ExecuteReturn: IEpSdkSchemaVersionTask_ExecuteReturn = - await this.run_present_schema_version({ - schemaObject: epSdkSchemaTask_ExecuteReturn.epObject, - specVersion: specVersion, - epAsyncApiMessageDocument: epAsyncApiMessageDocument, - applicationDomainId: assetApplicationDomainId, - checkmode: checkmode, - }); + const epSdkSchemaVersionTask_ExecuteReturn: IEpSdkSchemaVersionTask_ExecuteReturn = await this.run_present_schema_version({ + schemaObject: epSdkSchemaTask_ExecuteReturn.epObject, + specVersion: specVersion, + epAsyncApiMessageDocument: epAsyncApiMessageDocument, + applicationDomainId: assetApplicationDomainId, + checkmode: checkmode, + }); CliRunContext.pop(); return epSdkSchemaVersionTask_ExecuteReturn.epObject; }; @@ -373,10 +372,9 @@ export abstract class CliAssetsImporter extends CliImporter { ); /* istanbul ignore next */ - if (enumObject.id === undefined) - throw new CliEPApiContentError(logName, "enumObject.id === undefined", { - enumObject: enumObject, - }); + if (enumObject.id === undefined) throw new CliEPApiContentError(logName, "enumObject.id === undefined", { + enumObject: enumObject, + }); const epSdkEnumVersionTask = new EpSdkEnumVersionTask({ epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, @@ -384,8 +382,7 @@ export abstract class CliAssetsImporter extends CliImporter { enumId: enumObject.id, versionString: specVersion, versionStrategy: this.get_EEpSdk_VersionTaskStrategy(), - enumValues: - epAsyncApiChannelParameterDocument.getParameterEnumValueList(), + enumValues: epAsyncApiChannelParameterDocument.getParameterEnumValueList(), enumVersionSettings: { description: epAsyncApiChannelParameterDocument.getDescription(), displayName: epAsyncApiChannelParameterDocument.getDisplayName(), @@ -394,24 +391,15 @@ export abstract class CliAssetsImporter extends CliImporter { epSdkTask_TransactionConfig: this.get_IEpSdkTask_TransactionConfig(), checkmode: checkmode, }); - const epSdkEnumVersionTask_ExecuteReturn: IEpSdkEnumVersionTask_ExecuteReturn = - await this.executeTask({ - epSdkTask: epSdkEnumVersionTask, - expectNoAction: checkmode, - }); - CliLogger.trace( - CliLogger.createLogEntry(logName, { - code: ECliStatusCodes.IMPORTING_EP_ENUM_VERSION, - details: { - epSdkEnumVersionTask_ExecuteReturn: - epSdkEnumVersionTask_ExecuteReturn, - }, - }) - ); - // summary - CliRunSummary.processedEnumVersion({ - epSdkEnumVersionTask_ExecuteReturn: epSdkEnumVersionTask_ExecuteReturn, + const epSdkEnumVersionTask_ExecuteReturn: IEpSdkEnumVersionTask_ExecuteReturn = await this.executeTask({ + epSdkTask: epSdkEnumVersionTask, + expectNoAction: checkmode, }); + CliLogger.trace(CliLogger.createLogEntry(logName, {code: ECliStatusCodes.IMPORTING_EP_ENUM_VERSION, details: { + epSdkEnumVersionTask_ExecuteReturn: epSdkEnumVersionTask_ExecuteReturn, + }})); + // summary + CliRunSummary.processedEnumVersion({ epSdkEnumVersionTask_ExecuteReturn: epSdkEnumVersionTask_ExecuteReturn }); }; private run_present_channel_parameters = async ({ diff --git a/packages/ep-asyncapi/.nycrc b/packages/ep-asyncapi/.nycrc index c117dd721..11132c916 100644 --- a/packages/ep-asyncapi/.nycrc +++ b/packages/ep-asyncapi/.nycrc @@ -2,9 +2,9 @@ "all": true, "check-coverage": true, "statements": 78, - "branches": 68, + "branches": 67, "functions": 77, - "lines": 80, + "lines": 79, "temp-dir": "./test/logs/nyc_output", "reporter": ["html", "text", "text-summary", "lcov"], "report-dir": "./test/logs/coverage", diff --git a/packages/ep-asyncapi/src/documents/EpAsyncApiChannelParameterDocument.ts b/packages/ep-asyncapi/src/documents/EpAsyncApiChannelParameterDocument.ts index e41c230df..33a3fd400 100644 --- a/packages/ep-asyncapi/src/documents/EpAsyncApiChannelParameterDocument.ts +++ b/packages/ep-asyncapi/src/documents/EpAsyncApiChannelParameterDocument.ts @@ -23,10 +23,9 @@ export class EpAsyncApiChannelParameterDocument { public getAsyncApiChannelParameter(): ChannelParameter { return this.asyncApiChannelParameter; } - public getDescription(): string { + public getDescription(): string | undefined { const description: string | null = this.asyncApiChannelParameter.description(); - if(description) return description; - return ''; + if(description && description.length > 0) return description; } public getDisplayName(): string | undefined { diff --git a/packages/ep-sdk/src/tasks/EpSdkEnumVersionTask.ts b/packages/ep-sdk/src/tasks/EpSdkEnumVersionTask.ts index 6b5262d4a..0146bfd85 100644 --- a/packages/ep-sdk/src/tasks/EpSdkEnumVersionTask.ts +++ b/packages/ep-sdk/src/tasks/EpSdkEnumVersionTask.ts @@ -79,9 +79,7 @@ export class EpSdkEnumVersionTask extends EpSdkVersionTask { private getTaskConfig(): IEpSdkEnumVersionTask_Config { return this.epSdkTask_Config as IEpSdkEnumVersionTask_Config; } - private createEnumValueList( - valueList: Array - ): Array { + private createEnumValueList(valueList: Array): Array { const enumValueList: Array = []; valueList.forEach((value: string) => { const enumValue: TopicAddressEnumValue = { @@ -167,8 +165,7 @@ export class EpSdkEnumVersionTask extends EpSdkVersionTask { /** * Get the latest EnumVersion. */ - protected async getFunc( - epSdkEnumVersionTask_Keys: IEpSdkEnumVersionTask_Keys + protected async getFunc(epSdkEnumVersionTask_Keys: IEpSdkEnumVersionTask_Keys ): Promise { const funcName = "getFunc"; const logName = `${EpSdkEnumVersionTask.name}.${funcName}()`; @@ -187,9 +184,7 @@ export class EpSdkEnumVersionTask extends EpSdkVersionTask { epSdkEnumVersionTask_Keys: epSdkEnumVersionTask_Keys, enumVersion: enumVersion ? enumVersion : "undefined", }})); - if (enumVersion === undefined) return this.Empty_IEpSdkEnumVersionTask_GetFuncReturn; - const epSdkEnumVersionTask_GetFuncReturn: IEpSdkEnumVersionTask_GetFuncReturn = { epObjectKeys: this.getEpObjectKeys(enumVersion), epObject: enumVersion, @@ -227,7 +222,6 @@ export class EpSdkEnumVersionTask extends EpSdkVersionTask { if (epSdkEnumVersionTask_GetFuncReturn.epObject.version === undefined) throw new EpSdkApiContentError(logName, this.constructor.name, "epSdkEnumVersionTask_GetFuncReturn.epObject.version === undefined", { epObject: epSdkEnumVersionTask_GetFuncReturn.epObject, }); - const existingObject: TopicAddressEnumVersion = epSdkEnumVersionTask_GetFuncReturn.epObject; const existingCompareObject: TEpSdkEnumVersionTask_CompareObject = { description: existingObject.description ? existingObject.description : undefined, @@ -276,16 +270,10 @@ export class EpSdkEnumVersionTask extends EpSdkVersionTask { enumId: this.getTaskConfig().enumId, version: this.versionString, }; - EpSdkLogger.trace( - EpSdkLogger.createLogEntry(logName, { - code: EEpSdkLoggerCodes.TASK_EXECUTE_CREATE, - module: this.constructor.name, - details: { - epSdkEnumVersionTask_Config: this.getTaskConfig(), - create: create, - }, - }) - ); + EpSdkLogger.trace(EpSdkLogger.createLogEntry(logName, { code: EEpSdkLoggerCodes.TASK_EXECUTE_CREATE, module: this.constructor.name, details: { + epSdkEnumVersionTask_Config: this.getTaskConfig(), + create: create, + }})); if (this.isCheckmode()) { return { @@ -302,21 +290,14 @@ export class EpSdkEnumVersionTask extends EpSdkVersionTask { xContextId: this.xContextId, enumId: this.getTaskConfig().enumId, topicAddressEnumVersion: create, - targetLifecycleStateId: - this.getTaskConfig().enumVersionSettings.stateId, + targetLifecycleStateId: this.getTaskConfig().enumVersionSettings.stateId, }); - EpSdkLogger.trace( - EpSdkLogger.createLogEntry(logName, { - code: EEpSdkLoggerCodes.TASK_EXECUTE_CREATE, - module: this.constructor.name, - details: { - epSdkApplicationDomainTask_Config: this.getTaskConfig(), - create: create, - topicAddressEnumVersion: topicAddressEnumVersion, - }, - }) - ); + EpSdkLogger.trace(EpSdkLogger.createLogEntry(logName, { code: EEpSdkLoggerCodes.TASK_EXECUTE_CREATE, module: this.constructor.name, details: { + epSdkApplicationDomainTask_Config: this.getTaskConfig(), + create: create, + topicAddressEnumVersion: topicAddressEnumVersion, + }})); return { epSdkTask_Action: this.getCreateFuncAction(), @@ -328,53 +309,26 @@ export class EpSdkEnumVersionTask extends EpSdkVersionTask { /** * Creates a new EnumVersion with bumped version number. */ - protected async updateFunc( - epSdkEnumVersionTask_GetFuncReturn: IEpSdkEnumVersionTask_GetFuncReturn + protected async updateFunc(epSdkEnumVersionTask_GetFuncReturn: IEpSdkEnumVersionTask_GetFuncReturn ): Promise { const funcName = "updateFunc"; const logName = `${EpSdkEnumVersionTask.name}.${funcName}()`; - EpSdkLogger.trace( - EpSdkLogger.createLogEntry(logName, { - code: EEpSdkLoggerCodes.TASK_EXECUTE_START_UPDATE, - module: this.constructor.name, - }) - ); + EpSdkLogger.trace(EpSdkLogger.createLogEntry(logName, { code: EEpSdkLoggerCodes.TASK_EXECUTE_START_UPDATE, module: this.constructor.name })); - if (epSdkEnumVersionTask_GetFuncReturn.epObject === undefined) - throw new EpSdkInternalTaskError( - logName, - this.constructor.name, - "epSdkEnumVersionTask_GetFuncReturn.epObject === undefined" - ); + if (epSdkEnumVersionTask_GetFuncReturn.epObject === undefined) throw new EpSdkInternalTaskError(logName, this.constructor.name, "epSdkEnumVersionTask_GetFuncReturn.epObject === undefined"); /* istanbul ignore next */ - if (epSdkEnumVersionTask_GetFuncReturn.epObject.id === undefined) - throw new EpSdkApiContentError( - logName, - this.constructor.name, - "epSdkEnumVersionTask_GetFuncReturn.epObject.id === undefined", - { - epObject: epSdkEnumVersionTask_GetFuncReturn.epObject, - } - ); + if (epSdkEnumVersionTask_GetFuncReturn.epObject.id === undefined) throw new EpSdkApiContentError( logName, this.constructor.name, "epSdkEnumVersionTask_GetFuncReturn.epObject.id === undefined", { + epObject: epSdkEnumVersionTask_GetFuncReturn.epObject, + }); /* istanbul ignore next */ - if (epSdkEnumVersionTask_GetFuncReturn.epObject.version === undefined) - throw new EpSdkApiContentError( - logName, - this.constructor.name, - "epSdkEnumVersionTask_GetFuncReturn.epObject.version === undefined", - { - epObject: epSdkEnumVersionTask_GetFuncReturn.epObject, - } - ); - + if (epSdkEnumVersionTask_GetFuncReturn.epObject.version === undefined) throw new EpSdkApiContentError(logName, this.constructor.name, "epSdkEnumVersionTask_GetFuncReturn.epObject.version === undefined", { + epObject: epSdkEnumVersionTask_GetFuncReturn.epObject, + }); // getFuncReturn has the latest version object let nextVersion: string; try { - nextVersion = this.createNextVersionWithStrategyValidation({ - existingObjectVersionString: - epSdkEnumVersionTask_GetFuncReturn.epObject.version, - }); + nextVersion = this.createNextVersionWithStrategyValidation({existingObjectVersionString: epSdkEnumVersionTask_GetFuncReturn.epObject.version }); } catch (e) { if ( this.isCheckmode() && From 1cccbd7e9284f057b8ef8e6587b7adb436c74046 Mon Sep 17 00:00:00 2001 From: Ricardo Gomez_Ulmke Date: Sat, 11 Mar 2023 17:35:35 +0100 Subject: [PATCH 19/33] test --- .../documents/EpAsyncApiMessageDocument.ts | 2 + .../ep-sdk/src/tasks/EpSdkEnumVersionTask.ts | 38 +++++++------------ 2 files changed, 15 insertions(+), 25 deletions(-) diff --git a/packages/ep-asyncapi/src/documents/EpAsyncApiMessageDocument.ts b/packages/ep-asyncapi/src/documents/EpAsyncApiMessageDocument.ts index ce6db1312..635542e9b 100644 --- a/packages/ep-asyncapi/src/documents/EpAsyncApiMessageDocument.ts +++ b/packages/ep-asyncapi/src/documents/EpAsyncApiMessageDocument.ts @@ -154,6 +154,7 @@ export class EpAsyncApiMessageDocument { public getPayloadSchemaName(): string { const schema: Schema = this.asyncApiMessage.payload(); + if(!schema) return this.getMessageName(); try { const title = schema.title(); if(title && title !== '') return title; @@ -168,6 +169,7 @@ export class EpAsyncApiMessageDocument { public getPayloadSchemaDisplayName(): string | undefined { const schema: Schema = this.asyncApiMessage.payload(); + if(!schema) return undefined; if(schema.hasExtension(EpAsyncApiSchemaExtensions.xEpSchemaVersionDisplayName)) { return schema.extension(EpAsyncApiSchemaExtensions.xEpSchemaVersionDisplayName); } diff --git a/packages/ep-sdk/src/tasks/EpSdkEnumVersionTask.ts b/packages/ep-sdk/src/tasks/EpSdkEnumVersionTask.ts index 0146bfd85..42dcd89ce 100644 --- a/packages/ep-sdk/src/tasks/EpSdkEnumVersionTask.ts +++ b/packages/ep-sdk/src/tasks/EpSdkEnumVersionTask.ts @@ -99,8 +99,7 @@ export class EpSdkEnumVersionTask extends EpSdkVersionTask { }; } - protected transform_EpSdkTask_Config( - epSdkEnumVersionTask_Config: IEpSdkEnumVersionTask_Config + protected transform_EpSdkTask_Config(epSdkEnumVersionTask_Config: IEpSdkEnumVersionTask_Config ): IEpSdkEnumVersionTask_Config { epSdkEnumVersionTask_Config.enumVersionSettings.displayName = this.truncate( epSdkEnumVersionTask_Config.enumVersionSettings.displayName, @@ -129,9 +128,7 @@ export class EpSdkEnumVersionTask extends EpSdkVersionTask { if (epObject === undefined) return this.getDefaultEpObjectKeys(); /* istanbul ignore next */ - if (epObject.id === undefined) - throw new EpSdkApiContentError( - logName, + if (epObject.id === undefined) throw new EpSdkApiContentError(logName, this.constructor.name, "epObject.id === undefined", { @@ -385,30 +382,21 @@ export class EpSdkEnumVersionTask extends EpSdkVersionTask { targetLifecycleStateId: this.getTaskConfig().enumVersionSettings.stateId, }); - EpSdkLogger.trace( - EpSdkLogger.createLogEntry(logName, { - code: EEpSdkLoggerCodes.TASK_EXECUTE_UPDATE, - module: this.constructor.name, - details: { - epSdkApplicationDomainTask_Config: this.getTaskConfig(), - update: update, - topicAddressEnumVersion: topicAddressEnumVersion, - }, - }) - ); - - const epSdkEnumVersionTask_UpdateFuncReturn: IEpSdkEnumVersionTask_UpdateFuncReturn = - { - epSdkTask_Action: this.getUpdateFuncAction(), - epObject: topicAddressEnumVersion, - epObjectKeys: this.getEpObjectKeys(topicAddressEnumVersion), - }; + EpSdkLogger.trace(EpSdkLogger.createLogEntry(logName, {code: EEpSdkLoggerCodes.TASK_EXECUTE_UPDATE,module: this.constructor.name,details: { + epSdkApplicationDomainTask_Config: this.getTaskConfig(), + update: update, + topicAddressEnumVersion: topicAddressEnumVersion, + }})); + const epSdkEnumVersionTask_UpdateFuncReturn: IEpSdkEnumVersionTask_UpdateFuncReturn = { + epSdkTask_Action: this.getUpdateFuncAction(), + epObject: topicAddressEnumVersion, + epObjectKeys: this.getEpObjectKeys(topicAddressEnumVersion), + }; return epSdkEnumVersionTask_UpdateFuncReturn; } public async execute(xContextId?: string): Promise { - const epSdkTask_ExecuteReturn: IEpSdkEnumVersionTask_ExecuteReturn = - await super.execute(xContextId); + const epSdkTask_ExecuteReturn: IEpSdkEnumVersionTask_ExecuteReturn = await super.execute(xContextId); return epSdkTask_ExecuteReturn; } } From 78f6d935f44b63c2011b4e19c03bc9c689f3d669 Mon Sep 17 00:00:00 2001 From: Ricardo Gomez_Ulmke Date: Sat, 11 Mar 2023 17:59:41 +0100 Subject: [PATCH 20/33] test --- packages/ep-asyncapi/.nycrc | 8 +- .../test/specs/test-pass/ep-downloads.spec.ts | 89 +++++++++++++++++++ 2 files changed, 93 insertions(+), 4 deletions(-) create mode 100644 packages/ep-asyncapi/test/specs/test-pass/ep-downloads.spec.ts diff --git a/packages/ep-asyncapi/.nycrc b/packages/ep-asyncapi/.nycrc index 11132c916..5c59f02b5 100644 --- a/packages/ep-asyncapi/.nycrc +++ b/packages/ep-asyncapi/.nycrc @@ -1,10 +1,10 @@ { "all": true, "check-coverage": true, - "statements": 78, - "branches": 67, - "functions": 77, - "lines": 79, + "statements": 80, + "branches": 69, + "functions": 80, + "lines": 82, "temp-dir": "./test/logs/nyc_output", "reporter": ["html", "text", "text-summary", "lcov"], "report-dir": "./test/logs/coverage", diff --git a/packages/ep-asyncapi/test/specs/test-pass/ep-downloads.spec.ts b/packages/ep-asyncapi/test/specs/test-pass/ep-downloads.spec.ts new file mode 100644 index 000000000..4ba3b69ae --- /dev/null +++ b/packages/ep-asyncapi/test/specs/test-pass/ep-downloads.spec.ts @@ -0,0 +1,89 @@ +import 'mocha'; +import { expect } from 'chai'; +import path from 'path'; +import { + TestContext, +} from '@internal/tools/src'; +import { + TestConfig, + TestLogger +} from '../../lib'; +import { + EpAsyncApiDocumentService, + EpAsyncApiDocument, + EpAsyncApiError, + T_EpAsyncApiChannelDocumentMap +} from '../../../src'; + + +const scriptName: string = path.basename(__filename); +TestLogger.logMessage(scriptName, ">>> starting ..."); + +let AsyncApiSpecFile: string; + +const expectedApplicationDomainName = "TEST_EP_ASYNC_API_IMPORTER/multi-domain.x-spec.ts/ApplicationDomain_Main_Name"; + + +describe(`${scriptName}`, () => { + + beforeEach(() => { + TestContext.newItId(); + }); + + it(`${scriptName}: should initialize globals`, async () => { + try { + AsyncApiSpecFile = `${TestConfig.getConfig().dataRootDir}/ep-downloads/EventApi-Name.json`; + } catch(e) { + expect(e instanceof EpAsyncApiError, TestLogger.createNotEpAsyncApiErrorMessage(e)).to.be.true; + expect(false, TestLogger.createEpAsyncApiTestFailMessage('failed', e)).to.be.true; + } + }); + + + it(`${scriptName}: should parse spec`, async () => { + try { + const epAsyncApiDocument: EpAsyncApiDocument = await EpAsyncApiDocumentService.createFromFile({ + filePath: AsyncApiSpecFile, + }); + const appDomainName = epAsyncApiDocument.getApplicationDomainName(); + expect(appDomainName, 'failed').to.eq(expectedApplicationDomainName); + // walk the document + const epAsyncApiChannelDocumentMap: T_EpAsyncApiChannelDocumentMap = epAsyncApiDocument.getEpAsyncApiChannelDocumentMap(); + for(const [topic, epAsyncApiChannelDocument] of epAsyncApiChannelDocumentMap) { + const epEventName = epAsyncApiChannelDocument.getEpEventName(); + const epEventVersionName = epAsyncApiChannelDocument.getEpEventVersionName(); + const epAsyncApiChannelParameterDocumentMap = epAsyncApiChannelDocument.getEpAsyncApiChannelParameterDocumentMap(); + for(const [parameter, epAsyncApiChannelParameterDocument] of epAsyncApiChannelParameterDocumentMap) { + const parameterDisplayName = epAsyncApiChannelParameterDocument.getDisplayName(); + const parameterDescription = epAsyncApiChannelParameterDocument.getDescription(); + const debug = { + topic, + epEventName, + epEventVersionName, + parameter, + parameterDisplayName, + parameterDescription + } + console.log(`debug = ${JSON.stringify(debug, null, 2)}`); + } + } + } catch(e) { + expect(e instanceof EpAsyncApiError, TestLogger.createNotEpAsyncApiErrorMessage(e)).to.be.true; + expect(false, TestLogger.createEpAsyncApiTestFailMessage('failed', e)).to.be.true; + } + }); + + it(`${scriptName}: should validate best practices`, async () => { + try { + const epAsyncApiDocument: EpAsyncApiDocument = await EpAsyncApiDocumentService.createFromFile({ + filePath: AsyncApiSpecFile, + }); + epAsyncApiDocument.validate_BestPractices(); + } catch(e) { + expect(e instanceof EpAsyncApiError, TestLogger.createNotEpAsyncApiErrorMessage(e)).to.be.true; + expect(false, TestLogger.createEpAsyncApiTestFailMessage('failed', e)).to.be.true; + } + }); + +}); + From 169053fff59b635b40229d5c94044cbb90450a7a Mon Sep 17 00:00:00 2001 From: Ricardo Gomez_Ulmke Date: Sun, 12 Mar 2023 15:07:12 +0100 Subject: [PATCH 21/33] test idempotency --- .../src/importers/CliAssetsImporter.ts | 36 +- .../src/importers/CliEventApiImporter.ts | 6 +- .../test/specs/ep-idempotency.x-spec.ts | 40 +- .../ep-asyncapi/src/constants/ep-xtensions.ts | 21 +- packages/ep-asyncapi/src/decs.d.ts | 1 + .../documents/EpAsyncApiChannelDocument.ts | 361 ++++++++++-------- .../documents/EpAsyncApiChannelOperation.ts | 2 +- .../EpAsyncApiChannelParameterDocument.ts | 15 +- .../src/documents/EpAsyncApiDocument.ts | 193 +++------- .../documents/EpAsyncApiMessageDocument.ts | 70 ++-- .../test/data/ep-downloads/EventApi-Name.json | 16 +- .../test-fail/very-long-event-name.spec.yml | 6 +- .../test/data/test-pass/kafka/Confluent.json | 153 ++++---- .../test/specs/test-pass/ep-downloads.spec.ts | 56 ++- packages/ep-asyncapi/tsconfig.json | 2 +- .../src/tasks/EpSdkApplicationVersionTask.ts | 67 +--- .../ep-sdk/src/tasks/EpSdkEnumVersionTask.ts | 57 +-- .../src/tasks/EpSdkEpEventVersionTask.ts | 96 ++--- .../src/tasks/EpSdkEventApiVersionTask.ts | 164 +++----- .../src/tasks/EpSdkSchemaVersionTask.ts | 309 +++++---------- 20 files changed, 734 insertions(+), 937 deletions(-) create mode 100644 packages/ep-asyncapi/src/decs.d.ts diff --git a/packages/ep-async-api-importer/src/importers/CliAssetsImporter.ts b/packages/ep-async-api-importer/src/importers/CliAssetsImporter.ts index 828da9e81..493fb7797 100644 --- a/packages/ep-async-api-importer/src/importers/CliAssetsImporter.ts +++ b/packages/ep-async-api-importer/src/importers/CliAssetsImporter.ts @@ -108,7 +108,6 @@ export abstract class CliAssetsImporter extends CliImporter { }); const eventId: string = eventObject.id; - const eventVersionDisplayName: string = epAsyncApiChannelDocument.getEpEventName(); const channelTopic: string = epAsyncApiChannelDocument.getAsyncApiChannelKey(); const epSdkEpEventVersionTask = new EpSdkEpEventVersionTask({ @@ -120,8 +119,8 @@ export abstract class CliAssetsImporter extends CliImporter { topicString: channelTopic, topicDelimiter: epAsyncApiChannelDocument.getChannelDelimiter(), eventVersionSettings: { - description: epAsyncApiMessageDocument.getDescription(), - displayName: eventVersionDisplayName, + description: epAsyncApiChannelDocument.getEpEventDescription(), + displayName: epAsyncApiChannelDocument.getEpEventVersionName(), schemaVersionId: schemaVersionId, stateId: this.get_EpSdkTask_StateId(), brokerType: epAsyncApiChannelDocument.getBrokerType() @@ -254,7 +253,10 @@ export abstract class CliAssetsImporter extends CliImporter { versionStrategy: this.get_EEpSdk_VersionTaskStrategy(), schemaVersionSettings: { content: JSON.stringify(epAsyncApiMessageDocument.getSchemaAsSanitizedJson()), - description: epAsyncApiMessageDocument.getPayloadSchemaDescription(), + // don't set the description, it remains in the schema + // otherwise no idempotency + // description: epAsyncApiMessageDocument.getPayloadSchemaDescription(), + description: '', displayName: epAsyncApiMessageDocument.getPayloadSchemaDisplayName(), stateId: this.get_EpSdkTask_StateId(), }, @@ -352,25 +354,13 @@ export abstract class CliAssetsImporter extends CliImporter { }): Promise => { const funcName = "run_present_enum_version"; const logName = `${CliAssetsImporter.name}.${funcName}()`; - CliLogger.debug( - CliLogger.createLogEntry(logName, { - code: ECliStatusCodes.IMPORTING_API_CHANNEL_PARAMETER, - details: {}, - }) - ); - CliLogger.trace( - CliLogger.createLogEntry(logName, { - code: ECliStatusCodes.IMPORTING_API_CHANNEL_PARAMETER, - details: { - enumObject: enumObject, - specVersion: specVersion, - epAsyncApiChannelParameterDocument: - epAsyncApiChannelParameterDocument, - checkmode: checkmode, - }, - }) - ); - + CliLogger.debug(CliLogger.createLogEntry(logName, {code: ECliStatusCodes.IMPORTING_API_CHANNEL_PARAMETER,details: {}})); + CliLogger.trace(CliLogger.createLogEntry(logName, {code: ECliStatusCodes.IMPORTING_API_CHANNEL_PARAMETER, details: { + enumObject: enumObject, + specVersion: specVersion, + epAsyncApiChannelParameterDocument: epAsyncApiChannelParameterDocument, + checkmode: checkmode, + }})); /* istanbul ignore next */ if (enumObject.id === undefined) throw new CliEPApiContentError(logName, "enumObject.id === undefined", { enumObject: enumObject, diff --git a/packages/ep-async-api-importer/src/importers/CliEventApiImporter.ts b/packages/ep-async-api-importer/src/importers/CliEventApiImporter.ts index 7c8c81f36..a4cca1909 100644 --- a/packages/ep-async-api-importer/src/importers/CliEventApiImporter.ts +++ b/packages/ep-async-api-importer/src/importers/CliEventApiImporter.ts @@ -147,7 +147,7 @@ export class CliEventApiImporter extends CliAssetsImporter { versionStrategy: EEpSdk_VersionTaskStrategy.EXACT_VERSION, eventApiVersionSettings: { description: epAsyncApiDocument.getDescription(), - displayName: epAsyncApiDocument.getTitle(), + displayName: epAsyncApiDocument.getEpEventApiVersionName(), producedEventVersionIds: cliPubSubEventVersionIds.publishEventVersionIdList, consumedEventVersionIds: cliPubSubEventVersionIds.subscribeEventVersionIdList, stateId: this.get_EpSdkTask_StateId(), @@ -189,7 +189,7 @@ export class CliEventApiImporter extends CliAssetsImporter { versionStrategy: EEpSdk_VersionTaskStrategy.BUMP_PATCH, eventApiVersionSettings: { description: epAsyncApiDocument.getDescription(), - displayName: epAsyncApiDocument.getTitle(), + displayName: epAsyncApiDocument.getEpEventApiVersionName(), producedEventVersionIds: cliPubSubEventVersionIds.publishEventVersionIdList, consumedEventVersionIds: cliPubSubEventVersionIds.subscribeEventVersionIdList, // stateId: CliEPStatesService.getTargetLifecycleState({cliAssetImport_TargetLifecycleState: ECliAssetImport_TargetLifecycleState.DRAFT }), @@ -257,7 +257,7 @@ export class CliEventApiImporter extends CliAssetsImporter { versionStrategy: EEpSdk_VersionTaskStrategy.EXACT_VERSION, eventApiVersionSettings: { description: epAsyncApiDocument.getDescription(), - displayName: epAsyncApiDocument.getTitle(), + displayName: epAsyncApiDocument.getEpEventApiVersionName(), producedEventVersionIds: cliPubSubEventVersionIds.publishEventVersionIdList, consumedEventVersionIds: cliPubSubEventVersionIds.subscribeEventVersionIdList, stateId: this.get_EpSdkTask_StateId(), diff --git a/packages/ep-async-api-importer/test/specs/ep-idempotency.x-spec.ts b/packages/ep-async-api-importer/test/specs/ep-idempotency.x-spec.ts index 1e4b0fb52..6a2d03995 100644 --- a/packages/ep-async-api-importer/test/specs/ep-idempotency.x-spec.ts +++ b/packages/ep-async-api-importer/test/specs/ep-idempotency.x-spec.ts @@ -54,6 +54,7 @@ import { EpAsyncApiDocument, EpAsyncApiDocumentService } from "@solace-labs/ep-asyncapi"; +import { ECliAssetImport_TargetVersionStrategy } from "../../src/importers"; const scriptName: string = path.basename(__filename); const TestSpecName = scriptName; @@ -69,8 +70,7 @@ let SchemaVersion_1_Id: string | undefined; let Schema_2_Name: string; let Schema_2_Id: string | undefined; let SchemaVersion_2_Id: string | undefined; -const SchemaContent = ` -{ +const SchemaContent = `{ "description": "Generic message header.", "type": "object", "properties": { @@ -93,8 +93,7 @@ const SchemaContent = ` "transactionId", "storeId" ] -} -`; +}`; let Enum_1_Name: string; let Enum_1_Id: string | undefined; @@ -198,9 +197,9 @@ describe(`${scriptName}`, () => { versionString: "1.0.0", schemaVersionSettings: { stateId: EpSdkStatesService.releasedId, - displayName: 'Schema_1_Id', + displayName: `${Schema_1_Name} displayName`, // description: 'Schema_1_Id', - content: SchemaContent, + content: JSON.stringify(JSON.parse(SchemaContent)), }, }); const task_1_1_ExecuteReturn: IEpSdkSchemaVersionTask_ExecuteReturn = await task_1_1.execute(); @@ -224,9 +223,9 @@ describe(`${scriptName}`, () => { versionString: "1.0.0", schemaVersionSettings: { stateId: EpSdkStatesService.releasedId, - displayName: 'Schema_2_Id', + displayName: `${Schema_2_Name} displayName`, // description: 'Schema_2_Id', - content: SchemaContent, + content: JSON.stringify(JSON.parse(SchemaContent)), }, }); const task_2_1_ExecuteReturn: IEpSdkSchemaVersionTask_ExecuteReturn = await task_2_1.execute(); @@ -257,8 +256,7 @@ describe(`${scriptName}`, () => { versionString: "1.0.0", enumVersionSettings: { stateId: EpSdkStatesService.releasedId, - displayName: 'Enum_1_Id', - // description: 'Enum_1_Id', + displayName: `${Enum_1_Name} displayName`, }, enumValues: EnumValues }); @@ -282,8 +280,7 @@ describe(`${scriptName}`, () => { versionString: "1.0.0", enumVersionSettings: { stateId: EpSdkStatesService.releasedId, - displayName: 'Enum_2_Id', - // description: 'Enum_2_Id', + displayName: `${Enum_2_Name} displayName`, }, enumValues: EnumValues }); @@ -316,8 +313,8 @@ describe(`${scriptName}`, () => { eventId: Event_1_Id, versionString: "1.0.0", eventVersionSettings: { - displayName: 'Event_1_Id', - description: 'Event_1_Id', + displayName: `${Event_1_Name} displayName`, + description: `${Event_1_Name} description`, schemaVersionId: SchemaVersion_1_Id, stateId: EpSdkStatesService.releasedId, }, @@ -343,8 +340,8 @@ describe(`${scriptName}`, () => { eventId: Event_2_Id, versionString: "1.0.0", eventVersionSettings: { - displayName: 'Event_2_Id', - // description: 'Event_2_Id', + displayName: `${Event_2_Name} displayName`, + description: `${Event_2_Name} description`, schemaVersionId: SchemaVersion_2_Id, stateId: EpSdkStatesService.releasedId, }, @@ -380,8 +377,8 @@ describe(`${scriptName}`, () => { versionString: "1.0.0", eventApiVersionSettings: { stateId: EpSdkStatesService.releasedId, - displayName: 'EventApi_Id', - description: 'EventApi_Id', + displayName: `${EventApi_Name} displayName`, + description: `${EventApi_Name} description`, consumedEventVersionIds: [EventVersion_1_Id], producedEventVersionIds: [EventVersion_2_Id], } @@ -414,8 +411,8 @@ describe(`${scriptName}`, () => { applicationId: App_Id, versionString: "1.0.0", applicationVersionSettings: { - displayName: 'App_Id', - description: 'App_Id', + displayName: `${App_Name} displayName`, + description: `${App_Name} description`, declaredConsumedEventVersionIds: [EventVersion_2_Id], declaredProducedEventVersionIds: [EventVersion_1_Id], stateId: EpSdkStatesService.releasedId, @@ -467,6 +464,7 @@ describe(`${scriptName}`, () => { try { CliConfig.getCliImporterManagerOptions().asyncApiFileList = [AsyncApiSpecFileNameJson]; CliConfig.getCliImporterManagerOptions().cliImporterManagerMode = ECliImporterManagerMode.RELEASE_MODE; + CliConfig.getCliImporterManagerOptions().cliTestSetupDomainsForApis = true; // CliConfig.getCliImporterManagerOptions().runId = scriptName; // // DEBUG // CliConfig.getCliImporterManagerOptions().cliImporterManagerMode = ECliImporterManagerMode.TEST_MODE_KEEP; @@ -474,6 +472,8 @@ describe(`${scriptName}`, () => { CliConfig.getCliImporterManagerOptions().createEventApiApplication = true; CliConfig.getCliImporterManagerOptions().cliImporterOptions.cliAssetImport_BrokerType = undefined; CliConfig.getCliImporterManagerOptions().cliImporterOptions.cliAssetImport_ChannelDelimiter = undefined; + CliConfig.getCliImporterManagerOptions().cliImporterOptions.cliValidateApiSpecBestPractices = true; + CliConfig.getCliImporterManagerOptions().cliImporterOptions.cliAssetImport_TargetVersionStrategy = ECliAssetImport_TargetVersionStrategy.BUMP_PATCH; const cliImporter = new CliImporterManager(CliConfig.getCliImporterManagerOptions()); const xvoid: void = await cliImporter.run(); diff --git a/packages/ep-asyncapi/src/constants/ep-xtensions.ts b/packages/ep-asyncapi/src/constants/ep-xtensions.ts index aea519603..53d5d8c54 100644 --- a/packages/ep-asyncapi/src/constants/ep-xtensions.ts +++ b/packages/ep-asyncapi/src/constants/ep-xtensions.ts @@ -1,15 +1,26 @@ -export enum EpAsyncApiParameterExtensions { +/** extensions used by EP when exporting spec */ +export enum EpParameterExtensions { xEpEnumName = "x-ep-enum-name", xEpParameterName = "x-ep-parameter-name", xEpEnumVersionDisplayName = "x-ep-enum-version-displayname", } - -export enum EpAsyncApiMessageExtensions { +/** extensions used by EP when exporting spec */ +export enum EpMessageExtensions { xEpEventName = "x-ep-event-name", xEpEventVersionDisplayName = "x-ep-event-version-displayname", } - -export enum EpAsyncApiSchemaExtensions { +/** extensions used by EP when exporting spec */ +export enum EpSchemaExtensions { xEpSchemaName = "x-ep-schema-name", xEpSchemaVersionDisplayName = "x-ep-schema-version-displayname", } +/** extensions used by EP when exporting spec */ +export enum EpApiInfoExtensions { + xEpApiInfoVersionDisplayName = "x-ep-displayname", +} + +/** extensions used by this module when reading spec */ +export enum EpAsyncApiChannelExtensions { + xEpEventName = "x-ep-event-name", +} + diff --git a/packages/ep-asyncapi/src/decs.d.ts b/packages/ep-asyncapi/src/decs.d.ts new file mode 100644 index 000000000..a8f5520f7 --- /dev/null +++ b/packages/ep-asyncapi/src/decs.d.ts @@ -0,0 +1 @@ +declare module '@asyncapi/avro-schema-parser'; \ No newline at end of file diff --git a/packages/ep-asyncapi/src/documents/EpAsyncApiChannelDocument.ts b/packages/ep-asyncapi/src/documents/EpAsyncApiChannelDocument.ts index 46a0dc108..27e5b2ee7 100644 --- a/packages/ep-asyncapi/src/documents/EpAsyncApiChannelDocument.ts +++ b/packages/ep-asyncapi/src/documents/EpAsyncApiChannelDocument.ts @@ -1,6 +1,7 @@ -import { Channel, ChannelParameter } from "@asyncapi/parser"; +import { Channel, ChannelParameter, Message } from "@asyncapi/parser"; import { $Event, $EventVersion } from "@solace-labs/ep-openapi-node"; import { Validator, ValidatorResult } from "jsonschema"; +import { EpAsyncApiChannelExtensions } from "../constants"; import { EpAsyncApiInternalError, EpAsyncApiValidationError @@ -18,147 +19,191 @@ import { EpAsyncApiDocument, T_EpAsyncApiChannelParameterDocumentMap, } from "./EpAsyncApiDocument"; +import { EpAsyncApiMessageDocument } from "./EpAsyncApiMessageDocument"; -enum E_EpAsyncApiExtensions { - X_EP_EVENT_NAME = "x-ep-event-name", +export enum EpAsyncApiChannelOperationType { + PublishOperation = "PublishOperation", + SubscribeOperation = "SubscribeOperation" } export class EpAsyncApiChannelDocument { private epAsyncApiDocument: EpAsyncApiDocument; private asyncApiChannelKey: string; private asyncApiChannel: Channel; + /** 1 channel can only have 1 message document */ + private epAsyncApiMessageDocument?: EpAsyncApiMessageDocument; private epEventName?: string; private epEventVersionName?: string; + private epEventDescription?: string; - constructor( - epAsyncApiDocument: EpAsyncApiDocument, - asyncApiChannelKey: string, - asyncApiChannel: Channel - ) { + constructor(epAsyncApiDocument: EpAsyncApiDocument, asyncApiChannelKey: string, asyncApiChannel: Channel) { this.epAsyncApiDocument = epAsyncApiDocument; this.asyncApiChannelKey = asyncApiChannelKey; this.asyncApiChannel = asyncApiChannel; + this.epAsyncApiMessageDocument = this.createMessageDocument(); + this.epEventName = this.createEpEventName(); + this.epEventVersionName = this.createEpEventVersionName(); + this.epEventDescription = this.createEpEventDescription(); } - private get_X_EpEventName(): string | undefined { - if (this.asyncApiChannel.hasExtension(E_EpAsyncApiExtensions.X_EP_EVENT_NAME)) - return this.asyncApiChannel.extension(E_EpAsyncApiExtensions.X_EP_EVENT_NAME); + private get_X_AsyncApi_EpEventName(): string | undefined { + if(this.asyncApiChannel.hasExtension(EpAsyncApiChannelExtensions.xEpEventName)) { + const eventName = this.asyncApiChannel.extension(EpAsyncApiChannelExtensions.xEpEventName); + if(eventName && eventName.length > 0) return eventName; + } return undefined; } - private createEpEventName() { - if (this.epEventName !== undefined) return; - const xEpEventName: string | undefined = this.get_X_EpEventName(); - if (xEpEventName !== undefined) this.epEventName = xEpEventName; - else { - this.epEventName = this.asyncApiChannelKey; + + public getAllChannelMessageDocuments(): Map> { + const operationMessageMap = new Map>(); + if(this.asyncApiChannel.hasPublish()) { + const publishOperation = this.asyncApiChannel.publish(); + if(publishOperation.hasMultipleMessages()) { + const messages: Array = publishOperation.messages(); + const epAsyncApiMessageDocuments: Array = []; + for(const message of messages) { + const epAsyncApiMessageDocument = new EpAsyncApiMessageDocument( + this.epAsyncApiDocument, + this, + message + ); + epAsyncApiMessageDocuments.push(epAsyncApiMessageDocument); + } + operationMessageMap.set(EpAsyncApiChannelOperationType.PublishOperation, epAsyncApiMessageDocuments); + } else { + const message: Message = publishOperation.message(); + const epAsyncApiMessageDocument = new EpAsyncApiMessageDocument( + this.epAsyncApiDocument, + this, + message + ); + operationMessageMap.set(EpAsyncApiChannelOperationType.PublishOperation, [epAsyncApiMessageDocument]); + } } - // Note: message name must NOT contain slashes '/', otherwise exported async api channel will reference a message which will NOT be found. - //eslint-disable-next-line - this.epEventName = this.epEventName.replaceAll(/[^0-9a-zA-Z\._]+/g, "-"); - } - private createEpEventVersionName() { - if (this.epEventVersionName !== undefined) return; - try { - this._validate_EpEventVersionName(this.getEpEventName()); - this.epEventVersionName = this.getEpEventName(); - } catch (e: any) { - if (e instanceof EpAsyncApiValidationError) { - // set to empty string - this.epEventVersionName = ""; + if(this.asyncApiChannel.hasSubscribe()) { + const subscribeOperation = this.asyncApiChannel.subscribe(); + if(subscribeOperation.hasMultipleMessages()) { + const messages: Array = subscribeOperation.messages(); + const epAsyncApiMessageDocuments: Array = []; + for(const message of messages) { + const epAsyncApiMessageDocument = new EpAsyncApiMessageDocument( + this.epAsyncApiDocument, + this, + message + ); + epAsyncApiMessageDocuments.push(epAsyncApiMessageDocument); + } + operationMessageMap.set(EpAsyncApiChannelOperationType.SubscribeOperation, epAsyncApiMessageDocuments); + } else { + const message: Message = subscribeOperation.message(); + const epAsyncApiMessageDocument = new EpAsyncApiMessageDocument( + this.epAsyncApiDocument, + this, + message + ); + operationMessageMap.set(EpAsyncApiChannelOperationType.SubscribeOperation, [epAsyncApiMessageDocument]); } } + return operationMessageMap; + } + /** + * Get all messages for pub & sub operations. + * If more than 1 found or they are different return undefined + */ + private createMessageDocument(): EpAsyncApiMessageDocument | undefined { + const operationMesssagesMap: Map> = this.getAllChannelMessageDocuments(); + const pubMessages = operationMesssagesMap.get(EpAsyncApiChannelOperationType.PublishOperation); + const subMessages = operationMesssagesMap.get(EpAsyncApiChannelOperationType.SubscribeOperation); + // no message found + if(!pubMessages && !subMessages) return undefined; + // only 1 message allowed + if(pubMessages && pubMessages.length > 1) return undefined; + if(subMessages && subMessages.length > 1) return undefined; + // check both messages are the same + const pubMessageName = pubMessages && pubMessages[0].getMessageName(); + const subMessageName = subMessages && subMessages[0].getMessageName(); + if(pubMessageName && subMessageName && pubMessageName !== subMessageName) return undefined; + // return either one since they are the same + if(pubMessageName) return pubMessages[0]; + if(subMessageName) return subMessages[0]; } - private validate_EpName = () => { - const funcName = "validate_EpName"; - const logName = `${EpAsyncApiChannelDocument.name}.${funcName}()`; - // WORKAROUND_UNTIL_EP_API_FIXED - const schema = { - ...$Event.properties.name, - maxLength: 60, - }; - - this.createEpEventName(); - if (this.epEventName === undefined) - throw new EpAsyncApiInternalError( - logName, - this.constructor.name, - "this.epEventName === undefined" - ); - const v: Validator = new Validator(); - const validateResult: ValidatorResult = v.validate( - this.epEventName, - schema - ); - - if (!validateResult.valid) - throw new EpAsyncApiValidationError( - logName, - this.constructor.name, - undefined, - { - asyncApiSpecTitle: this.epAsyncApiDocument.getTitle(), - issues: validateResult.errors, - value: { - epEventName: this.epEventName, - length: this.epEventName.length, - }, - } - ); - }; + private createEpEventName(): string | undefined { + if(this.epEventName !== undefined) return this.epEventName; + // try channel extension first + const eventName: string | undefined = this.get_X_AsyncApi_EpEventName(); + if(eventName !== undefined) return eventName; + if(this.epAsyncApiMessageDocument) { + // get the event name from the message document + return this.epAsyncApiMessageDocument.getMessageName(); + } + // none found + return undefined; + // else { + // // get the event name from the channel key as last resort + // // Note: message name must NOT contain slashes '/', otherwise exported async api channel will reference a message which will NOT be found. + // //eslint-disable-next-line + // return this.asyncApiChannelKey.replaceAll(/[^0-9a-zA-Z\._]+/g, "-"); + // } + } + private createEpEventVersionName(): string { + if(this.epEventVersionName !== undefined) return this.epEventVersionName; + if(this.epAsyncApiMessageDocument) { + return this.epAsyncApiMessageDocument.getMessageDisplayName(); + } + // set to empty string for better logging + return ''; + } + private createEpEventDescription(): string { + if(this.epEventDescription !== undefined) return this.epEventDescription; + if(this.epAsyncApiMessageDocument) return this.epAsyncApiMessageDocument.getMessageDescription(); + // set to empty string for better logging + return ''; + } - private _validate_EpEventVersionName = ( - epEventVersionName: string - ): string => { - const funcName = "_validate_EpEventVersionName"; + private validateEpEventName = () => { + const funcName = "validateEpEventName"; const logName = `${EpAsyncApiChannelDocument.name}.${funcName}()`; - const schema = $EventVersion.properties.displayName; + const epEventName = this.createEpEventName(); + if(epEventName === undefined) throw new EpAsyncApiValidationError(logName, this.constructor.name, undefined, { + asyncApiSpecTitle: this.epAsyncApiDocument.getTitle(), + value: { + channel: this.asyncApiChannelKey + }, + issues: 'unable to create EP Event Name for channel', + }); + const schema = $Event.properties.name; const v: Validator = new Validator(); - const validateResult: ValidatorResult = v.validate( - epEventVersionName, - schema - ); + const validateResult: ValidatorResult = v.validate(epEventName, schema); if (!validateResult.valid) throw new EpAsyncApiValidationError(logName, this.constructor.name, undefined, { asyncApiSpecTitle: this.epAsyncApiDocument.getTitle(), - issues: validateResult.errors, value: { - epEventVersionName: epEventVersionName, - length: epEventVersionName.length, + channel: this.asyncApiChannelKey, + epEventName: epEventName }, + issues: validateResult.errors, }); - return epEventVersionName; }; - private validate_EpEventVersionName = () => { - const funcName = "validate_EpEventVersionName"; + private validateEpEventVersionName = () => { + const funcName = "validateEpEventVersionName"; const logName = `${EpAsyncApiChannelDocument.name}.${funcName}()`; + const epEventVersionName = this.createEpEventVersionName(); const schema = $EventVersion.properties.displayName; - - this.createEpEventVersionName(); - if (this.epEventVersionName === undefined) - throw new EpAsyncApiInternalError( - logName, - this.constructor.name, - "this.epEventVersionName === undefined" - ); const v: Validator = new Validator(); - const validateResult: ValidatorResult = v.validate( - this.epEventVersionName, - schema - ); - - if (!validateResult.valid) - throw new EpAsyncApiValidationError(logName, this.constructor.name, undefined, { - asyncApiSpecTitle: this.epAsyncApiDocument.getTitle(), - issues: validateResult.errors, - value: { - epEventVersionName: this.epEventVersionName, - }, - }); + const validateResult: ValidatorResult = v.validate(epEventVersionName, schema); + if (!validateResult.valid) throw new EpAsyncApiValidationError(logName, this.constructor.name, undefined, { + asyncApiSpecTitle: this.epAsyncApiDocument.getTitle(), + value: { + channel: this.asyncApiChannelKey, + epEventVersionName: epEventVersionName + }, + issues: validateResult.errors, + }); }; - public validate_BrokerType(): void { - const funcName = "validate_BrokerType"; + public validateBrokerType(): void { + const funcName = "validateBrokerType"; const logName = `${EpAsyncApiChannelDocument.name}.${funcName}()`; if(this.getBrokerType() !== EBrokerTypes.KAFKA) return; const epAsyncApiChannelParameterDocumentMap: T_EpAsyncApiChannelParameterDocumentMap | undefined = this.getEpAsyncApiChannelParameterDocumentMap(); @@ -173,11 +218,44 @@ export class EpAsyncApiChannelDocument { } } + private validateChannelMessage(): void { + const funcName = "validateChannelMessage"; + const logName = `${EpAsyncApiChannelDocument.name}.${funcName}()`; + const throwIssues = (issues: any) => { + throw new EpAsyncApiValidationError(logName, this.constructor.name, undefined, { + asyncApiSpecTitle: this.epAsyncApiDocument.getTitle(), + issues: issues, + value: { + channel: this.getAsyncApiChannelKey(), + }, + }); + } + const messageDocument = this.createMessageDocument(); + if(messageDocument !== undefined) return; + const operationMesssagesMap: Map> = this.getAllChannelMessageDocuments(); + const pubMessages = operationMesssagesMap.get(EpAsyncApiChannelOperationType.PublishOperation); + const subMessages = operationMesssagesMap.get(EpAsyncApiChannelOperationType.SubscribeOperation); + // no message found + if(!pubMessages && !subMessages) throwIssues('no message found'); + // only 1 message allowed + if(pubMessages && pubMessages.length > 1) throwIssues('found multiple messages for publish operation (only 1 message allowed)'); + if(subMessages && subMessages.length > 1) throwIssues('found multiple messages for subscribe operation (only 1 message allowed)'); + // check both messages are the same + const pubMessageName = pubMessages && pubMessages[0].getMessageName(); + const subMessageName = subMessages && subMessages[0].getMessageName(); + if(pubMessageName && subMessageName && pubMessageName !== subMessageName) throwIssues({ + message: 'found different messages for publish and subscribe operations (only 1 message allowed)', + pubMessageName: pubMessageName, + subMessageName: subMessageName + }); + } + public validate(): void { // this doc - this.validate_EpName(); - this.validate_EpEventVersionName(); - this.validate_BrokerType(); + this.validateChannelMessage(); + this.validateEpEventName(); + this.validateEpEventVersionName(); + this.validateBrokerType(); // channel parameters const epAsyncApiChannelParameterDocumentMap: T_EpAsyncApiChannelParameterDocumentMap | undefined = this.getEpAsyncApiChannelParameterDocumentMap(); if (epAsyncApiChannelParameterDocumentMap !== undefined) { @@ -203,60 +281,51 @@ export class EpAsyncApiChannelDocument { // channel parameters const epAsyncApiChannelParameterDocumentMap: T_EpAsyncApiChannelParameterDocumentMap | undefined = this.getEpAsyncApiChannelParameterDocumentMap(); if (epAsyncApiChannelParameterDocumentMap !== undefined) { - for (const [ - parameterName, - epAsyncApiChannelParameterDocument, - ] of epAsyncApiChannelParameterDocumentMap) { - parameterName; + for (const [_parameterName, epAsyncApiChannelParameterDocument] of epAsyncApiChannelParameterDocumentMap) { epAsyncApiChannelParameterDocument.validate_BestPractices(); } } // channel operations const epAsynApiChannelPublishOperation: EpAsynApiChannelPublishOperation | undefined = this.getEpAsyncApiChannelPublishOperation(); - if (epAsynApiChannelPublishOperation !== undefined) { - epAsynApiChannelPublishOperation.validate_BestPractices(); - } + if(epAsynApiChannelPublishOperation !== undefined) epAsynApiChannelPublishOperation.validate_BestPractices(); const epAsynApiChannelSubscribeOperation: EpAsyncApiChannelSubscribeOperation | undefined = this.getEpAsyncApiChannelSubscribeOperation(); - if (epAsynApiChannelSubscribeOperation !== undefined) { - epAsynApiChannelSubscribeOperation.validate_BestPractices(); - } + if(epAsynApiChannelSubscribeOperation !== undefined) epAsynApiChannelSubscribeOperation.validate_BestPractices(); } - public getAsyncApiChannel(): Channel { - return this.asyncApiChannel; - } + public getAsyncApiChannel(): Channel { return this.asyncApiChannel; } - public getAsyncApiChannelKey(): string { - return this.asyncApiChannelKey; - } + public getAsyncApiChannelKey(): string { return this.asyncApiChannelKey; } - /** - * Return the event name for EP from: - * 1) channel extension: x-ep-event-name - * 2) channel topic - */ public getEpEventName(): string { const funcName = "getEpEventName"; const logName = `${EpAsyncApiDocument.name}.${funcName}()`; - if (this.epEventName === undefined) { - this.createEpEventName(); - this.validate_EpName(); - } - if (this.epEventName === undefined) throw new EpAsyncApiInternalError(logName, this.constructor.name, "this.epEventName === undefined"); + if(this.epEventName === undefined) throw new EpAsyncApiInternalError(logName, this.constructor.name, "this.epEventName === undefined"); + // if(this.epEventName === undefined) { + // this.epEventName = this.createEpEventName(); + // this.validateEpEventName(); + // } + // if(this.epEventName === undefined) throw new EpAsyncApiInternalError(logName, this.constructor.name, "this.epEventName === undefined"); return this.epEventName; } public getEpEventVersionName(): string { const funcName = "getEpEventVersionName"; const logName = `${EpAsyncApiDocument.name}.${funcName}()`; - if (this.epEventVersionName === undefined) { - this.createEpEventVersionName(); - this.validate_EpEventVersionName(); - } - if (this.epEventVersionName === undefined) throw new EpAsyncApiInternalError(logName, this.constructor.name, "this.epEventVersionName === undefined"); + if(this.epEventVersionName === undefined) throw new EpAsyncApiInternalError(logName, this.constructor.name, "this.epEventVersionName === undefined"); + // if(this.epEventVersionName === undefined) { + // this.epEventVersionName = this.createEpEventVersionName(); + // this.validateEpEventVersionName(); + // } return this.epEventVersionName; } + public getEpEventDescription(): string { + const funcName = "getEpEventDescription"; + const logName = `${EpAsyncApiDocument.name}.${funcName}()`; + if(this.epEventDescription === undefined) throw new EpAsyncApiInternalError(logName, this.constructor.name, "this.epEventDescription === undefined"); + return this.epEventDescription; + } + public getApplicationDomainName(): string { return this.epAsyncApiDocument.getAssetsApplicationDomainName(); } @@ -277,21 +346,15 @@ export class EpAsyncApiChannelDocument { public getChannelDelimiter(): EChannelDelimiters { return this.epAsyncApiDocument.getChannelDelimiter(); } public getEpAsyncApiChannelPublishOperation(): EpAsynApiChannelPublishOperation | undefined { - if (this.asyncApiChannel.hasPublish()) { return new EpAsynApiChannelPublishOperation( - this.epAsyncApiDocument, - this, - this.asyncApiChannel.publish() - ); + if (this.asyncApiChannel.hasPublish()) { + return new EpAsynApiChannelPublishOperation(this.epAsyncApiDocument, this, this.asyncApiChannel.publish()); } return undefined; } public getEpAsyncApiChannelSubscribeOperation(): EpAsyncApiChannelSubscribeOperation | undefined { if (this.asyncApiChannel.hasSubscribe()) { - return new EpAsyncApiChannelSubscribeOperation( - this.epAsyncApiDocument, - this, - this.asyncApiChannel.subscribe() + return new EpAsyncApiChannelSubscribeOperation(this.epAsyncApiDocument, this, this.asyncApiChannel.subscribe() ); } return undefined; diff --git a/packages/ep-asyncapi/src/documents/EpAsyncApiChannelOperation.ts b/packages/ep-asyncapi/src/documents/EpAsyncApiChannelOperation.ts index 4555537f8..2cf0427cb 100644 --- a/packages/ep-asyncapi/src/documents/EpAsyncApiChannelOperation.ts +++ b/packages/ep-asyncapi/src/documents/EpAsyncApiChannelOperation.ts @@ -45,7 +45,7 @@ abstract class EpAsyncApiChannelOperation { asyncApiChannelOperation: asyncApiChannelOperation, asyncApiSpecTitle: this.epAsyncApiDocument.getTitle(), }); - return new EpAsyncApiMessageDocument(this.epAsyncApiDocument, this.epAsyncApiChannelDocument, undefined, messageList[0]); + return new EpAsyncApiMessageDocument(this.epAsyncApiDocument, this.epAsyncApiChannelDocument, messageList[0]); } } diff --git a/packages/ep-asyncapi/src/documents/EpAsyncApiChannelParameterDocument.ts b/packages/ep-asyncapi/src/documents/EpAsyncApiChannelParameterDocument.ts index 33a3fd400..86fe7f430 100644 --- a/packages/ep-asyncapi/src/documents/EpAsyncApiChannelParameterDocument.ts +++ b/packages/ep-asyncapi/src/documents/EpAsyncApiChannelParameterDocument.ts @@ -2,7 +2,9 @@ import { ChannelParameter, Schema, } from '@asyncapi/parser'; -import { EpAsyncApiParameterExtensions } from '../constants'; +import { + EpParameterExtensions +} from '../constants'; export class EpAsyncApiChannelParameterDocument { private channelParameterName: string; @@ -23,15 +25,18 @@ export class EpAsyncApiChannelParameterDocument { public getAsyncApiChannelParameter(): ChannelParameter { return this.asyncApiChannelParameter; } - public getDescription(): string | undefined { + public getDescription(): string { const description: string | null = this.asyncApiChannelParameter.description(); if(description && description.length > 0) return description; + return ''; } - public getDisplayName(): string | undefined { - if(this.asyncApiChannelParameter.hasExtension(EpAsyncApiParameterExtensions.xEpEnumVersionDisplayName)) { - return this.asyncApiChannelParameter.extension(EpAsyncApiParameterExtensions.xEpEnumVersionDisplayName); + public getDisplayName(): string { + if(this.asyncApiChannelParameter.hasExtension(EpParameterExtensions.xEpEnumVersionDisplayName)) { + const displayName = this.asyncApiChannelParameter.extension(EpParameterExtensions.xEpEnumVersionDisplayName); + if(displayName && displayName.length > 0) return displayName; } + return ''; } public getParameterEnumValueList(): Array { diff --git a/packages/ep-asyncapi/src/documents/EpAsyncApiDocument.ts b/packages/ep-asyncapi/src/documents/EpAsyncApiDocument.ts index 316051dca..e7c96b67b 100644 --- a/packages/ep-asyncapi/src/documents/EpAsyncApiDocument.ts +++ b/packages/ep-asyncapi/src/documents/EpAsyncApiDocument.ts @@ -10,12 +10,13 @@ import { EpAsyncApiXtensionError, } from "../utils"; import { EpAsyncApiMessageDocument } from "./EpAsyncApiMessageDocument"; -import { EpAsyncApiChannelDocument } from "./EpAsyncApiChannelDocument"; +import { EpAsyncApiChannelDocument, EpAsyncApiChannelOperationType } from "./EpAsyncApiChannelDocument"; import { EpAsyncApiChannelParameterDocument } from "./EpAsyncApiChannelParameterDocument"; import { EpAsynApiChannelPublishOperation, EpAsyncApiChannelSubscribeOperation, } from "./EpAsyncApiChannelOperation"; +import { EpApiInfoExtensions } from "../constants"; export enum E_EpAsyncApiExtensions { X_EP_APPLICATION_DOMAIN_NAME = "x-ep-application-domain-name", @@ -82,7 +83,7 @@ export class EpAsyncApiDocument { private overrideBrokerType: string | undefined; private channelDelimiter: EChannelDelimiters; private overrideChannelDelimiter: string | undefined; - private epEventApiName?: string; + private epEventApiName: string; private epEventApiVersionName?: string; private getJSON(asyncApiDocument: AsyncAPIDocument): any { @@ -176,15 +177,18 @@ export class EpAsyncApiDocument { if(channelDelimiter === undefined) channelDelimiter = EpAsyncApiDocument.DefaultChannelDelimiter; return channelDelimiter as EChannelDelimiters; } - private createEpEventApiName() { - if (this.epEventApiName !== undefined) return; - const xEpEventApiName: string = this.getTitle(); - this.epEventApiName = xEpEventApiName; + private createEpEventApiName(): string { + if(this.epEventApiName !== undefined) return this.epEventApiName; + return this.getTitle(); } - private createEpEventApiVersionName() { - if (this.epEventApiVersionName !== undefined) return; - const xEpEventApiVersionName: string = this.getTitle(); - this.epEventApiVersionName = xEpEventApiVersionName; + private createEpEventApiVersionName(): string { + if(!this.asyncApiDocument.info()) return ''; + if(this.asyncApiDocument.info().hasExtension(EpApiInfoExtensions.xEpApiInfoVersionDisplayName)) { + const eventApiDisplayName = this.asyncApiDocument.info().extension(EpApiInfoExtensions.xEpApiInfoVersionDisplayName); + if(eventApiDisplayName && eventApiDisplayName.length > 0) return eventApiDisplayName; + } + // set to empty for better logging + return ''; } private createOriginalApiSpecJson(originalApiSpec: any): any { const funcName = "createOriginalApiSpecJson"; @@ -214,11 +218,7 @@ export class EpAsyncApiDocument { return json; } } catch (e) { - throw new EpAsyncApiInternalError( - logName, - this.constructor.name, - "unable to determine original spec type" - ); + throw new EpAsyncApiInternalError(logName,this.constructor.name,"unable to determine original spec type"); } } } @@ -245,72 +245,41 @@ export class EpAsyncApiDocument { this.overrideChannelDelimiter = overrideChannelDelimiter; this.brokerType = this.createBrokerType(); this.channelDelimiter = this.createChannelDelimiter(); + this.epEventApiName = this.createEpEventApiName(); + this.epEventApiVersionName = this.createEpEventApiVersionName(); } - private validate_EpEventApiName = () => { - const funcName = "validate_EpEventApiName"; + private validateEpEventApiName = () => { + const funcName = "validateEpEventApiName"; const logName = `${EpAsyncApiDocument.name}.${funcName}()`; + const eventApiName = this.epEventApiName || this.createEpEventApiName(); const schema = $EventApi.properties.name; - - this.createEpEventApiName(); - if (this.epEventApiName === undefined) - throw new EpAsyncApiInternalError( - logName, - this.constructor.name, - "this.epEventApiName === undefined" - ); const v: Validator = new Validator(); - const validateResult: ValidatorResult = v.validate( - this.epEventApiName, - schema - ); - - if (!validateResult.valid) - throw new EpAsyncApiValidationError( - logName, - this.constructor.name, - undefined, - { - asyncApiSpecTitle: this.getTitle(), - issues: validateResult.errors, - value: { - epEventApiName: this.epEventApiName, - }, - } - ); + const validateResult: ValidatorResult = v.validate(eventApiName, schema); + if (!validateResult.valid) throw new EpAsyncApiValidationError(logName,this.constructor.name,undefined,{ + asyncApiSpecTitle: this.getTitle(), + issues: validateResult.errors, + value: { + epEventApiName: this.epEventApiName, + } + }); }; - private validate_EpEventApiVersionName = () => { - const funcName = "validate_EpEventApiVersionName"; + private validateEpEventApiVersionName = () => { + const funcName = "validateEpEventApiVersionName"; const logName = `${EpAsyncApiDocument.name}.${funcName}()`; + const eventApiVersionName = this.epEventApiVersionName || this.createEpEventApiVersionName(); + if(eventApiVersionName === undefined) throw new EpAsyncApiInternalError(logName, this.constructor.name, 'eventApiVersionName === undefined'); const schema = $EventApiVersion.properties.displayName; - - this.createEpEventApiVersionName(); - if (this.epEventApiVersionName === undefined) - throw new EpAsyncApiInternalError( - logName, - this.constructor.name, - "this.epEventApiVersionName === undefined" - ); const v: Validator = new Validator(); - const validateResult: ValidatorResult = v.validate( - this.epEventApiVersionName, - schema - ); - - if (!validateResult.valid) - throw new EpAsyncApiValidationError( - logName, - this.constructor.name, - undefined, - { - asyncApiSpecTitle: this.getTitle(), - issues: validateResult.errors, - value: { - epEventApiVersionName: this.epEventApiVersionName, - }, - } - ); + const validateResult: ValidatorResult = v.validate(eventApiVersionName, schema); + if (!validateResult.valid) throw new EpAsyncApiValidationError(logName,this.constructor.name,undefined,{ + asyncApiSpecTitle: this.getTitle(), + issues: validateResult.errors, + value: { + epEventApiVersionName: this.epEventApiVersionName, + }, + }); }; private validate_VersionIsSemVerFormat(): void { @@ -357,8 +326,8 @@ export class EpAsyncApiDocument { public validate(): void { // this doc this.validate_VersionIsSemVerFormat(); - this.validate_EpEventApiName(); - this.validate_EpEventApiVersionName(); + this.validateEpEventApiName(); + this.validateEpEventApiVersionName(); this.validate_BrokerType(); this.validate_ChannelDelimiter(); // cascade validation to all elements @@ -425,54 +394,23 @@ export class EpAsyncApiDocument { public getChannelDelimiter(): EChannelDelimiters { return this.channelDelimiter; } - public getEpEventApiName(): string { - const funcName = "getEpEventApiName"; - const logName = `${EpAsyncApiDocument.name}.${funcName}()`; - if (this.epEventApiName === undefined) { - this.createEpEventApiName(); - this.validate_EpEventApiName(); - } - if (this.epEventApiName === undefined) - throw new EpAsyncApiInternalError( - logName, - this.constructor.name, - "this.epEventApiName === undefined" - ); - return this.epEventApiName; - } + public getEpEventApiName(): string { return this.epEventApiName; } public getEpEventApiVersionName(): string { - const funcName = "getEpEventApiVersionName"; - const logName = `${EpAsyncApiDocument.name}.${funcName}()`; - if (this.epEventApiVersionName === undefined) { - this.createEpEventApiVersionName(); - this.validate_EpEventApiVersionName(); - } - if (this.epEventApiVersionName === undefined) - throw new EpAsyncApiInternalError( - logName, - this.constructor.name, - "this.epEventApiVersionName === undefined" - ); + if(this.epEventApiVersionName === undefined) return ''; return this.epEventApiVersionName; } - public getAsJson(): any { - return this.asyncApiDocumentJson; - } + public getAsJson(): any { return this.asyncApiDocumentJson; } public getAsYamlString(): string { const json = this.getAsJson(); return yaml.dump(json); } - public getOriginalSpecAsJson(): any { - return this.originalApiSpecJson; - } + public getOriginalSpecAsJson(): any { return this.originalApiSpecJson; } - public getOriginalSpecAsYamlString(): string { - return yaml.dump(this.originalApiSpecJson); - } + public getOriginalSpecAsYamlString(): string { return yaml.dump(this.originalApiSpecJson); } public getEpAsyncApiEventNames(): T_EpAsyncApiEventNames { const epAsyncApiEventNames: T_EpAsyncApiEventNames = { @@ -509,38 +447,25 @@ export class EpAsyncApiDocument { public getEpAsyncApiChannelDocumentMap(): T_EpAsyncApiChannelDocumentMap { const channels: Record = this.asyncApiDocument.channels(); - - const epAsyncApiChannelDocumentMap: T_EpAsyncApiChannelDocumentMap = - new Map(); + const epAsyncApiChannelDocumentMap: T_EpAsyncApiChannelDocumentMap = new Map(); for (const [key, channel] of Object.entries(channels)) { - const epAsyncApiChannelDocument = new EpAsyncApiChannelDocument( - this, - key, - channel - ); + const epAsyncApiChannelDocument = new EpAsyncApiChannelDocument(this, key, channel); epAsyncApiChannelDocumentMap.set(key, epAsyncApiChannelDocument); } return epAsyncApiChannelDocumentMap; } public getEpAsyncApiMessageDocumentMap(): T_EpAsyncApiMessageDocumentMap { - // const funcName = 'getMessageDocuments'; - // const logName = `${CliAsyncApiDocument.name}.${funcName}()`; - - const allMessages: Map = - this.asyncApiDocument.allMessages(); - - const epAsyncApiMessageDocumentMap: T_EpAsyncApiMessageDocumentMap = - new Map(); - - for (const [key, message] of allMessages) { - const epAsyncApiMessageDocument = new EpAsyncApiMessageDocument( - this, - undefined, - key, - message - ); - epAsyncApiMessageDocumentMap.set(key, epAsyncApiMessageDocument); + const epAsyncApiMessageDocumentMap: T_EpAsyncApiMessageDocumentMap = new Map(); + const topicChannelDocumentMap: Map = this.getEpAsyncApiChannelDocumentMap(); + for(const [_topic, channelDocument] of topicChannelDocumentMap) { + const operationMessageDocumentMap: Map = channelDocument.getAllChannelMessageDocuments(); + for(const [_operation, messageDocuments] of operationMessageDocumentMap) { + for(const messageDocument of messageDocuments) { + epAsyncApiMessageDocumentMap.set(messageDocument.getMessageName(), messageDocument); + } + + } } return epAsyncApiMessageDocumentMap; } diff --git a/packages/ep-asyncapi/src/documents/EpAsyncApiMessageDocument.ts b/packages/ep-asyncapi/src/documents/EpAsyncApiMessageDocument.ts index 635542e9b..b189308c3 100644 --- a/packages/ep-asyncapi/src/documents/EpAsyncApiMessageDocument.ts +++ b/packages/ep-asyncapi/src/documents/EpAsyncApiMessageDocument.ts @@ -2,7 +2,10 @@ import { Message, Schema } from '@asyncapi/parser'; -import { EpAsyncApiSchemaExtensions } from '../constants'; +import { + EpMessageExtensions, + EpSchemaExtensions +} from '../constants'; import { EpAsyncApiUtils, EpAsyncApiMessageError, @@ -23,9 +26,9 @@ export enum E_EpAsyncApiSchemaFormatType { export class EpAsyncApiMessageDocument { private epAsyncApiDocument: EpAsyncApiDocument; - private epAsyncApiChannelDocument: EpAsyncApiChannelDocument | undefined; - private asyncApiMessageKey: string; + private epAsyncApiChannelDocument: EpAsyncApiChannelDocument; private asyncApiMessage: Message; + private asyncApiMessageKey: string; private contentType: E_EpAsyncApiContentTypes; private schemaFormatType: E_EpAsyncApiSchemaFormatType; public static readonly ContentTypeIssue = 'contentType === undefined, neither message has a contentType nor api has a defaultContentType'; @@ -77,6 +80,11 @@ export class EpAsyncApiMessageDocument { private extractMessageKey(asyncApiMessage: Message): string { const funcName = 'extractMessageKey'; const logName = `${EpAsyncApiMessageDocument.name}.${funcName}()`; + // try ep extension first + if(asyncApiMessage.hasExtension(EpMessageExtensions.xEpEventName)) { + const eventName = asyncApiMessage.extension(EpMessageExtensions.xEpEventName); + if(eventName && eventName.length > 0) return eventName; + } // 2.4.0 if(asyncApiMessage.name()) return asyncApiMessage.name(); // 2.0.0 @@ -90,11 +98,11 @@ export class EpAsyncApiMessageDocument { }); } - constructor(epAsyncApiDocument: EpAsyncApiDocument, epAsyncApiChannelDocument: EpAsyncApiChannelDocument | undefined, asyncApiMessageKey: string | undefined, asyncApiMessage: Message) { + constructor(epAsyncApiDocument: EpAsyncApiDocument, epAsyncApiChannelDocument: EpAsyncApiChannelDocument, asyncApiMessage: Message) { this.epAsyncApiDocument = epAsyncApiDocument; this.epAsyncApiChannelDocument = epAsyncApiChannelDocument; - this.asyncApiMessageKey = asyncApiMessageKey ? asyncApiMessageKey : this.extractMessageKey(asyncApiMessage); this.asyncApiMessage = asyncApiMessage; + this.asyncApiMessageKey = this.extractMessageKey(asyncApiMessage); this.contentType = this.determineContentType(); this.schemaFormatType = this.determineSchemaFormatType(); } @@ -111,23 +119,13 @@ export class EpAsyncApiMessageDocument { asyncApiSpecTitle: this.epAsyncApiDocument.getTitle(), issues: EpAsyncApiMessageDocument.MissingMessagePayloadSchemaIssue, value: { - channel: this.epAsyncApiChannelDocument.getAsyncApiChannelKey(), + channel: this.asyncApiMessageKey, message: this.asyncApiMessageKey } }); } } - public getMessageName(): string { - // const funcName = 'getMessageName'; - // const logName = `${EpAsyncApiMessageDocument.name}.${funcName}()`; - // Note: message name must NOT contain slashes '/', otherwise exported async api channel will reference a message which will NOT be found. - //eslint-disable-next-line - let name: string = this.asyncApiMessageKey.replaceAll(/[^0-9a-zA-Z\._]+/g, '-'); - if(this.asyncApiMessage.name() !== undefined) name = this.asyncApiMessage.name(); - return name; - } - public getContentType(): E_EpAsyncApiContentTypes { return this.contentType; } public getSchemaFormatType(): E_EpAsyncApiSchemaFormatType { return this.schemaFormatType; } @@ -141,11 +139,22 @@ export class EpAsyncApiMessageDocument { return JSON.stringify(schema.json()); } - public getDescription(): string | undefined { + public getMessageName(): string { return this.asyncApiMessageKey; } + + public getMessageDisplayName(): string { + if(this.asyncApiMessage.hasExtension(EpMessageExtensions.xEpEventVersionDisplayName)) { + const displayName = this.asyncApiMessage.extension(EpMessageExtensions.xEpEventVersionDisplayName); + if(displayName && displayName.length > 0) return displayName; + } + return ''; + } + + public getMessageDescription(): string { const description: string | null = this.asyncApiMessage.description(); const summary: string | null = this.asyncApiMessage.summary(); - if(description) return description; - if(summary) return summary; + if(description && description.length > 0) return description; + if(summary && summary.length > 0) return summary; + return ''; } public getMessageNameAsFilePath(): string { @@ -160,30 +169,31 @@ export class EpAsyncApiMessageDocument { if(title && title !== '') return title; throw new Error('no title found'); } catch(e) { - if(schema.hasExtension(EpAsyncApiSchemaExtensions.xEpSchemaName)) { - return schema.extension(EpAsyncApiSchemaExtensions.xEpSchemaName); + if(schema.hasExtension(EpSchemaExtensions.xEpSchemaName)) { + return schema.extension(EpSchemaExtensions.xEpSchemaName); } return this.getMessageName(); } } - public getPayloadSchemaDisplayName(): string | undefined { + public getPayloadSchemaDisplayName(): string { const schema: Schema = this.asyncApiMessage.payload(); - if(!schema) return undefined; - if(schema.hasExtension(EpAsyncApiSchemaExtensions.xEpSchemaVersionDisplayName)) { - return schema.extension(EpAsyncApiSchemaExtensions.xEpSchemaVersionDisplayName); + if(!schema) return ''; + if(schema.hasExtension(EpSchemaExtensions.xEpSchemaVersionDisplayName)) { + return schema.extension(EpSchemaExtensions.xEpSchemaVersionDisplayName); } + return ''; } - public getPayloadSchemaDescription(): string | undefined { + public getPayloadSchemaDescription(): string { const schema: Schema = this.asyncApiMessage.payload(); try { const descr = schema.description(); - if(descr === "") return undefined; - return descr; + if(descr && descr.length > 0) return descr; } catch(e) { - return undefined; + // no op } + return ''; } public getSchemaFileName(): string { @@ -208,10 +218,12 @@ export class EpAsyncApiMessageDocument { // should never get here return undefined; } + public getSchemaAsSanitizedJson(): any { const anySchema: any = this.getPayloadSchema(); const sanitized = JSON.parse(JSON.stringify(anySchema, (k,v) => { if(k.startsWith("x-parser")) return undefined; + if(k.startsWith("x-ep")) return undefined; return v; })); return sanitized; diff --git a/packages/ep-asyncapi/test/data/ep-downloads/EventApi-Name.json b/packages/ep-asyncapi/test/data/ep-downloads/EventApi-Name.json index 4fafc4332..4170e7e6d 100644 --- a/packages/ep-asyncapi/test/data/ep-downloads/EventApi-Name.json +++ b/packages/ep-asyncapi/test/data/ep-downloads/EventApi-Name.json @@ -6,7 +6,7 @@ "x-ep-schema-state-id": "2", "x-ep-schema-version-id": "n00r9bespvj", "x-ep-schema-id": "bx9070aj3mu", - "description": "Generic message header.", + "description": "Schema_2_Name description", "x-ep-schema-state-name": "RELEASED", "x-ep-schema-name": "Schema_2_Name", "type": "object", @@ -26,14 +26,14 @@ } }, "required": ["sentAt", "transactionId", "storeId"], - "x-ep-schema-version-displayname": "Schema_2_Id" + "x-ep-schema-version-displayname": "Schema_2_Version_Name" }, "Schema_1_Name": { "x-ep-schema-version": "1.0.0", "x-ep-schema-state-id": "2", "x-ep-schema-version-id": "loyscnlazj5", "x-ep-schema-id": "5e95l0jqxlt", - "description": "Generic message header.", + "description": "Schema_1_Name description", "x-ep-schema-state-name": "RELEASED", "x-ep-schema-name": "Schema_1_Name", "type": "object", @@ -53,20 +53,20 @@ } }, "required": ["sentAt", "transactionId", "storeId"], - "x-ep-schema-version-displayname": "Schema_1_Id" + "x-ep-schema-version-displayname": "Schema_1_Version_Name" } }, "messages": { "Event_2_Name": { "x-ep-event-id": "oumr2wycciv", - "x-ep-event-version-displayname": "Event_2_Id", + "x-ep-event-version-displayname": "Event_2_Version_Name", "x-ep-event-version-id": "ifg6vpksml9", "payload": { "$ref": "#/components/schemas/Schema_2_Name" }, "x-ep-event-version": "1.0.0", "x-ep-event-name": "Event_2_Name", - "description": "Event_2_Id", + "description": "Event_2_Name description", "schemaFormat": "application/vnd.aai.asyncapi+json;version=2.0.0", "contentType": "application/json", "x-ep-event-state-id": "2", @@ -74,14 +74,14 @@ }, "Event_1_Name": { "x-ep-event-id": "7jhc9d369ob", - "x-ep-event-version-displayname": "Event_1_Id", + "x-ep-event-version-displayname": "Event_1_Version_Name", "x-ep-event-version-id": "mvi0eewza58", "payload": { "$ref": "#/components/schemas/Schema_1_Name" }, "x-ep-event-version": "1.0.0", "x-ep-event-name": "Event_1_Name", - "description": "Event_1_Id", + "description": "Event_1_Name description", "schemaFormat": "application/vnd.aai.asyncapi+json;version=2.0.0", "contentType": "application/json", "x-ep-event-state-id": "2", diff --git a/packages/ep-asyncapi/test/data/test-fail/very-long-event-name.spec.yml b/packages/ep-asyncapi/test/data/test-fail/very-long-event-name.spec.yml index 3dfa74a95..d95f2c85e 100644 --- a/packages/ep-asyncapi/test/data/test-fail/very-long-event-name.spec.yml +++ b/packages/ep-asyncapi/test/data/test-fail/very-long-event-name.spec.yml @@ -5,13 +5,13 @@ info: version: '1.2.0' defaultContentType: application/json channels: - ep-asyncapi/test/very-long-event-name/very/very/very/very/very/very/very/very/very/very/very/very/very/very/very/very/very/veryvery/very/very/very/very/very/very/very/very/very/very/very/very/very/very/very/very/very/very/very/very/very/very/very/very/very/very/very/very/very/very/very/very/very/very/long: + ep-asyncapi/test: publish: message: - $ref: '#/components/messages/message-1' + $ref: '#/components/messages/very-long-message-name-very-long-message-name-very-long-message-name-very-long-message-name-very-long-message-name-very-long-message-name' components: messages: - message-1: + very-long-message-name-very-long-message-name-very-long-message-name-very-long-message-name-very-long-message-name-very-long-message-name: payload: type: string diff --git a/packages/ep-asyncapi/test/data/test-pass/kafka/Confluent.json b/packages/ep-asyncapi/test/data/test-pass/kafka/Confluent.json index 112e574d1..65f95c250 100644 --- a/packages/ep-asyncapi/test/data/test-pass/kafka/Confluent.json +++ b/packages/ep-asyncapi/test/data/test-pass/kafka/Confluent.json @@ -1,87 +1,76 @@ { - "components": { - "schemas": {}, - "messages": { - "samples.clickstream.avro.ClickEvent-1ddlngjbz4z": { - "payload": { - "name": "ClickEvent", - "namespace": "samples.clickstream.avro", - "type": "record", - "fields": [ - { - "name": "ip", - "type": "string" - }, - { - "name": "eventtimestamp", - "type": "long" - }, - { - "name": "devicetype", - "type": "string" - }, - { - "name": "event_type", - "type": [ - "string", - "null" - ] - }, - { - "name": "product_type", - "type": [ - "string", - "null" - ] - }, - { - "name": "userid", - "type": "int" - }, - { - "name": "globalseq", - "type": "long" - }, - { - "default": 0, - "name": "prevglobalseq", - "type": "long" - } - ] - }, - "name": "samples.clickstream.avro.ClickEvent-1ddlngjbz4z", - "contentType": "application/json", - "schemaFormat": "application/vnd.apache.avro;version=1.9.0" + "components": { + "schemas": {}, + "messages": { + "samples.clickstream.avro.ClickEvent-1ddlngjbz4z": { + "payload": { + "name": "ClickEvent", + "namespace": "samples.clickstream.avro", + "type": "record", + "fields": [ + { + "name": "ip", + "type": "string" }, - "1ddlngjbz4p": { - "payload": { - "type": "string" - }, - "name": "1ddlngjbz4p", - "contentType": "application/json", - "schemaFormat": "application/vnd.apache.avro;version=1.9.0" - } - } - }, - "channels": { - "User_Sessions_Aggregates_With_Order_Checkout": {}, - "ClickEvents_UserId_Agg_Result": {}, - "__amazon_msk_canary": {}, - "_schemas": {}, - "Departments_Agg": {}, - "ExampleTopic": { - "publish": { - "message": { - "$ref": "#/components/messages/samples.clickstream.avro.ClickEvent-1ddlngjbz4z" - } + { + "name": "eventtimestamp", + "type": "long" + }, + { + "name": "devicetype", + "type": "string" + }, + { + "name": "event_type", + "type": ["string", "null"] + }, + { + "name": "product_type", + "type": ["string", "null"] + }, + { + "name": "userid", + "type": "int" + }, + { + "name": "globalseq", + "type": "long" + }, + { + "default": 0, + "name": "prevglobalseq", + "type": "long" } + ] + }, + "name": "samples.clickstream.avro.ClickEvent-1ddlngjbz4z", + "contentType": "application/json", + "schemaFormat": "application/vnd.apache.avro;version=1.9.0" + }, + "1ddlngjbz4p": { + "payload": { + "type": "string" + }, + "name": "1ddlngjbz4p", + "contentType": "application/json", + "schemaFormat": "application/vnd.apache.avro;version=1.9.0" + } + } + }, + "channels": { + "ExampleTopic": { + "publish": { + "message": { + "$ref": "#/components/messages/samples.clickstream.avro.ClickEvent-1ddlngjbz4z" } - }, - "asyncapi": "2.2.0", - "x-ep-application-domain-name": "Discovery", - "info": { - "description": "Discovery Agent Scan", - "title": "Confluent16-1", - "version": "0.1.0" + } } -} \ No newline at end of file + }, + "asyncapi": "2.2.0", + "x-ep-application-domain-name": "Discovery", + "info": { + "description": "Discovery Agent Scan", + "title": "Confluent16-1", + "version": "0.1.0" + } +} diff --git a/packages/ep-asyncapi/test/specs/test-pass/ep-downloads.spec.ts b/packages/ep-asyncapi/test/specs/test-pass/ep-downloads.spec.ts index 4ba3b69ae..9ac015676 100644 --- a/packages/ep-asyncapi/test/specs/test-pass/ep-downloads.spec.ts +++ b/packages/ep-asyncapi/test/specs/test-pass/ep-downloads.spec.ts @@ -21,8 +21,23 @@ TestLogger.logMessage(scriptName, ">>> starting ..."); let AsyncApiSpecFile: string; -const expectedApplicationDomainName = "TEST_EP_ASYNC_API_IMPORTER/multi-domain.x-spec.ts/ApplicationDomain_Main_Name"; +const ExpectedApplicationDomainName = "TEST_EP_ASYNC_API_IMPORTER/multi-domain.x-spec.ts/ApplicationDomain_Main_Name"; +const ExpectedTopic1 = "topic/{Enum_1_Name}/_1_"; +const ExpectedEventName1 = "Event_1_Name"; +const ExpectedEventVersionName1 = "Event_1_Version_Name"; +const ExpectedEventDescription1 = "Event_1_Name description"; +const ExpectedSchemaName1 = "Schema_1_Name"; +const ExpectedSchemaDisplayName1 = "Schema_1_Version_Name"; +const ExpectedSchemaDescription1 = "Schema_1_Name description"; + +const ExpectedTopic2 = "topic/{Enum_2_Name}/_2_"; +const ExpectedEventName2 = "Event_2_Name"; +const ExpectedEventVersionName2 = "Event_2_Version_Name"; +const ExpectedEventDescription2 = "Event_2_Name description"; +const ExpectedSchemaName2 = "Schema_2_Name"; +const ExpectedSchemaDisplayName2 = "Schema_2_Version_Name"; +const ExpectedSchemaDescription2 = "Schema_2_Name description"; describe(`${scriptName}`, () => { @@ -45,13 +60,44 @@ describe(`${scriptName}`, () => { const epAsyncApiDocument: EpAsyncApiDocument = await EpAsyncApiDocumentService.createFromFile({ filePath: AsyncApiSpecFile, }); + epAsyncApiDocument.validate(); + epAsyncApiDocument.validate_BestPractices(); const appDomainName = epAsyncApiDocument.getApplicationDomainName(); - expect(appDomainName, 'failed').to.eq(expectedApplicationDomainName); + expect(appDomainName, 'failed').to.eq(ExpectedApplicationDomainName); // walk the document const epAsyncApiChannelDocumentMap: T_EpAsyncApiChannelDocumentMap = epAsyncApiDocument.getEpAsyncApiChannelDocumentMap(); for(const [topic, epAsyncApiChannelDocument] of epAsyncApiChannelDocumentMap) { const epEventName = epAsyncApiChannelDocument.getEpEventName(); const epEventVersionName = epAsyncApiChannelDocument.getEpEventVersionName(); + const epEventDescription = epAsyncApiChannelDocument.getEpEventDescription(); + let epSchemaName: string | undefined = undefined; + let epSchemaDisplayName: string | undefined = undefined; + let epSchemaDescription: string | undefined = undefined; + if(epAsyncApiChannelDocument.getEpAsyncApiChannelPublishOperation()) { + epSchemaName = epAsyncApiChannelDocument.getEpAsyncApiChannelPublishOperation().getEpAsyncApiMessageDocument().getPayloadSchemaName(); + epSchemaDisplayName = epAsyncApiChannelDocument.getEpAsyncApiChannelPublishOperation().getEpAsyncApiMessageDocument().getPayloadSchemaDisplayName(); + epSchemaDescription = epAsyncApiChannelDocument.getEpAsyncApiChannelPublishOperation().getEpAsyncApiMessageDocument().getPayloadSchemaDescription(); + } else if(epAsyncApiChannelDocument.getEpAsyncApiChannelSubscribeOperation()) { + epSchemaName = epAsyncApiChannelDocument.getEpAsyncApiChannelSubscribeOperation().getEpAsyncApiMessageDocument().getPayloadSchemaName(); + epSchemaDisplayName = epAsyncApiChannelDocument.getEpAsyncApiChannelSubscribeOperation().getEpAsyncApiMessageDocument().getPayloadSchemaDisplayName(); + epSchemaDescription = epAsyncApiChannelDocument.getEpAsyncApiChannelSubscribeOperation().getEpAsyncApiMessageDocument().getPayloadSchemaDescription(); + } + if(topic === ExpectedTopic1) { + expect(epEventName, 'wrong event name').to.equal(ExpectedEventName1); + expect(epEventVersionName, 'wrong event version name').to.equal(ExpectedEventVersionName1); + expect(epEventDescription, 'wrong event descrption').to.equal(ExpectedEventDescription1); + expect(epSchemaName, 'wrong schema name').to.equal(ExpectedSchemaName1); + expect(epSchemaDisplayName, 'wrong schema display name').to.equal(ExpectedSchemaDisplayName1); + expect(epSchemaDescription, 'wrong schema description').to.equal(ExpectedSchemaDescription1); + } else if (topic === ExpectedTopic2) { + expect(epEventName, 'wrong event name').to.equal(ExpectedEventName2); + expect(epEventVersionName, 'wrong event version name').to.equal(ExpectedEventVersionName2); + expect(epEventDescription, 'wrong event descrption').to.equal(ExpectedEventDescription2); + expect(epSchemaName, 'wrong schema name').to.equal(ExpectedSchemaName2); + expect(epSchemaDisplayName, 'wrong schema display name').to.equal(ExpectedSchemaDisplayName2); + expect(epSchemaDescription, 'wrong schema description').to.equal(ExpectedSchemaDescription2); + } else expect(topic, 'unknonw topic').to.be.false; + const epAsyncApiChannelParameterDocumentMap = epAsyncApiChannelDocument.getEpAsyncApiChannelParameterDocumentMap(); for(const [parameter, epAsyncApiChannelParameterDocument] of epAsyncApiChannelParameterDocumentMap) { const parameterDisplayName = epAsyncApiChannelParameterDocument.getDisplayName(); @@ -60,9 +106,13 @@ describe(`${scriptName}`, () => { topic, epEventName, epEventVersionName, + epEventDescription, parameter, parameterDisplayName, - parameterDescription + parameterDescription, + epSchemaName, + epSchemaDisplayName, + epSchemaDescription } console.log(`debug = ${JSON.stringify(debug, null, 2)}`); } diff --git a/packages/ep-asyncapi/tsconfig.json b/packages/ep-asyncapi/tsconfig.json index 41303f009..721490600 100644 --- a/packages/ep-asyncapi/tsconfig.json +++ b/packages/ep-asyncapi/tsconfig.json @@ -10,7 +10,7 @@ "moduleResolution": "node", "emitDecoratorMetadata": false, "experimentalDecorators": false, - "strict": false, + "strict": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, "strictPropertyInitialization": false diff --git a/packages/ep-sdk/src/tasks/EpSdkApplicationVersionTask.ts b/packages/ep-sdk/src/tasks/EpSdkApplicationVersionTask.ts index 89246dd79..44a73cc81 100644 --- a/packages/ep-sdk/src/tasks/EpSdkApplicationVersionTask.ts +++ b/packages/ep-sdk/src/tasks/EpSdkApplicationVersionTask.ts @@ -214,65 +214,36 @@ export class EpSdkApplicationVersionTask extends EpSdkVersionTask { return epSdkApplicationVersionTask_GetFuncReturn; } - protected async isUpdateRequiredFunc( - epSdkApplicationVersionTask_GetFuncReturn: IEpSdkApplicationVersionTask_GetFuncReturn - ): Promise { + protected async isUpdateRequiredFunc(epSdkApplicationVersionTask_GetFuncReturn: IEpSdkApplicationVersionTask_GetFuncReturn): Promise { const funcName = "isUpdateRequired"; const logName = `${EpSdkApplicationVersionTask.name}.${funcName}()`; - EpSdkLogger.trace( - EpSdkLogger.createLogEntry(logName, { - code: EEpSdkLoggerCodes.TASK_EXECUTE_START_IS_UPDATE_REQUIRED, - module: this.constructor.name, - details: { - epSdkApplicationVersionTask_GetFuncReturn: - epSdkApplicationVersionTask_GetFuncReturn, - }, - }) - ); + EpSdkLogger.trace(EpSdkLogger.createLogEntry(logName, {code: EEpSdkLoggerCodes.TASK_EXECUTE_START_IS_UPDATE_REQUIRED,module: this.constructor.name,details: { + epSdkApplicationVersionTask_GetFuncReturn: epSdkApplicationVersionTask_GetFuncReturn, + }})); - if (epSdkApplicationVersionTask_GetFuncReturn.epObject === undefined) - throw new EpSdkInternalTaskError( - logName, - this.constructor.name, - "epSdkApplicationVersionTask_GetFuncReturn.epObject === undefined" - ); + if (epSdkApplicationVersionTask_GetFuncReturn.epObject === undefined) throw new EpSdkInternalTaskError(logName,this.constructor.name,"epSdkApplicationVersionTask_GetFuncReturn.epObject === undefined"); /* istanbul ignore next */ - if ( - epSdkApplicationVersionTask_GetFuncReturn.epObject.version === undefined - ) - throw new EpSdkApiContentError( - logName, - this.constructor.name, - "epSdkApplicationVersionTask_GetFuncReturn.epObject.version === undefined", - { - epObject: epSdkApplicationVersionTask_GetFuncReturn.epObject, - } - ); - const existingObject: ApplicationVersion = - epSdkApplicationVersionTask_GetFuncReturn.epObject; + if (epSdkApplicationVersionTask_GetFuncReturn.epObject.version === undefined) throw new EpSdkApiContentError(logName,this.constructor.name,"epSdkApplicationVersionTask_GetFuncReturn.epObject.version === undefined",{ + epObject: epSdkApplicationVersionTask_GetFuncReturn.epObject, + }); + const existingObject: ApplicationVersion = epSdkApplicationVersionTask_GetFuncReturn.epObject; const existingCompareObject: TEpSdkApplicationVersionTask_CompareObject = { - description: existingObject.description, - displayName: existingObject.displayName, + description: existingObject.description ? existingObject.description : '', + displayName: existingObject.displayName ? existingObject.displayName : '', stateId: existingObject.stateId, - declaredConsumedEventVersionIds: - existingObject.declaredConsumedEventVersionIds, - declaredProducedEventVersionIds: - existingObject.declaredProducedEventVersionIds, + declaredConsumedEventVersionIds: existingObject.declaredConsumedEventVersionIds, + declaredProducedEventVersionIds: existingObject.declaredProducedEventVersionIds, }; - const requestedCompareObject: TEpSdkApplicationVersionTask_CompareObject = - this.createObjectSettings(); + const requestedCompareObject: TEpSdkApplicationVersionTask_CompareObject = this.createObjectSettings(); if (this.versionStrategy === EEpSdk_VersionTaskStrategy.EXACT_VERSION) { - existingCompareObject.version = - epSdkApplicationVersionTask_GetFuncReturn.epObject.version; + existingCompareObject.version = epSdkApplicationVersionTask_GetFuncReturn.epObject.version; requestedCompareObject.version = this.versionString; } - - const epSdkTask_IsUpdateRequiredFuncReturn: IEpSdkTask_IsUpdateRequiredFuncReturn = - this.create_IEpSdkTask_IsUpdateRequiredFuncReturn({ - existingObject: existingCompareObject, - requestedObject: requestedCompareObject, - }); + const epSdkTask_IsUpdateRequiredFuncReturn: IEpSdkTask_IsUpdateRequiredFuncReturn = this.create_IEpSdkTask_IsUpdateRequiredFuncReturn({ + existingObject: existingCompareObject, + requestedObject: requestedCompareObject, + }); // // DEBUG: // if(epSdkTask_IsUpdateRequiredFuncReturn.isUpdateRequired) { // EpSdkLogger.debug(EpSdkLogger.createLogEntry(logName, { code: EEpSdkLoggerCodes.TASK_EXECUTE_DONE_IS_UPDATE_REQUIRED, module: this.constructor.name, details: { diff --git a/packages/ep-sdk/src/tasks/EpSdkEnumVersionTask.ts b/packages/ep-sdk/src/tasks/EpSdkEnumVersionTask.ts index 42dcd89ce..2815a6048 100644 --- a/packages/ep-sdk/src/tasks/EpSdkEnumVersionTask.ts +++ b/packages/ep-sdk/src/tasks/EpSdkEnumVersionTask.ts @@ -66,16 +66,12 @@ export interface IEpSdkEnumVersionTask_ExecuteReturn /** @category Tasks */ export class EpSdkEnumVersionTask extends EpSdkVersionTask { - private readonly Empty_IEpSdkEnumVersionTask_GetFuncReturn: IEpSdkEnumVersionTask_GetFuncReturn = - { - epObjectKeys: this.getDefaultEpObjectKeys(), - epObject: undefined, - epObjectExists: false, - }; - private readonly Default_TEpSdkEnumVersionTask_Settings: Partial = - { - // description: `Created by ${EpSdkConfig.getAppName()}.`, - }; + private readonly Empty_IEpSdkEnumVersionTask_GetFuncReturn: IEpSdkEnumVersionTask_GetFuncReturn = { + epObjectKeys: this.getDefaultEpObjectKeys(), + epObject: undefined, + epObjectExists: false, + }; + private readonly Default_TEpSdkEnumVersionTask_Settings: Partial = {}; private getTaskConfig(): IEpSdkEnumVersionTask_Config { return this.epSdkTask_Config as IEpSdkEnumVersionTask_Config; } @@ -128,23 +124,13 @@ export class EpSdkEnumVersionTask extends EpSdkVersionTask { if (epObject === undefined) return this.getDefaultEpObjectKeys(); /* istanbul ignore next */ - if (epObject.id === undefined) throw new EpSdkApiContentError(logName, - this.constructor.name, - "epObject.id === undefined", - { - epObject: epObject, - } - ); + if (epObject.id === undefined) throw new EpSdkApiContentError(logName, this.constructor.name, "epObject.id === undefined", { + epObject: epObject, + }); /* istanbul ignore next */ - if (epObject.enumId === undefined) - throw new EpSdkApiContentError( - logName, - this.constructor.name, - "epObject.enumId === undefined", - { - epObject: epObject, - } - ); + if (epObject.enumId === undefined) throw new EpSdkApiContentError(logName,this.constructor.name,"epObject.enumId === undefined",{ + epObject: epObject, + }); return { ...this.getDefaultEpObjectKeys(), epObjectId: epObject.enumId, @@ -211,18 +197,15 @@ export class EpSdkEnumVersionTask extends EpSdkVersionTask { EpSdkLogger.trace(EpSdkLogger.createLogEntry(logName, { code: EEpSdkLoggerCodes.TASK_EXECUTE_START_IS_UPDATE_REQUIRED, module: this.constructor.name, details: { epSdkEnumVersionTask_GetFuncReturn: epSdkEnumVersionTask_GetFuncReturn, }})); - - if (epSdkEnumVersionTask_GetFuncReturn.epObject === undefined) throw new EpSdkInternalTaskError(logName, this.constructor.name, - "epSdkEnumVersionTask_GetFuncReturn.epObject === undefined" - ); + if (epSdkEnumVersionTask_GetFuncReturn.epObject === undefined) throw new EpSdkInternalTaskError(logName, this.constructor.name,"epSdkEnumVersionTask_GetFuncReturn.epObject === undefined"); /* istanbul ignore next */ if (epSdkEnumVersionTask_GetFuncReturn.epObject.version === undefined) throw new EpSdkApiContentError(logName, this.constructor.name, "epSdkEnumVersionTask_GetFuncReturn.epObject.version === undefined", { epObject: epSdkEnumVersionTask_GetFuncReturn.epObject, }); const existingObject: TopicAddressEnumVersion = epSdkEnumVersionTask_GetFuncReturn.epObject; const existingCompareObject: TEpSdkEnumVersionTask_CompareObject = { - description: existingObject.description ? existingObject.description : undefined, - displayName: existingObject.displayName, + description: existingObject.description ? existingObject.description : '', + displayName: existingObject.displayName ? existingObject.displayName: '', stateId: existingObject.stateId, values: this.createCompareEnumValueList_From_EP({ epEnumValueList: existingObject.values }), }; @@ -231,12 +214,10 @@ export class EpSdkEnumVersionTask extends EpSdkVersionTask { existingCompareObject.version = epSdkEnumVersionTask_GetFuncReturn.epObject.version; requestedCompareObject.version = this.versionString; } - - const epSdkTask_IsUpdateRequiredFuncReturn: IEpSdkTask_IsUpdateRequiredFuncReturn = - this.create_IEpSdkTask_IsUpdateRequiredFuncReturn({ - existingObject: existingCompareObject, - requestedObject: requestedCompareObject, - }); + const epSdkTask_IsUpdateRequiredFuncReturn: IEpSdkTask_IsUpdateRequiredFuncReturn = this.create_IEpSdkTask_IsUpdateRequiredFuncReturn({ + existingObject: existingCompareObject, + requestedObject: requestedCompareObject, + }); // // DEBUG: // if(epSdkTask_IsUpdateRequiredFuncReturn.isUpdateRequired) { // EpSdkLogger.debug(EpSdkLogger.createLogEntry(logName, { code: EEpSdkLoggerCodes.TASK_EXECUTE_DONE_IS_UPDATE_REQUIRED, module: this.constructor.name, details: { diff --git a/packages/ep-sdk/src/tasks/EpSdkEpEventVersionTask.ts b/packages/ep-sdk/src/tasks/EpSdkEpEventVersionTask.ts index 63a3b9f2d..6ecd0bb16 100644 --- a/packages/ep-sdk/src/tasks/EpSdkEpEventVersionTask.ts +++ b/packages/ep-sdk/src/tasks/EpSdkEpEventVersionTask.ts @@ -218,21 +218,13 @@ export class EpSdkEpEventVersionTask extends EpSdkVersionTask { /** * Get the latest EventVersion. */ - protected async getFunc( - epSdkEpEventVersionTask_Keys: IEpSdkEpEventVersionTask_Keys - ): Promise { + protected async getFunc(epSdkEpEventVersionTask_Keys: IEpSdkEpEventVersionTask_Keys): Promise { const funcName = "getFunc"; const logName = `${EpSdkEpEventVersionTask.name}.${funcName}()`; - EpSdkLogger.trace( - EpSdkLogger.createLogEntry(logName, { - code: EEpSdkLoggerCodes.TASK_EXECUTE_START_GET, - module: this.constructor.name, - details: { - epSdkEpEventVersionTask_Keys: epSdkEpEventVersionTask_Keys, - }, - }) - ); + EpSdkLogger.trace(EpSdkLogger.createLogEntry(logName, {code: EEpSdkLoggerCodes.TASK_EXECUTE_START_GET,module: this.constructor.name,details: { + epSdkEpEventVersionTask_Keys: epSdkEpEventVersionTask_Keys, + }})); const eventVersion: EventVersion | undefined = await EpSdkEpEventVersionsService.getLatestVersionForEventId({ xContextId: this.xContextId, @@ -240,25 +232,18 @@ export class EpSdkEpEventVersionTask extends EpSdkVersionTask { eventId: epSdkEpEventVersionTask_Keys.eventId, }); - EpSdkLogger.trace( - EpSdkLogger.createLogEntry(logName, { - code: EEpSdkLoggerCodes.TASK_EXECUTE_API_GET, - module: this.constructor.name, - details: { - epSdkEpEventVersionTask_Keys: epSdkEpEventVersionTask_Keys, - eventVersion: eventVersion ? eventVersion : "undefined", - }, - }) - ); + EpSdkLogger.trace(EpSdkLogger.createLogEntry(logName, {code: EEpSdkLoggerCodes.TASK_EXECUTE_API_GET,module: this.constructor.name,details: { + epSdkEpEventVersionTask_Keys: epSdkEpEventVersionTask_Keys, + eventVersion: eventVersion ? eventVersion : "undefined", + }})); if (eventVersion === undefined) return this.Empty_IEpSdkEpEventVersionTask_GetFuncReturn; - const epSdkEpEventVersionTask_GetFuncReturn: IEpSdkEpEventVersionTask_GetFuncReturn = - { - epObjectKeys: this.getEpObjectKeys(eventVersion), - epObject: eventVersion, - epObjectExists: true, - }; + const epSdkEpEventVersionTask_GetFuncReturn: IEpSdkEpEventVersionTask_GetFuncReturn = { + epObjectKeys: this.getEpObjectKeys(eventVersion), + epObject: eventVersion, + epObjectExists: true, + }; return epSdkEpEventVersionTask_GetFuncReturn; } @@ -266,56 +251,33 @@ export class EpSdkEpEventVersionTask extends EpSdkVersionTask { const funcName = "isUpdateRequired"; const logName = `${EpSdkEpEventVersionTask.name}.${funcName}()`; - EpSdkLogger.trace( - EpSdkLogger.createLogEntry(logName, { - code: EEpSdkLoggerCodes.TASK_EXECUTE_START_IS_UPDATE_REQUIRED, - module: this.constructor.name, - details: { - epSdkEpEventVersionTask_GetFuncReturn: - epSdkEpEventVersionTask_GetFuncReturn, - }, - }) - ); + EpSdkLogger.trace(EpSdkLogger.createLogEntry(logName, {code: EEpSdkLoggerCodes.TASK_EXECUTE_START_IS_UPDATE_REQUIRED,module: this.constructor.name,details: { + epSdkEpEventVersionTask_GetFuncReturn: epSdkEpEventVersionTask_GetFuncReturn, + }})); - if (epSdkEpEventVersionTask_GetFuncReturn.epObject === undefined) - throw new EpSdkInternalTaskError( - logName, - this.constructor.name, - "epSdkEpEventVersionTask_GetFuncReturn.epObject === undefined" - ); + if (epSdkEpEventVersionTask_GetFuncReturn.epObject === undefined) throw new EpSdkInternalTaskError(logName,this.constructor.name,"epSdkEpEventVersionTask_GetFuncReturn.epObject === undefined"); /* istanbul ignore next */ - if (epSdkEpEventVersionTask_GetFuncReturn.epObject.version === undefined) - throw new EpSdkApiContentError( - logName, - this.constructor.name, - "epSdkEpEventVersionTask_GetFuncReturn.epObject.version === undefined", - { - epObject: epSdkEpEventVersionTask_GetFuncReturn.epObject, - } - ); + if (epSdkEpEventVersionTask_GetFuncReturn.epObject.version === undefined) throw new EpSdkApiContentError(logName,this.constructor.name,"epSdkEpEventVersionTask_GetFuncReturn.epObject.version === undefined",{ + epObject: epSdkEpEventVersionTask_GetFuncReturn.epObject, + }); - const existingObject: EventVersion = - epSdkEpEventVersionTask_GetFuncReturn.epObject; + const existingObject: EventVersion = epSdkEpEventVersionTask_GetFuncReturn.epObject; const existingCompareObject: TEpSdkEpEventVersionTask_CompareObject = { - description: existingObject.description, - displayName: existingObject.displayName, + description: existingObject.description ? existingObject.description : '', + displayName: existingObject.displayName ? existingObject.displayName : '', stateId: existingObject.stateId, schemaVersionId: existingObject.schemaVersionId, deliveryDescriptor: existingObject.deliveryDescriptor, }; - const requestedCompareObject: TEpSdkEpEventVersionTask_CompareObject = - this.createObjectSettings(); + const requestedCompareObject: TEpSdkEpEventVersionTask_CompareObject = this.createObjectSettings(); if (this.versionStrategy === EEpSdk_VersionTaskStrategy.EXACT_VERSION) { - existingCompareObject.version = - epSdkEpEventVersionTask_GetFuncReturn.epObject.version; + existingCompareObject.version = epSdkEpEventVersionTask_GetFuncReturn.epObject.version; requestedCompareObject.version = this.versionString; } - - const epSdkTask_IsUpdateRequiredFuncReturn: IEpSdkTask_IsUpdateRequiredFuncReturn = - this.create_IEpSdkTask_IsUpdateRequiredFuncReturn({ - existingObject: existingCompareObject, - requestedObject: requestedCompareObject, - }); + const epSdkTask_IsUpdateRequiredFuncReturn: IEpSdkTask_IsUpdateRequiredFuncReturn = this.create_IEpSdkTask_IsUpdateRequiredFuncReturn({ + existingObject: existingCompareObject, + requestedObject: requestedCompareObject, + }); // // DEBUG: // if(epSdkTask_IsUpdateRequiredFuncReturn.isUpdateRequired) { // EpSdkLogger.debug(EpSdkLogger.createLogEntry(logName, { code: EEpSdkLoggerCodes.TASK_EXECUTE_DONE_IS_UPDATE_REQUIRED, module: this.constructor.name, details: { diff --git a/packages/ep-sdk/src/tasks/EpSdkEventApiVersionTask.ts b/packages/ep-sdk/src/tasks/EpSdkEventApiVersionTask.ts index afd770357..a05245145 100644 --- a/packages/ep-sdk/src/tasks/EpSdkEventApiVersionTask.ts +++ b/packages/ep-sdk/src/tasks/EpSdkEventApiVersionTask.ts @@ -37,9 +37,7 @@ export type TEpSdkEventApiVersionTask_Settings = Required< | "consumedEventVersionIds" > >; -type TEpSdkEventApiVersionTask_CompareObject = - Partial & - Pick; +type TEpSdkEventApiVersionTask_CompareObject = Partial & Pick; /** @category Tasks */ export interface IEpSdkEventApiVersionTask_Config @@ -76,16 +74,14 @@ export interface IEpSdkEventApiVersionTask_ExecuteReturn /** @category Tasks */ export class EpSdkEventApiVersionTask extends EpSdkVersionTask { - private readonly Empty_IEpSdkEventApiVersionTask_GetFuncReturn: IEpSdkEventApiVersionTask_GetFuncReturn = - { - epObjectKeys: this.getDefaultEpObjectKeys(), - epObject: undefined, - epObjectExists: false, - }; - private readonly Default_TEpSdkEventApiVersionTask_Settings: Partial = - { - // description: `Created by ${EpSdkConfig.getAppName()}.`, - }; + private readonly Empty_IEpSdkEventApiVersionTask_GetFuncReturn: IEpSdkEventApiVersionTask_GetFuncReturn = { + epObjectKeys: this.getDefaultEpObjectKeys(), + epObject: undefined, + epObjectExists: false, + }; + private readonly Default_TEpSdkEventApiVersionTask_Settings: Partial = { + // no defaults + }; private getTaskConfig(): IEpSdkEventApiVersionTask_Config { return this.epSdkTask_Config as IEpSdkEventApiVersionTask_Config; } @@ -96,14 +92,12 @@ export class EpSdkEventApiVersionTask extends EpSdkVersionTask { }; } - protected transform_EpSdkTask_Config( - epSdkEventApiVersionTask_Config: IEpSdkEventApiVersionTask_Config + protected transform_EpSdkTask_Config(epSdkEventApiVersionTask_Config: IEpSdkEventApiVersionTask_Config ): IEpSdkEventApiVersionTask_Config { - epSdkEventApiVersionTask_Config.eventApiVersionSettings.displayName = - this.truncate( - epSdkEventApiVersionTask_Config.eventApiVersionSettings.displayName, - $EventApiVersion.properties.displayName.maxLength - ); + epSdkEventApiVersionTask_Config.eventApiVersionSettings.displayName = this.truncate( + epSdkEventApiVersionTask_Config.eventApiVersionSettings.displayName, + $EventApiVersion.properties.displayName.maxLength + ); return epSdkEventApiVersionTask_Config; } @@ -119,33 +113,19 @@ export class EpSdkEventApiVersionTask extends EpSdkVersionTask { }; } - protected getEpObjectKeys( - epObject: EventApiVersion | undefined - ): IEpSdkVersionTask_EpObjectKeys { + protected getEpObjectKeys(epObject: EventApiVersion | undefined): IEpSdkVersionTask_EpObjectKeys { const funcName = "getEpObjectKeys"; const logName = `${EpSdkEventApiVersionTask.name}.${funcName}()`; if (epObject === undefined) return this.getDefaultEpObjectKeys(); /* istanbul ignore next */ - if (epObject.id === undefined) - throw new EpSdkApiContentError( - logName, - this.constructor.name, - "epObject.id === undefined", - { - epObject: epObject, - } - ); + if (epObject.id === undefined) throw new EpSdkApiContentError(logName,this.constructor.name,"epObject.id === undefined", { + epObject: epObject, + }); /* istanbul ignore next */ - if (epObject.eventApiId === undefined) - throw new EpSdkApiContentError( - logName, - this.constructor.name, - "epObject.eventApiId === undefined", - { - epObject: epObject, - } - ); + if (epObject.eventApiId === undefined) throw new EpSdkApiContentError(logName,this.constructor.name,"epObject.eventApiId === undefined",{ + epObject: epObject, + }); return { ...this.getDefaultEpObjectKeys(), epObjectId: epObject.eventApiId, @@ -163,21 +143,13 @@ export class EpSdkEventApiVersionTask extends EpSdkVersionTask { /** * Get the latest EventVersion. */ - protected async getFunc( - epSdkEventApiVersionTask_Keys: IEpSdkEventApiVersionTask_Keys - ): Promise { + protected async getFunc(epSdkEventApiVersionTask_Keys: IEpSdkEventApiVersionTask_Keys): Promise { const funcName = "getFunc"; const logName = `${EpSdkEventApiVersionTask.name}.${funcName}()`; - EpSdkLogger.trace( - EpSdkLogger.createLogEntry(logName, { - code: EEpSdkLoggerCodes.TASK_EXECUTE_START_GET, - module: this.constructor.name, - details: { - epSdkEventApiVersionTask_Keys: epSdkEventApiVersionTask_Keys, - }, - }) - ); + EpSdkLogger.trace(EpSdkLogger.createLogEntry(logName, {code: EEpSdkLoggerCodes.TASK_EXECUTE_START_GET,module: this.constructor.name,details: { + epSdkEventApiVersionTask_Keys: epSdkEventApiVersionTask_Keys, + }})); const eventApiVersion: EventApiVersion | undefined = await EpSdkEventApiVersionsService.getLatestVersionForEventApiId({ xContextId: this.xContextId, @@ -185,84 +157,52 @@ export class EpSdkEventApiVersionTask extends EpSdkVersionTask { eventApiId: epSdkEventApiVersionTask_Keys.eventApiId, }); - EpSdkLogger.trace( - EpSdkLogger.createLogEntry(logName, { - code: EEpSdkLoggerCodes.TASK_EXECUTE_API_GET, - module: this.constructor.name, - details: { - epSdkEventApiVersionTask_Keys: epSdkEventApiVersionTask_Keys, - eventApiVersion: eventApiVersion ? eventApiVersion : "undefined", - }, - }) - ); + EpSdkLogger.trace(EpSdkLogger.createLogEntry(logName, {code: EEpSdkLoggerCodes.TASK_EXECUTE_API_GET,module: this.constructor.name,details: { + epSdkEventApiVersionTask_Keys: epSdkEventApiVersionTask_Keys, + eventApiVersion: eventApiVersion ? eventApiVersion : "undefined", + }})); - if (eventApiVersion === undefined) - return this.Empty_IEpSdkEventApiVersionTask_GetFuncReturn; + if (eventApiVersion === undefined) return this.Empty_IEpSdkEventApiVersionTask_GetFuncReturn; - const epSdkEventApiVersionTask_GetFuncReturn: IEpSdkEventApiVersionTask_GetFuncReturn = - { - epObjectKeys: this.getEpObjectKeys(eventApiVersion), - epObject: eventApiVersion, - epObjectExists: true, - }; + const epSdkEventApiVersionTask_GetFuncReturn: IEpSdkEventApiVersionTask_GetFuncReturn = { + epObjectKeys: this.getEpObjectKeys(eventApiVersion), + epObject: eventApiVersion, + epObjectExists: true, + }; return epSdkEventApiVersionTask_GetFuncReturn; } - protected async isUpdateRequiredFunc( - epSdkEventApiVersionTask_GetFuncReturn: IEpSdkEventApiVersionTask_GetFuncReturn - ): Promise { + protected async isUpdateRequiredFunc(epSdkEventApiVersionTask_GetFuncReturn: IEpSdkEventApiVersionTask_GetFuncReturn): Promise { const funcName = "isUpdateRequired"; const logName = `${EpSdkEventApiVersionTask.name}.${funcName}()`; - EpSdkLogger.trace( - EpSdkLogger.createLogEntry(logName, { - code: EEpSdkLoggerCodes.TASK_EXECUTE_START_IS_UPDATE_REQUIRED, - module: this.constructor.name, - details: { - epSdkEventApiVersionTask_GetFuncReturn: - epSdkEventApiVersionTask_GetFuncReturn, - }, - }) - ); + EpSdkLogger.trace(EpSdkLogger.createLogEntry(logName, {code: EEpSdkLoggerCodes.TASK_EXECUTE_START_IS_UPDATE_REQUIRED,module: this.constructor.name,details: { + epSdkEventApiVersionTask_GetFuncReturn: epSdkEventApiVersionTask_GetFuncReturn, + }})); - if (epSdkEventApiVersionTask_GetFuncReturn.epObject === undefined) - throw new EpSdkInternalTaskError( - logName, - this.constructor.name, - "epSdkEventApiVersionTask_GetFuncReturn.epObject === undefined" - ); + if (epSdkEventApiVersionTask_GetFuncReturn.epObject === undefined) throw new EpSdkInternalTaskError(logName,this.constructor.name,"epSdkEventApiVersionTask_GetFuncReturn.epObject === undefined"); /* istanbul ignore next */ - if (epSdkEventApiVersionTask_GetFuncReturn.epObject.version === undefined) - throw new EpSdkApiContentError( - logName, - this.constructor.name, - "epSdkEventApiVersionTask_GetFuncReturn.epObject.version === undefined", - { - epObject: epSdkEventApiVersionTask_GetFuncReturn.epObject, - } - ); + if (epSdkEventApiVersionTask_GetFuncReturn.epObject.version === undefined) throw new EpSdkApiContentError(logName,this.constructor.name,"epSdkEventApiVersionTask_GetFuncReturn.epObject.version === undefined",{ + epObject: epSdkEventApiVersionTask_GetFuncReturn.epObject, + }); - const existingObject: EventApiVersion = - epSdkEventApiVersionTask_GetFuncReturn.epObject; + const existingObject: EventApiVersion = epSdkEventApiVersionTask_GetFuncReturn.epObject; const existingCompareObject: TEpSdkEventApiVersionTask_CompareObject = { - description: existingObject.description, - displayName: existingObject.displayName, + description: existingObject.description ? existingObject.description : '', + displayName: existingObject.displayName ? existingObject.displayName : '', stateId: existingObject.stateId, producedEventVersionIds: existingObject.producedEventVersionIds, consumedEventVersionIds: existingObject.consumedEventVersionIds, }; - const requestedCompareObject: TEpSdkEventApiVersionTask_CompareObject = - this.createObjectSettings(); + const requestedCompareObject: TEpSdkEventApiVersionTask_CompareObject = this.createObjectSettings(); if (this.versionStrategy === EEpSdk_VersionTaskStrategy.EXACT_VERSION) { - existingCompareObject.version = - epSdkEventApiVersionTask_GetFuncReturn.epObject.version; + existingCompareObject.version = epSdkEventApiVersionTask_GetFuncReturn.epObject.version; requestedCompareObject.version = this.versionString; } - const epSdkTask_IsUpdateRequiredFuncReturn: IEpSdkTask_IsUpdateRequiredFuncReturn = - this.create_IEpSdkTask_IsUpdateRequiredFuncReturn({ - existingObject: existingCompareObject, - requestedObject: requestedCompareObject, - }); + const epSdkTask_IsUpdateRequiredFuncReturn: IEpSdkTask_IsUpdateRequiredFuncReturn = this.create_IEpSdkTask_IsUpdateRequiredFuncReturn({ + existingObject: existingCompareObject, + requestedObject: requestedCompareObject, + }); // // DEBUG: // if(epSdkTask_IsUpdateRequiredFuncReturn.isUpdateRequired) { // EpSdkLogger.debug(EpSdkLogger.createLogEntry(logName, { code: EEpSdkLoggerCodes.TASK_EXECUTE_DONE_IS_UPDATE_REQUIRED, module: this.constructor.name, details: { diff --git a/packages/ep-sdk/src/tasks/EpSdkSchemaVersionTask.ts b/packages/ep-sdk/src/tasks/EpSdkSchemaVersionTask.ts index 74a4f94ed..e335182b3 100644 --- a/packages/ep-sdk/src/tasks/EpSdkSchemaVersionTask.ts +++ b/packages/ep-sdk/src/tasks/EpSdkSchemaVersionTask.ts @@ -62,34 +62,38 @@ export interface IEpSdkSchemaVersionTask_ExecuteReturn /** @category Tasks */ export class EpSdkSchemaVersionTask extends EpSdkVersionTask { - private readonly Empty_IEpSdkSchemaVersionTask_GetFuncReturn: IEpSdkSchemaVersionTask_GetFuncReturn = - { - epObjectKeys: this.getDefaultEpObjectKeys(), - epObject: undefined, - epObjectExists: false, - }; - private readonly Default_TEpSdkSchemaVersionTask_Settings: Partial = - { - // description: `Created by ${EpSdkConfig.getAppName()}.`, - }; + private readonly Empty_IEpSdkSchemaVersionTask_GetFuncReturn: IEpSdkSchemaVersionTask_GetFuncReturn = { + epObjectKeys: this.getDefaultEpObjectKeys(), + epObject: undefined, + epObjectExists: false, + }; + private readonly Default_TEpSdkSchemaVersionTask_Settings: Partial = { + // description: `Created by ${EpSdkConfig.getAppName()}.`, + }; private getTaskConfig(): IEpSdkSchemaVersionTask_Config { return this.epSdkTask_Config as IEpSdkSchemaVersionTask_Config; } private createObjectSettings(): Partial { + // // try parse the content as json + // let content = this.getTaskConfig().schemaVersionSettings.content; + // try { + // const jsonContent = JSON.parse(JSON.stringify(content)); + // content = JSON.stringify(jsonContent); + // } catch(e) { + // // nothing + // } return { - ...this.Default_TEpSdkSchemaVersionTask_Settings, + ...this.Default_TEpSdkSchemaVersionTask_Settings, ...this.getTaskConfig().schemaVersionSettings, + // content: content }; } - public transform_EpSdkTask_Config( - epSdkSchemaVersionTask_Config: IEpSdkSchemaVersionTask_Config - ): IEpSdkSchemaVersionTask_Config { - epSdkSchemaVersionTask_Config.schemaVersionSettings.displayName = - this.truncate( - epSdkSchemaVersionTask_Config.schemaVersionSettings.displayName, - $SchemaVersion.properties.displayName.maxLength - ); + public transform_EpSdkTask_Config(epSdkSchemaVersionTask_Config: IEpSdkSchemaVersionTask_Config): IEpSdkSchemaVersionTask_Config { + epSdkSchemaVersionTask_Config.schemaVersionSettings.displayName = this.truncate( + epSdkSchemaVersionTask_Config.schemaVersionSettings.displayName, + $SchemaVersion.properties.displayName.maxLength + ); return epSdkSchemaVersionTask_Config; } @@ -105,33 +109,18 @@ export class EpSdkSchemaVersionTask extends EpSdkVersionTask { }; } - protected getEpObjectKeys( - epObject: SchemaVersion | undefined - ): IEpSdkVersionTask_EpObjectKeys { + protected getEpObjectKeys(epObject: SchemaVersion | undefined): IEpSdkVersionTask_EpObjectKeys { const funcName = "getEpObjectKeys"; const logName = `${EpSdkSchemaVersionTask.name}.${funcName}()`; - if (epObject === undefined) return this.getDefaultEpObjectKeys(); /* istanbul ignore next */ - if (epObject.id === undefined) - throw new EpSdkApiContentError( - logName, - this.constructor.name, - "epObject.id === undefined", - { - epObject: epObject, - } - ); + if (epObject.id === undefined) throw new EpSdkApiContentError(logName,this.constructor.name,"epObject.id === undefined",{ + epObject: epObject, + }); /* istanbul ignore next */ - if (epObject.schemaId === undefined) - throw new EpSdkApiContentError( - logName, - this.constructor.name, - "epObject.schemaId === undefined", - { - epObject: epObject, - } - ); + if (epObject.schemaId === undefined) throw new EpSdkApiContentError(logName,this.constructor.name,"epObject.schemaId === undefined",{ + epObject: epObject, + }); return { ...this.getDefaultEpObjectKeys(), epObjectId: epObject.schemaId, @@ -149,21 +138,14 @@ export class EpSdkSchemaVersionTask extends EpSdkVersionTask { /** * Get the latest SchemaVersion. */ - protected async getFunc( - epSdkSchemaVersionTask_Keys: IEpSdkSchemaVersionTask_Keys + protected async getFunc(epSdkSchemaVersionTask_Keys: IEpSdkSchemaVersionTask_Keys ): Promise { const funcName = "getFunc"; const logName = `${EpSdkSchemaVersionTask.name}.${funcName}()`; - EpSdkLogger.trace( - EpSdkLogger.createLogEntry(logName, { - code: EEpSdkLoggerCodes.TASK_EXECUTE_START_GET, - module: this.constructor.name, - details: { - epSdkSchemaVersionTask_Keys: epSdkSchemaVersionTask_Keys, - }, - }) - ); + EpSdkLogger.trace(EpSdkLogger.createLogEntry(logName, {code: EEpSdkLoggerCodes.TASK_EXECUTE_START_GET,module: this.constructor.name,details: { + epSdkSchemaVersionTask_Keys: epSdkSchemaVersionTask_Keys, + }})); const schemaVersion: SchemaVersion | undefined = await EpSdkSchemaVersionsService.getLatestVersionForSchemaId({ xContextId: this.xContextId, @@ -171,83 +153,57 @@ export class EpSdkSchemaVersionTask extends EpSdkVersionTask { schemaId: epSdkSchemaVersionTask_Keys.schemaId, }); - EpSdkLogger.trace( - EpSdkLogger.createLogEntry(logName, { - code: EEpSdkLoggerCodes.TASK_EXECUTE_API_GET, - module: this.constructor.name, - details: { - epSdkSchemaVersionTask_Keys: epSdkSchemaVersionTask_Keys, - schemaVersion: schemaVersion ? schemaVersion : "undefined", - }, - }) - ); - - if (schemaVersion === undefined) - return this.Empty_IEpSdkSchemaVersionTask_GetFuncReturn; - - const epSdkSchemaVersionTask_GetFuncReturn: IEpSdkSchemaVersionTask_GetFuncReturn = - { - epObjectKeys: this.getEpObjectKeys(schemaVersion), - epObject: schemaVersion, - epObjectExists: true, - }; + EpSdkLogger.trace(EpSdkLogger.createLogEntry(logName, {code: EEpSdkLoggerCodes.TASK_EXECUTE_API_GET,module: this.constructor.name,details: { + epSdkSchemaVersionTask_Keys: epSdkSchemaVersionTask_Keys, + schemaVersion: schemaVersion ? schemaVersion : "undefined", + }})); + if (schemaVersion === undefined) return this.Empty_IEpSdkSchemaVersionTask_GetFuncReturn; + const epSdkSchemaVersionTask_GetFuncReturn: IEpSdkSchemaVersionTask_GetFuncReturn = { + epObjectKeys: this.getEpObjectKeys(schemaVersion), + epObject: schemaVersion, + epObjectExists: true, + }; return epSdkSchemaVersionTask_GetFuncReturn; } - protected async isUpdateRequiredFunc( - epSdkSchemaVersionTask_GetFuncReturn: IEpSdkSchemaVersionTask_GetFuncReturn - ): Promise { + protected async isUpdateRequiredFunc(epSdkSchemaVersionTask_GetFuncReturn: IEpSdkSchemaVersionTask_GetFuncReturn): Promise { const funcName = "isUpdateRequired"; const logName = `${EpSdkSchemaVersionTask.name}.${funcName}()`; - EpSdkLogger.trace( - EpSdkLogger.createLogEntry(logName, { - code: EEpSdkLoggerCodes.TASK_EXECUTE_START_IS_UPDATE_REQUIRED, - module: this.constructor.name, - details: { - epSdkSchemaVersionTask_GetFuncReturn: - epSdkSchemaVersionTask_GetFuncReturn, - }, - }) - ); + EpSdkLogger.trace(EpSdkLogger.createLogEntry(logName, {code: EEpSdkLoggerCodes.TASK_EXECUTE_START_IS_UPDATE_REQUIRED,module: this.constructor.name,details: { + epSdkSchemaVersionTask_GetFuncReturn: epSdkSchemaVersionTask_GetFuncReturn, + }})); - if (epSdkSchemaVersionTask_GetFuncReturn.epObject === undefined) - throw new EpSdkInternalTaskError( - logName, - this.constructor.name, - "epSdkSchemaVersionTask_GetFuncReturn.epObject === undefined" - ); + if (epSdkSchemaVersionTask_GetFuncReturn.epObject === undefined) throw new EpSdkInternalTaskError(logName,this.constructor.name,"epSdkSchemaVersionTask_GetFuncReturn.epObject === undefined"); /* istanbul ignore next */ - if (epSdkSchemaVersionTask_GetFuncReturn.epObject.version === undefined) - throw new EpSdkApiContentError( - logName, - this.constructor.name, - "epSdkSchemaVersionTask_GetFuncReturn.epObject.version === undefined", - { - epObject: epSdkSchemaVersionTask_GetFuncReturn.epObject, - } - ); - const existingObject: SchemaVersion = - epSdkSchemaVersionTask_GetFuncReturn.epObject; + if (epSdkSchemaVersionTask_GetFuncReturn.epObject.version === undefined) throw new EpSdkApiContentError(logName,this.constructor.name,"epSdkSchemaVersionTask_GetFuncReturn.epObject.version === undefined",{ + epObject: epSdkSchemaVersionTask_GetFuncReturn.epObject, + }); + const existingObject: SchemaVersion = epSdkSchemaVersionTask_GetFuncReturn.epObject; + // // try parse the content as JSON + // let content = existingObject.content; + // try { + // const jsonContent = JSON.parse(JSON.stringify(content)); + // content = JSON.stringify(jsonContent); + // } catch(e) { + // // nothing + // } const existingCompareObject: TEpSdkSchemaVersionTask_CompareObject = { content: existingObject.content, - description: existingObject.description, - displayName: existingObject.displayName, + description: existingObject.description ? existingObject.description : '', + displayName: existingObject.displayName ? existingObject.displayName : '', stateId: existingObject.stateId, }; - const requestedCompareObject: TEpSdkSchemaVersionTask_CompareObject = - this.createObjectSettings(); + const requestedCompareObject: TEpSdkSchemaVersionTask_CompareObject = this.createObjectSettings(); if (this.versionStrategy === EEpSdk_VersionTaskStrategy.EXACT_VERSION) { - existingCompareObject.version = - epSdkSchemaVersionTask_GetFuncReturn.epObject.version; + existingCompareObject.version = epSdkSchemaVersionTask_GetFuncReturn.epObject.version; requestedCompareObject.version = this.versionString; } - const epSdkTask_IsUpdateRequiredFuncReturn: IEpSdkTask_IsUpdateRequiredFuncReturn = - this.create_IEpSdkTask_IsUpdateRequiredFuncReturn({ - existingObject: existingCompareObject, - requestedObject: requestedCompareObject, - }); + const epSdkTask_IsUpdateRequiredFuncReturn: IEpSdkTask_IsUpdateRequiredFuncReturn = this.create_IEpSdkTask_IsUpdateRequiredFuncReturn({ + existingObject: existingCompareObject, + requestedObject: requestedCompareObject, + }); // // DEBUG: // if(epSdkTask_IsUpdateRequiredFuncReturn.isUpdateRequired) { // EpSdkLogger.debug(EpSdkLogger.createLogEntry(logName, { code: EEpSdkLoggerCodes.TASK_EXECUTE_DONE_IS_UPDATE_REQUIRED, module: this.constructor.name, details: { @@ -266,28 +222,17 @@ export class EpSdkSchemaVersionTask extends EpSdkVersionTask { const funcName = "createFunc"; const logName = `${EpSdkSchemaVersionTask.name}.${funcName}()`; - EpSdkLogger.trace( - EpSdkLogger.createLogEntry(logName, { - code: EEpSdkLoggerCodes.TASK_EXECUTE_START_CREATE, - module: this.constructor.name, - }) - ); + EpSdkLogger.trace(EpSdkLogger.createLogEntry(logName, {code: EEpSdkLoggerCodes.TASK_EXECUTE_START_CREATE,module: this.constructor.name})); const create: SchemaVersion = { ...this.createObjectSettings(), schemaId: this.getTaskConfig().schemaId, version: this.versionString, }; - EpSdkLogger.trace( - EpSdkLogger.createLogEntry(logName, { - code: EEpSdkLoggerCodes.TASK_EXECUTE_CREATE, - module: this.constructor.name, - details: { - epSdkSchemaVersionTask_Config: this.getTaskConfig(), - create: create, - }, - }) - ); + EpSdkLogger.trace(EpSdkLogger.createLogEntry(logName, {code: EEpSdkLoggerCodes.TASK_EXECUTE_CREATE,module: this.constructor.name,details: { + epSdkSchemaVersionTask_Config: this.getTaskConfig(), + create: create, + }})); if (this.isCheckmode()) { return { @@ -299,7 +244,6 @@ export class EpSdkSchemaVersionTask extends EpSdkVersionTask { }), }; } - const schemaVersion: SchemaVersion = await EpSdkSchemaVersionsService.createSchemaVersion({ xContextId: this.xContextId, applicationDomainId: this.getTaskConfig().applicationDomainId, @@ -308,17 +252,11 @@ export class EpSdkSchemaVersionTask extends EpSdkVersionTask { targetLifecycleStateId: this.getTaskConfig().schemaVersionSettings.stateId, }); - EpSdkLogger.trace( - EpSdkLogger.createLogEntry(logName, { - code: EEpSdkLoggerCodes.TASK_EXECUTE_CREATE, - module: this.constructor.name, - details: { - epSdkApplicationDomainTask_Config: this.getTaskConfig(), - create: create, - schemaVersion: schemaVersion, - }, - }) - ); + EpSdkLogger.trace(EpSdkLogger.createLogEntry(logName, {code: EEpSdkLoggerCodes.TASK_EXECUTE_CREATE,module: this.constructor.name,details: { + epSdkApplicationDomainTask_Config: this.getTaskConfig(), + create: create, + schemaVersion: schemaVersion, + }})); return { epSdkTask_Action: this.getCreateFuncAction(), @@ -330,53 +268,25 @@ export class EpSdkSchemaVersionTask extends EpSdkVersionTask { /** * Creates a new SchemaVersion with bumped version number. */ - protected async updateFunc( - epSdkSchemaVersionTask_GetFuncReturn: IEpSdkSchemaVersionTask_GetFuncReturn - ): Promise { + protected async updateFunc(epSdkSchemaVersionTask_GetFuncReturn: IEpSdkSchemaVersionTask_GetFuncReturn): Promise { const funcName = "updateFunc"; const logName = `${EpSdkSchemaVersionTask.name}.${funcName}()`; - EpSdkLogger.trace( - EpSdkLogger.createLogEntry(logName, { - code: EEpSdkLoggerCodes.TASK_EXECUTE_START_UPDATE, - module: this.constructor.name, - }) - ); + EpSdkLogger.trace(EpSdkLogger.createLogEntry(logName, {code: EEpSdkLoggerCodes.TASK_EXECUTE_START_UPDATE,module: this.constructor.name})); - if (epSdkSchemaVersionTask_GetFuncReturn.epObject === undefined) - throw new EpSdkInternalTaskError( - logName, - this.constructor.name, - "epSdkSchemaVersionTask_GetFuncReturn.epObject === undefined" - ); + if (epSdkSchemaVersionTask_GetFuncReturn.epObject === undefined) throw new EpSdkInternalTaskError(logName,this.constructor.name,"epSdkSchemaVersionTask_GetFuncReturn.epObject === undefined"); /* istanbul ignore next */ - if (epSdkSchemaVersionTask_GetFuncReturn.epObject.id === undefined) - throw new EpSdkApiContentError( - logName, - this.constructor.name, - "epSdkSchemaVersionTask_GetFuncReturn.epObject.id === undefined", - { - epObject: epSdkSchemaVersionTask_GetFuncReturn.epObject, - } - ); + if (epSdkSchemaVersionTask_GetFuncReturn.epObject.id === undefined) throw new EpSdkApiContentError(logName,this.constructor.name,"epSdkSchemaVersionTask_GetFuncReturn.epObject.id === undefined",{ + epObject: epSdkSchemaVersionTask_GetFuncReturn.epObject, + }); /* istanbul ignore next */ - if (epSdkSchemaVersionTask_GetFuncReturn.epObject.version === undefined) - throw new EpSdkApiContentError( - logName, - this.constructor.name, - "epSdkSchemaVersionTask_GetFuncReturn.epObject.version === undefined", - { - epObject: epSdkSchemaVersionTask_GetFuncReturn.epObject, - } - ); - + if (epSdkSchemaVersionTask_GetFuncReturn.epObject.version === undefined) throw new EpSdkApiContentError(logName,this.constructor.name,"epSdkSchemaVersionTask_GetFuncReturn.epObject.version === undefined",{ + epObject: epSdkSchemaVersionTask_GetFuncReturn.epObject, + }); // getFuncReturn has the latest version object let nextVersion: string; try { - nextVersion = this.createNextVersionWithStrategyValidation({ - existingObjectVersionString: - epSdkSchemaVersionTask_GetFuncReturn.epObject.version, - }); + nextVersion = this.createNextVersionWithStrategyValidation({existingObjectVersionString: epSdkSchemaVersionTask_GetFuncReturn.epObject.version }); } catch (e) { if ( this.isCheckmode() && @@ -404,16 +314,10 @@ export class EpSdkSchemaVersionTask extends EpSdkVersionTask { schemaId: epSdkSchemaVersionTask_GetFuncReturn.epObject.id, version: nextVersion, }; - EpSdkLogger.trace( - EpSdkLogger.createLogEntry(logName, { - code: EEpSdkLoggerCodes.TASK_EXECUTE_UPDATE, - module: this.constructor.name, - details: { - epSdkApplicationDomainTask_Config: this.getTaskConfig(), - update: update, - }, - }) - ); + EpSdkLogger.trace(EpSdkLogger.createLogEntry(logName, {code: EEpSdkLoggerCodes.TASK_EXECUTE_UPDATE,module: this.constructor.name,details: { + epSdkApplicationDomainTask_Config: this.getTaskConfig(), + update: update, + }})); if (this.isCheckmode()) { const wouldBe_EpObject: SchemaVersion = { @@ -435,24 +339,17 @@ export class EpSdkSchemaVersionTask extends EpSdkVersionTask { targetLifecycleStateId: this.getTaskConfig().schemaVersionSettings.stateId, }); - EpSdkLogger.trace( - EpSdkLogger.createLogEntry(logName, { - code: EEpSdkLoggerCodes.TASK_EXECUTE_UPDATE, - module: this.constructor.name, - details: { - epSdkApplicationDomainTask_Config: this.getTaskConfig(), - update: update, - schemaVersion: schemaVersion, - }, - }) - ); + EpSdkLogger.trace(EpSdkLogger.createLogEntry(logName, {code: EEpSdkLoggerCodes.TASK_EXECUTE_UPDATE,module: this.constructor.name,details: { + epSdkApplicationDomainTask_Config: this.getTaskConfig(), + update: update, + schemaVersion: schemaVersion, + }})); - const epSdkSchemaVersionTask_UpdateFuncReturn: IEpSdkSchemaVersionTask_UpdateFuncReturn = - { - epSdkTask_Action: this.getUpdateFuncAction(), - epObject: schemaVersion, - epObjectKeys: this.getEpObjectKeys(schemaVersion), - }; + const epSdkSchemaVersionTask_UpdateFuncReturn: IEpSdkSchemaVersionTask_UpdateFuncReturn = { + epSdkTask_Action: this.getUpdateFuncAction(), + epObject: schemaVersion, + epObjectKeys: this.getEpObjectKeys(schemaVersion), + }; return epSdkSchemaVersionTask_UpdateFuncReturn; } From 70c7bb998be8bebedc8b60fe63ea0f89087cea48 Mon Sep 17 00:00:00 2001 From: Ricardo Gomez_Ulmke Date: Sun, 12 Mar 2023 15:31:51 +0100 Subject: [PATCH 22/33] comparing displayName & description --- .../src/tasks/EpSdkApplicationVersionTask.ts | 2 + .../ep-sdk/src/tasks/EpSdkEnumVersionTask.ts | 6 +-- .../src/tasks/EpSdkEpEventVersionTask.ts | 2 + .../src/tasks/EpSdkEventApiVersionTask.ts | 2 + .../src/tasks/EpSdkSchemaVersionTask.ts | 25 +++++++--- .../test/specs/tasks/enumVersionTask.spec.ts | 50 ++++--------------- 6 files changed, 37 insertions(+), 50 deletions(-) diff --git a/packages/ep-sdk/src/tasks/EpSdkApplicationVersionTask.ts b/packages/ep-sdk/src/tasks/EpSdkApplicationVersionTask.ts index 44a73cc81..bf43bdf5e 100644 --- a/packages/ep-sdk/src/tasks/EpSdkApplicationVersionTask.ts +++ b/packages/ep-sdk/src/tasks/EpSdkApplicationVersionTask.ts @@ -94,6 +94,8 @@ export class EpSdkApplicationVersionTask extends EpSdkVersionTask { return { ...this.Default_TEpSdkApplicationVersionTask_Settings, ...this.getTaskConfig().applicationVersionSettings, + description: this.getTaskConfig().applicationVersionSettings.description ? this.getTaskConfig().applicationVersionSettings.description : '', + displayName: this.getTaskConfig().applicationVersionSettings.displayName ? this.getTaskConfig().applicationVersionSettings.displayName : '', }; } diff --git a/packages/ep-sdk/src/tasks/EpSdkEnumVersionTask.ts b/packages/ep-sdk/src/tasks/EpSdkEnumVersionTask.ts index 2815a6048..6b612a12e 100644 --- a/packages/ep-sdk/src/tasks/EpSdkEnumVersionTask.ts +++ b/packages/ep-sdk/src/tasks/EpSdkEnumVersionTask.ts @@ -92,6 +92,8 @@ export class EpSdkEnumVersionTask extends EpSdkVersionTask { ...this.Default_TEpSdkEnumVersionTask_Settings, ...this.getTaskConfig().enumVersionSettings, values: this.createEnumValueList(this.getTaskConfig().enumValues), + description: this.getTaskConfig().enumVersionSettings.description ? this.getTaskConfig().enumVersionSettings.description : '', + displayName: this.getTaskConfig().enumVersionSettings.displayName ? this.getTaskConfig().enumVersionSettings.displayName : '', }; } @@ -188,9 +190,7 @@ export class EpSdkEnumVersionTask extends EpSdkVersionTask { }); } - protected async isUpdateRequiredFunc( - epSdkEnumVersionTask_GetFuncReturn: IEpSdkEnumVersionTask_GetFuncReturn - ): Promise { + protected async isUpdateRequiredFunc(epSdkEnumVersionTask_GetFuncReturn: IEpSdkEnumVersionTask_GetFuncReturn): Promise { const funcName = "isUpdateRequired"; const logName = `${EpSdkEnumVersionTask.name}.${funcName}()`; diff --git a/packages/ep-sdk/src/tasks/EpSdkEpEventVersionTask.ts b/packages/ep-sdk/src/tasks/EpSdkEpEventVersionTask.ts index 6ecd0bb16..20d9018b3 100644 --- a/packages/ep-sdk/src/tasks/EpSdkEpEventVersionTask.ts +++ b/packages/ep-sdk/src/tasks/EpSdkEpEventVersionTask.ts @@ -119,6 +119,8 @@ export class EpSdkEpEventVersionTask extends EpSdkVersionTask { const settings: TEpSdkEpEventVersionTask_Settings = { ...this.Default_TEpSdkEpEventVersionTask_Settings, ...this.getTaskConfig().eventVersionSettings, + description: this.getTaskConfig().eventVersionSettings.description ? this.getTaskConfig().eventVersionSettings.description : '', + displayName: this.getTaskConfig().eventVersionSettings.displayName ? this.getTaskConfig().eventVersionSettings.displayName : '', }; delete settings.brokerType; const brokerType = this.getTaskConfig().eventVersionSettings.brokerType diff --git a/packages/ep-sdk/src/tasks/EpSdkEventApiVersionTask.ts b/packages/ep-sdk/src/tasks/EpSdkEventApiVersionTask.ts index a05245145..131b906f6 100644 --- a/packages/ep-sdk/src/tasks/EpSdkEventApiVersionTask.ts +++ b/packages/ep-sdk/src/tasks/EpSdkEventApiVersionTask.ts @@ -89,6 +89,8 @@ export class EpSdkEventApiVersionTask extends EpSdkVersionTask { return { ...this.Default_TEpSdkEventApiVersionTask_Settings, ...this.getTaskConfig().eventApiVersionSettings, + description: this.getTaskConfig().eventApiVersionSettings.description ? this.getTaskConfig().eventApiVersionSettings.description : '', + displayName: this.getTaskConfig().eventApiVersionSettings.displayName ? this.getTaskConfig().eventApiVersionSettings.displayName : '', }; } diff --git a/packages/ep-sdk/src/tasks/EpSdkSchemaVersionTask.ts b/packages/ep-sdk/src/tasks/EpSdkSchemaVersionTask.ts index e335182b3..b233a0189 100644 --- a/packages/ep-sdk/src/tasks/EpSdkSchemaVersionTask.ts +++ b/packages/ep-sdk/src/tasks/EpSdkSchemaVersionTask.ts @@ -180,14 +180,23 @@ export class EpSdkSchemaVersionTask extends EpSdkVersionTask { epObject: epSdkSchemaVersionTask_GetFuncReturn.epObject, }); const existingObject: SchemaVersion = epSdkSchemaVersionTask_GetFuncReturn.epObject; - // // try parse the content as JSON - // let content = existingObject.content; - // try { - // const jsonContent = JSON.parse(JSON.stringify(content)); - // content = JSON.stringify(jsonContent); - // } catch(e) { - // // nothing - // } + // get the parent object to check for contentType + // existingObject.schemaId + // try parse the content as JSON + let content = existingObject.content; + try { + const jsonContent = JSON.parse(content); + + console.log(`\n\n\n\njsonContent = ${JSON.stringify(jsonContent, null, 2)}\n\n\n\n`); + + + content = JSON.stringify(jsonContent); + } catch(e) { + // nothing + } + + + const existingCompareObject: TEpSdkSchemaVersionTask_CompareObject = { content: existingObject.content, description: existingObject.description ? existingObject.description : '', diff --git a/packages/ep-sdk/test/specs/tasks/enumVersionTask.spec.ts b/packages/ep-sdk/test/specs/tasks/enumVersionTask.spec.ts index ce6f2d731..e6d3633e8 100644 --- a/packages/ep-sdk/test/specs/tasks/enumVersionTask.spec.ts +++ b/packages/ep-sdk/test/specs/tasks/enumVersionTask.spec.ts @@ -147,35 +147,20 @@ describe(`${scriptName}`, () => { groupTransactionId: "groupTransactionId", }, }); - - const epSdkEnumVersionTask_ExecuteReturn: IEpSdkEnumVersionTask_ExecuteReturn = - await epSdkEnumVersionTask.execute(); - - const message = TestLogger.createLogMessage( - "epSdkEnumVersionTask_ExecuteReturn", - epSdkEnumVersionTask_ExecuteReturn - ); - expect( - epSdkEnumVersionTask_ExecuteReturn.epSdkTask_TransactionLogData - .epSdkTask_Action, - message - ).to.eq(EEpSdkTask_Action.CREATE_FIRST_VERSION); - + const epSdkEnumVersionTask_ExecuteReturn: IEpSdkEnumVersionTask_ExecuteReturn = await epSdkEnumVersionTask.execute(); + const message = TestLogger.createLogMessage("epSdkEnumVersionTask_ExecuteReturn",epSdkEnumVersionTask_ExecuteReturn); + expect(epSdkEnumVersionTask_ExecuteReturn.epSdkTask_TransactionLogData.epSdkTask_Action,message).to.eq(EEpSdkTask_Action.CREATE_FIRST_VERSION); EnumVersionId = epSdkEnumVersionTask_ExecuteReturn.epObject.id; - // // DEBUG // expect(false, message).to.be.true; } catch (e) { - if (e instanceof ApiError) - expect(false, TestLogger.createApiTestFailMessage("failed")).to.be.true; - expect(e instanceof EpSdkError, TestLogger.createNotEpSdkErrorMessage(e)) - .to.be.true; - expect(false, TestLogger.createEpSdkTestFailMessage("failed", e)).to.be - .true; + if (e instanceof ApiError) expect(false, TestLogger.createApiTestFailMessage("failed")).to.be.true; + expect(e instanceof EpSdkError, TestLogger.createNotEpSdkErrorMessage(e)).to.be.true; + expect(false, TestLogger.createEpSdkTestFailMessage("failed", e)).to.be.true; } }); - it(`${scriptName}: enum version present: create`, async () => { + it(`${scriptName}: enum version present: create: idempotency no action`, async () => { try { const epSdkEnumVersionTask = new EpSdkEnumVersionTask({ epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, @@ -192,23 +177,10 @@ describe(`${scriptName}`, () => { groupTransactionId: "groupTransactionId", }, }); - - const epSdkEnumVersionTask_ExecuteReturn: IEpSdkEnumVersionTask_ExecuteReturn = - await epSdkEnumVersionTask.execute(); - - const message = TestLogger.createLogMessage( - "epSdkEnumVersionTask_ExecuteReturn", - epSdkEnumVersionTask_ExecuteReturn - ); - expect( - epSdkEnumVersionTask_ExecuteReturn.epSdkTask_TransactionLogData - .epSdkTask_Action, - message - ).to.eq(EEpSdkTask_Action.NO_ACTION); - expect(epSdkEnumVersionTask_ExecuteReturn.epObject.id, message).to.eq( - EnumVersionId - ); - + const epSdkEnumVersionTask_ExecuteReturn: IEpSdkEnumVersionTask_ExecuteReturn = await epSdkEnumVersionTask.execute(); + const message = TestLogger.createLogMessage("epSdkEnumVersionTask_ExecuteReturn", epSdkEnumVersionTask_ExecuteReturn); + expect(epSdkEnumVersionTask_ExecuteReturn.epSdkTask_TransactionLogData.epSdkTask_Action,message).to.eq(EEpSdkTask_Action.NO_ACTION); + expect(epSdkEnumVersionTask_ExecuteReturn.epObject.id, message).to.eq(EnumVersionId); // // DEBUG // expect(false, message).to.be.true; } catch (e) { From d41e56ada891210b8fd53c6ea0b4e543e1d652ec Mon Sep 17 00:00:00 2001 From: Ricardo Gomez_Ulmke Date: Sun, 12 Mar 2023 15:47:48 +0100 Subject: [PATCH 23/33] compare schema content as json object if possible --- packages/ep-sdk/.nycrc | 4 +- .../src/tasks/EpSdkSchemaVersionTask.ts | 44 +++++++++---------- 2 files changed, 22 insertions(+), 26 deletions(-) diff --git a/packages/ep-sdk/.nycrc b/packages/ep-sdk/.nycrc index 2303ecf95..bb3f03acf 100644 --- a/packages/ep-sdk/.nycrc +++ b/packages/ep-sdk/.nycrc @@ -2,9 +2,9 @@ "all": true, "check-coverage": true, "statements": 96, - "branches": 82, + "branches": 81, "functions": 99, - "lines": 97, + "lines": 98, "temp-dir": "./test/logs/nyc_output", "reporter": ["html", "text", "text-summary", "lcov"], "report-dir": "./test/logs/coverage", diff --git a/packages/ep-sdk/src/tasks/EpSdkSchemaVersionTask.ts b/packages/ep-sdk/src/tasks/EpSdkSchemaVersionTask.ts index b233a0189..22ab48cd8 100644 --- a/packages/ep-sdk/src/tasks/EpSdkSchemaVersionTask.ts +++ b/packages/ep-sdk/src/tasks/EpSdkSchemaVersionTask.ts @@ -25,7 +25,9 @@ import { /** @category Tasks */ export type TEpSdkSchemaVersionTask_Settings = Required> & Pick; -type TEpSdkSchemaVersionTask_CompareObject = Partial & Partial>; +type TEpSdkSchemaVersionTask_CompareObject = Partial & Partial> & { + content?: any; +} /** @category Tasks */ export interface IEpSdkSchemaVersionTask_Config @@ -74,18 +76,9 @@ export class EpSdkSchemaVersionTask extends EpSdkVersionTask { return this.epSdkTask_Config as IEpSdkSchemaVersionTask_Config; } private createObjectSettings(): Partial { - // // try parse the content as json - // let content = this.getTaskConfig().schemaVersionSettings.content; - // try { - // const jsonContent = JSON.parse(JSON.stringify(content)); - // content = JSON.stringify(jsonContent); - // } catch(e) { - // // nothing - // } return { ...this.Default_TEpSdkSchemaVersionTask_Settings, ...this.getTaskConfig().schemaVersionSettings, - // content: content }; } @@ -180,30 +173,33 @@ export class EpSdkSchemaVersionTask extends EpSdkVersionTask { epObject: epSdkSchemaVersionTask_GetFuncReturn.epObject, }); const existingObject: SchemaVersion = epSdkSchemaVersionTask_GetFuncReturn.epObject; - // get the parent object to check for contentType - // existingObject.schemaId + // better: get the parent object to check for contentType: existingObject.schemaId // try parse the content as JSON - let content = existingObject.content; + let existingContent: any = existingObject.content; try { - const jsonContent = JSON.parse(content); - - console.log(`\n\n\n\njsonContent = ${JSON.stringify(jsonContent, null, 2)}\n\n\n\n`); - - - content = JSON.stringify(jsonContent); + const jsonContent = JSON.parse(existingContent); + existingContent = jsonContent; } catch(e) { // nothing } - - - const existingCompareObject: TEpSdkSchemaVersionTask_CompareObject = { - content: existingObject.content, + content: existingContent, + // content: existingObject.content, description: existingObject.description ? existingObject.description : '', displayName: existingObject.displayName ? existingObject.displayName : '', stateId: existingObject.stateId, }; - const requestedCompareObject: TEpSdkSchemaVersionTask_CompareObject = this.createObjectSettings(); + let requestedContent: any = this.createObjectSettings().content; + try { + const jsonContent = JSON.parse(requestedContent); + requestedContent = jsonContent; + } catch(e) { + // nothing + } + const requestedCompareObject: TEpSdkSchemaVersionTask_CompareObject = { + ...this.createObjectSettings(), + content: requestedContent + } if (this.versionStrategy === EEpSdk_VersionTaskStrategy.EXACT_VERSION) { existingCompareObject.version = epSdkSchemaVersionTask_GetFuncReturn.epObject.version; requestedCompareObject.version = this.versionString; From 8bf15facbb955bd7ab3f4ce9697f71212dae585e Mon Sep 17 00:00:00 2001 From: Ricardo Gomez_Ulmke Date: Mon, 13 Mar 2023 09:03:03 +0100 Subject: [PATCH 24/33] fixed test --- .../services/CliApplicationDomainsService.ts | 7 ++- .../best-practices/message-no-schema.spec.yml | 1 - .../test/lib/TestService.ts | 27 +++++++----- .../test/specs/best-practices.spec.ts | 43 ++++++------------- .../documents/EpAsyncApiMessageDocument.ts | 2 +- 5 files changed, 35 insertions(+), 45 deletions(-) diff --git a/packages/ep-async-api-importer/src/services/CliApplicationDomainsService.ts b/packages/ep-async-api-importer/src/services/CliApplicationDomainsService.ts index 365da9de2..4e368c700 100644 --- a/packages/ep-async-api-importer/src/services/CliApplicationDomainsService.ts +++ b/packages/ep-async-api-importer/src/services/CliApplicationDomainsService.ts @@ -9,10 +9,9 @@ class CliApplicationDomainsService { }): Promise => { for (const applicationDomainName of applicationDomainNameList) { try { - const applicationDomain: ApplicationDomain = - await EpSdkApplicationDomainsService.deleteByName({ - applicationDomainName: applicationDomainName, - }); + const applicationDomain: ApplicationDomain = await EpSdkApplicationDomainsService.deleteByName({ + applicationDomainName: applicationDomainName, + }); /* istanbul ignore next */ applicationDomain; } catch (e) { diff --git a/packages/ep-async-api-importer/test/data/best-practices/message-no-schema.spec.yml b/packages/ep-async-api-importer/test/data/best-practices/message-no-schema.spec.yml index 3e7b737eb..a3cfbf12f 100644 --- a/packages/ep-async-api-importer/test/data/best-practices/message-no-schema.spec.yml +++ b/packages/ep-async-api-importer/test/data/best-practices/message-no-schema.spec.yml @@ -1,6 +1,5 @@ --- asyncapi: "2.5.0" -x-ep-application-domain-name: solace-labs/ep-asyncapi/test info: title: "Message no schema" version: "0.1.1" diff --git a/packages/ep-async-api-importer/test/lib/TestService.ts b/packages/ep-async-api-importer/test/lib/TestService.ts index cd484ec05..fcfe900ce 100644 --- a/packages/ep-async-api-importer/test/lib/TestService.ts +++ b/packages/ep-async-api-importer/test/lib/TestService.ts @@ -1,4 +1,5 @@ import { EpAsyncApiDocument } from "@solace-labs/ep-asyncapi"; +import { EEpSdkTask_TargetState, EpSdkApplicationDomainTask, IEpSdkApplicationDomainTask_ExecuteReturn } from "@solace-labs/ep-sdk"; import { CliUtils } from "../../src/cli-components"; import { CliApplicationDomainsService, @@ -70,17 +71,11 @@ export class TestService { if (keep) return; const xvoid: void = await CliApplicationDomainsService.absent_ApplicationDomains({ - applicationDomainNameList: TestService.testApiSpecRecordList - .map((testApiSpecRecord: TTestApiSpecRecord) => { + applicationDomainNameList: TestService.testApiSpecRecordList.map((testApiSpecRecord: TTestApiSpecRecord) => { return testApiSpecRecord.epAsyncApiDocument.getApplicationDomainName(); - }) - .concat( - TestService.testApiSpecRecordList.map( - (testApiSpecRecord: TTestApiSpecRecord) => { - return testApiSpecRecord.epAsyncApiDocument.getAssetsApplicationDomainName(); - } - ) - ), + }).concat(TestService.testApiSpecRecordList.map((testApiSpecRecord: TTestApiSpecRecord) => { + return testApiSpecRecord.epAsyncApiDocument.getAssetsApplicationDomainName(); + })), }); }; @@ -101,4 +96,16 @@ export class TestService { return true; }; + + public static applicationDomainTask = async({ applicationDomainName, epSdkTask_TargetState}:{ + applicationDomainName: string; + epSdkTask_TargetState: EEpSdkTask_TargetState; + }): Promise => { + const task = new EpSdkApplicationDomainTask({ + applicationDomainName: applicationDomainName, + epSdkTask_TargetState: epSdkTask_TargetState + }); + const task_ExecuteReturn: IEpSdkApplicationDomainTask_ExecuteReturn = await task.execute('xContextId'); + } + } diff --git a/packages/ep-async-api-importer/test/specs/best-practices.spec.ts b/packages/ep-async-api-importer/test/specs/best-practices.spec.ts index 068fac15c..8c553fdd0 100644 --- a/packages/ep-async-api-importer/test/specs/best-practices.spec.ts +++ b/packages/ep-async-api-importer/test/specs/best-practices.spec.ts @@ -1,49 +1,44 @@ import "mocha"; import { expect } from "chai"; import path from "path"; -import { - ApplicationDomain, - EventApisResponse, - EventApIsService, - EventsResponse, - EventsService, - SchemasResponse, - SchemasService, -} from "@solace-labs/ep-openapi-node"; -import { EpSdkApplicationDomainsService } from "@solace-labs/ep-sdk"; -import { TestContext } from "@internal/tools/src"; +import { TestContext, TestUtils } from "@internal/tools/src"; import { TestConfig, TestLogger, TestService, - TTestApiSpecRecord, } from "../lib"; import { CliConfig, CliError, - CliRunSummary, - ICliRunSummary_Base, CliImporterManager, ECliImporterManagerMode, CliErrorFromEpAsyncApiError, } from "../../src/cli-components"; -import { EpAsyncApiBestPracticesError, EpAsyncApiError, EpAsyncApiMessageDocument } from "@solace-labs/ep-asyncapi"; +import { + EpAsyncApiBestPracticesError, + EpAsyncApiError, + EpAsyncApiMessageDocument +} from "@solace-labs/ep-asyncapi"; +import { EEpSdkTask_TargetState } from "@solace-labs/ep-sdk"; const scriptName: string = path.basename(__filename); TestLogger.logMessage(scriptName, ">>> starting ..."); +const TestSpecName = scriptName; +const TestSpecId = TestUtils.getUUID(); // TEST expects only 1 api file, not a list of api files. let FileList: Array = []; let AsyncApiSpecFile: string; -let AsyncApiSpecFile_X_EpApplicationDomainName: string; -let AsyncApiSpecFile_X_EpAssetApplicationDomainName: string; +let ApplicationDomainName: string; const initializeGlobals = () => { + ApplicationDomainName = `${TestConfig.getAppId()}/${TestSpecName}`; AsyncApiSpecFile = TestService.validateFilePathWithReadPermission(`${TestConfig.getConfig().dataRootDir}/best-practices/message-no-schema.spec.yml`); FileList.push(AsyncApiSpecFile); // set test specific importer options CliConfig.getCliImporterManagerOptions().asyncApiFileList = FileList; CliConfig.getCliImporterManagerOptions().cliImporterManagerMode = ECliImporterManagerMode.RELEASE_MODE; + CliConfig.getCliImporterManagerOptions().applicationDomainName = ApplicationDomainName; // CliConfig.getCliImporterManagerOptions().runId = scriptName; // // DEBUG // CliConfig.getCliImporterManagerOptions().cliImporterManagerMode = ECliImporterManagerMode.TEST_MODE_KEEP; @@ -66,18 +61,7 @@ describe(`${scriptName}`, () => { after(async () => { TestContext.newItId(); - let err: Error | undefined = undefined; - try { - // test ep assets & versions are correctly imported as in epAsyncApiDocument - const pass: boolean = await TestService.checkAssetsCreatedAsExpected(); - expect(pass, `${scriptName}: AFTER checks not passed`).to.be.true; - } catch (e) { - err = e; - } finally { - // ensure all app domains are absent - const xvoid: void = await TestService.absent_ApplicationDomains(CliConfig.getCliImporterManagerOptions().cliImporterManagerMode === ECliImporterManagerMode.TEST_MODE_KEEP); - } - expect(err, TestLogger.createNotCliErrorMesssage(JSON.stringify(err))).to.be.undefined; + await TestService.applicationDomainTask({ applicationDomainName: ApplicationDomainName, epSdkTask_TargetState: EEpSdkTask_TargetState.ABSENT}); }); it(`${scriptName}: should import spec with validate best practices ON`, async () => { @@ -87,6 +71,7 @@ describe(`${scriptName}`, () => { const xvoid: void = await cliImporter.run(); expect(false, 'should never get here').to.be.true; } catch (e) { + // console.log(`e = ${JSON.stringify(e, null, 2)}`); expect(e instanceof CliError, TestLogger.createNotCliErrorMesssage(e.message)).to.be.true; expect(e instanceof CliErrorFromEpAsyncApiError, TestLogger.createWrongCliErrorInstance(CliErrorFromEpAsyncApiError.name, e)).to.be.true; const cliErrorFromEpAsyncApiError: CliErrorFromEpAsyncApiError = e; diff --git a/packages/ep-asyncapi/src/documents/EpAsyncApiMessageDocument.ts b/packages/ep-asyncapi/src/documents/EpAsyncApiMessageDocument.ts index b189308c3..af58d80ec 100644 --- a/packages/ep-asyncapi/src/documents/EpAsyncApiMessageDocument.ts +++ b/packages/ep-asyncapi/src/documents/EpAsyncApiMessageDocument.ts @@ -119,7 +119,7 @@ export class EpAsyncApiMessageDocument { asyncApiSpecTitle: this.epAsyncApiDocument.getTitle(), issues: EpAsyncApiMessageDocument.MissingMessagePayloadSchemaIssue, value: { - channel: this.asyncApiMessageKey, + channel: this.epAsyncApiChannelDocument.getAsyncApiChannelKey(), message: this.asyncApiMessageKey } }); From 14c7906c05b7ac087f5bdf0f656db8ca465e3f87 Mon Sep 17 00:00:00 2001 From: Ricardo Gomez_Ulmke Date: Mon, 13 Mar 2023 10:23:38 +0100 Subject: [PATCH 25/33] tests --- .../src/importers/CliApplicationImporter.ts | 16 ++++----- .../src/importers/CliEventApiImporter.ts | 23 +++++++------ .../src/documents/EpAsyncApiDocument.ts | 34 ++++++++++++++----- 3 files changed, 45 insertions(+), 28 deletions(-) diff --git a/packages/ep-async-api-importer/src/importers/CliApplicationImporter.ts b/packages/ep-async-api-importer/src/importers/CliApplicationImporter.ts index 069c42af8..c879198bf 100644 --- a/packages/ep-async-api-importer/src/importers/CliApplicationImporter.ts +++ b/packages/ep-async-api-importer/src/importers/CliApplicationImporter.ts @@ -52,9 +52,7 @@ export class CliApplicationImporter extends CliImporter { super(cliApplicationImporterOptions); } - protected generate_assets_ouput = async ({ - cliImporterGenerateAssetsOptions, - }: { + protected generate_assets_ouput = async ({cliImporterGenerateAssetsOptions}: { cliImporterGenerateAssetsOptions: ICliImporterGenerateAssetsOptions; }): Promise => { const funcName = "generate_assets_ouput"; @@ -84,7 +82,7 @@ export class CliApplicationImporter extends CliImporter { // get latest version as reference const latestExistingApplicationVersionObjectBefore: ApplicationVersion | undefined = await EpSdkApplicationVersionsService.getLatestVersionForApplicationName({ applicationDomainId: applicationDomainId, - applicationName: epAsyncApiDocument.getTitle(), + applicationName: epAsyncApiDocument.getEpApplicationName(), }); // const latestExistingApplicationVersionString: string | undefined = latestExistingApplicationVersionObjectBefore?.version; @@ -109,7 +107,7 @@ export class CliApplicationImporter extends CliImporter { versionStrategy: EEpSdk_VersionTaskStrategy.EXACT_VERSION, applicationVersionSettings: { description: epAsyncApiDocument.getDescription(), - displayName: epAsyncApiDocument.getTitle(), + displayName: epAsyncApiDocument.getEpApplicationVersionName(), stateId: this.get_EpSdkTask_StateId(), declaredConsumedEventVersionIds: cliPubSubEventVersionIds.publishEventVersionIdList, @@ -142,7 +140,7 @@ export class CliApplicationImporter extends CliImporter { if (latestExistingApplicationVersionObjectBefore === undefined) throw new CliInternalCodeInconsistencyError(logName, { message: "latestExistingApplicationVersionObjectBefore === undefined", applicationDomainId: applicationDomainId, - applicationName: epAsyncApiDocument.getTitle(), + applicationName: epAsyncApiDocument.getEpApplicationName(), }); // create a new application version and issue warning @@ -154,7 +152,7 @@ export class CliApplicationImporter extends CliImporter { versionStrategy: EEpSdk_VersionTaskStrategy.BUMP_PATCH, applicationVersionSettings: { description: epAsyncApiDocument.getDescription(), - displayName: epAsyncApiDocument.getTitle(), + displayName: epAsyncApiDocument.getEpApplicationVersionName(), stateId: this.get_EpSdkTask_StateId(), declaredConsumedEventVersionIds: cliPubSubEventVersionIds.publishEventVersionIdList, declaredProducedEventVersionIds: cliPubSubEventVersionIds.subscribeEventVersionIdList, @@ -196,7 +194,7 @@ export class CliApplicationImporter extends CliImporter { versionStrategy: EEpSdk_VersionTaskStrategy.EXACT_VERSION, applicationVersionSettings: { description: epAsyncApiDocument.getDescription(), - displayName: epAsyncApiDocument.getTitle(), + displayName: epAsyncApiDocument.getEpApplicationVersionName(), stateId: this.get_EpSdkTask_StateId(), declaredConsumedEventVersionIds: cliPubSubEventVersionIds.publishEventVersionIdList, declaredProducedEventVersionIds: cliPubSubEventVersionIds.subscribeEventVersionIdList, @@ -239,7 +237,7 @@ export class CliApplicationImporter extends CliImporter { const epSdkApplicationTask = new EpSdkApplicationTask({ epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, applicationDomainId: applicationDomainId, - applicationName: epAsyncApiDocument.getTitle(), + applicationName: epAsyncApiDocument.getEpApplicationName(), applicationObjectSettings: { applicationType: "standard", brokerType: epAsyncApiDocument.getBrokerType() as unknown as Application.brokerType diff --git a/packages/ep-async-api-importer/src/importers/CliEventApiImporter.ts b/packages/ep-async-api-importer/src/importers/CliEventApiImporter.ts index a4cca1909..d507a9711 100644 --- a/packages/ep-async-api-importer/src/importers/CliEventApiImporter.ts +++ b/packages/ep-async-api-importer/src/importers/CliEventApiImporter.ts @@ -124,7 +124,7 @@ export class CliEventApiImporter extends CliAssetsImporter { // get latest version as reference const latestExistingEventApiVersionObjectBefore: EventApiVersion | undefined = await EpSdkEventApiVersionsService.getLatestVersionForEventApiName({ applicationDomainId: applicationDomainId, - eventApiName: epAsyncApiDocument.getTitle(), + eventApiName: epAsyncApiDocument.getEpEventApiName(), }); // const latestExistingEventApiVersionString: string | undefined = latestExistingEventApiVersionObjectBefore?.version; // get the list of pub and sub events @@ -177,7 +177,7 @@ export class CliEventApiImporter extends CliAssetsImporter { if (latestExistingEventApiVersionObjectBefore === undefined) throw new CliInternalCodeInconsistencyError(logName, { message: "latestExistingEventApiVersionObjectBefore === undefined", applicationDomainId: applicationDomainId, - applicationName: epAsyncApiDocument.getTitle(), + applicationName: epAsyncApiDocument.getEpApplicationName(), }); if (CliRunContext.get().runMode === ECliRunContext_RunMode.RELEASE) { // create event api version and issue warning @@ -242,6 +242,8 @@ export class CliEventApiImporter extends CliAssetsImporter { requestedUpdates: requestedUpdates, }); throw new CliImporterTestRunAssetsInconsistencyError(logName, { + applicationDomainName: epAsyncApiDocument.getApplicationDomainName(), + eventApiName: epAsyncApiDocument.getEpEventApiName(), requestedUpdates: requestedUpdates, latestExistingEventApiVersionObjectBefore: latestExistingEventApiVersionObjectBefore, epSdkEventApiVersionTask_ExecuteReturn: epSdkEventApiVersionTask_ExecuteReturn_Check, @@ -307,7 +309,7 @@ export class CliEventApiImporter extends CliAssetsImporter { const epSdkEventApiTask = new EpSdkEventApiTask({ epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, applicationDomainId: applicationDomainId, - eventApiName: epAsyncApiDocument.getTitle(), + eventApiName: epAsyncApiDocument.getEpEventApiName(), eventApiObjectSettings: { shared: true, brokerType: epAsyncApiDocument.getBrokerType() as unknown as EventApi.brokerType, @@ -338,8 +340,7 @@ export class CliEventApiImporter extends CliAssetsImporter { return { eventApiId: eventApiId, - eventApiVersionId: - cliEventApiImporterRunPresentEventApiVersionReturn.eventApiVersionId, + eventApiVersionId: cliEventApiImporterRunPresentEventApiVersionReturn.eventApiVersionId, }; }; @@ -349,7 +350,7 @@ export class CliEventApiImporter extends CliAssetsImporter { const funcName = "run_present"; const logName = `${CliEventApiImporter.name}.${funcName}()`; - const apiTitle: string = cliImporterRunPresentOptions.epAsyncApiDocument.getTitle(); + const apiTitle: string = cliImporterRunPresentOptions.epAsyncApiDocument.getEpEventApiName(); const apiVersion: string = cliImporterRunPresentOptions.epAsyncApiDocument.getVersion(); const apiBrokerType: string = cliImporterRunPresentOptions.epAsyncApiDocument.getBrokerType(); const epApplicationDomainName: string = cliImporterRunPresentOptions.epAsyncApiDocument.getApplicationDomainName(); @@ -480,7 +481,7 @@ export class CliEventApiImporter extends CliAssetsImporter { CliUtils.convertStringToFilePath( epAsyncApiDocument.getApplicationDomainName() ); - const apiTitleAsFilePath = epAsyncApiDocument.getTitleAsFilePath(); + const apiTitleAsFilePath = epAsyncApiDocument.getEpEventApiNameAsFilePath(); const assetOutputRootDir: string = CliUtils.ensureDirExists( this.cliImporterOptions.assetOutputDir, applicationDomainNameAsFilePath + "/" + apiTitleAsFilePath @@ -489,8 +490,8 @@ export class CliEventApiImporter extends CliAssetsImporter { assetOutputRootDir, "schemas" ); - const asyncApiSpecFileNameJson = assetOutputRootDir + "/" + epAsyncApiDocument.getTitleAsFileName("json"); - const asyncApiSpecFileNameYaml = assetOutputRootDir + "/" + epAsyncApiDocument.getTitleAsFileName("yml"); + const asyncApiSpecFileNameJson = assetOutputRootDir + "/" + epAsyncApiDocument.getEpEventApiNameAsFileName("json"); + const asyncApiSpecFileNameYaml = assetOutputRootDir + "/" + epAsyncApiDocument.getEpEventApiNameAsFileName("yml"); CliLogger.trace(CliLogger.createLogEntry(logName, { code: ECliStatusCodes.GENERATING_ASSETS_OUTPUT, details: { applicationDomainNameAsFilePath: applicationDomainNameAsFilePath, apiTitleAsFilePath: apiTitleAsFilePath, @@ -507,7 +508,7 @@ export class CliEventApiImporter extends CliAssetsImporter { CliRunSummary.generatingApiOutput({ cliRunSummary_GenerateApiOutput: { type: ECliRunSummary_Type.ApiOutput, - apiName: epAsyncApiDocument.getTitle(), + apiName: epAsyncApiDocument.getEpEventApiName(), apiVersion: epAsyncApiDocument.getVersion(), outputDir: assetOutputRootDir, }}); @@ -620,7 +621,7 @@ export class CliEventApiImporter extends CliAssetsImporter { overrideChannelDelimiter: cliImporterRunOptions.overrideChannelDelimiter, validateBestPractices: this.cliImporterOptions.cliValidateApiSpecBestPractices, }); - cliEventApiImporterRunImportReturn.apiTitle = epAsyncApiDocument.getTitle(); + cliEventApiImporterRunImportReturn.apiTitle = epAsyncApiDocument.getEpEventApiName(); cliEventApiImporterRunImportReturn.applicationDomainName = epAsyncApiDocument.getApplicationDomainName(); cliEventApiImporterRunImportReturn.assetApplicationDomainName = epAsyncApiDocument.getAssetsApplicationDomainName(); diff --git a/packages/ep-asyncapi/src/documents/EpAsyncApiDocument.ts b/packages/ep-asyncapi/src/documents/EpAsyncApiDocument.ts index e7c96b67b..c12234c4e 100644 --- a/packages/ep-asyncapi/src/documents/EpAsyncApiDocument.ts +++ b/packages/ep-asyncapi/src/documents/EpAsyncApiDocument.ts @@ -356,6 +356,14 @@ export class EpAsyncApiDocument { return this.asyncApiDocument.info().title(); } + // private getTitleAsFilePath(): string { + // return this.getTitle().replaceAll(/[^0-9a-zA-Z]+/g, "-"); + // } + + // private getTitleAsFileName(ext: string): string { + // return `${this.getTitleAsFilePath()}.${ext}`; + // } + public getVersion(): string { return this.asyncApiDocument.info().version(); } @@ -382,25 +390,35 @@ export class EpAsyncApiDocument { return this.unprefixedAssetsApplicationDomainName; } - public getTitleAsFilePath(): string { - return this.getTitle().replaceAll(/[^0-9a-zA-Z]+/g, "-"); - } - - public getTitleAsFileName(ext: string): string { - return `${this.getTitleAsFilePath()}.${ext}`; - } - public getBrokerType(): EBrokerTypes { return this.brokerType; } public getChannelDelimiter(): EChannelDelimiters { return this.channelDelimiter; } public getEpEventApiName(): string { return this.epEventApiName; } + public getEpEventApiNameAsFilePath(): string { + return this.getEpEventApiName().replaceAll(/[^0-9a-zA-Z]+/g, "-"); + } + + public getEpEventApiNameAsFileName(ext: string): string { + return `${this.getEpEventApiNameAsFilePath()}.${ext}`; + } + public getEpEventApiVersionName(): string { if(this.epEventApiVersionName === undefined) return ''; return this.epEventApiVersionName; } + public getEpApplicationName(): string { + // TODO: needs its own property, different create algo + return this.getEpEventApiName(); + } + + public getEpApplicationVersionName(): string { + // TODO: needs its own property, different create algo + return this.getEpEventApiVersionName(); + } + public getAsJson(): any { return this.asyncApiDocumentJson; } public getAsYamlString(): string { From 8603c9dd1275d5c0c2b2df8011f9e5b896cd3bd8 Mon Sep 17 00:00:00 2001 From: Ricardo Gomez_Ulmke Date: Mon, 13 Mar 2023 10:33:43 +0100 Subject: [PATCH 26/33] test --- .../ep-asyncapi/test/specs/unit/EpAsyncApiDocument.spec.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/ep-asyncapi/test/specs/unit/EpAsyncApiDocument.spec.ts b/packages/ep-asyncapi/test/specs/unit/EpAsyncApiDocument.spec.ts index defa8c976..92136d54f 100644 --- a/packages/ep-asyncapi/test/specs/unit/EpAsyncApiDocument.spec.ts +++ b/packages/ep-asyncapi/test/specs/unit/EpAsyncApiDocument.spec.ts @@ -60,11 +60,11 @@ describe(`${scriptName}`, () => { expect(title, 'failed').to.eq(Global_Title); const expected_titleAsFilePath = "slash-amp-star-quotes-"; - const titleAsFilePath = Global_EpAsyncApiDocument.getTitleAsFilePath(); + const titleAsFilePath = Global_EpAsyncApiDocument.getEpEventApiNameAsFilePath(); expect(titleAsFilePath, 'failed').to.eq(expected_titleAsFilePath); const expected_titleAsFileName = expected_titleAsFilePath + ".yml"; - const titleAsFileName = Global_EpAsyncApiDocument.getTitleAsFileName('yml'); + const titleAsFileName = Global_EpAsyncApiDocument.getEpEventApiNameAsFileName('yml'); expect(titleAsFileName, 'failed').to.eq(expected_titleAsFileName); }); From 1565b7483734e851257db4d59746a6ea604a1c7c Mon Sep 17 00:00:00 2001 From: Ricardo Gomez_Ulmke Date: Mon, 13 Mar 2023 11:34:59 +0100 Subject: [PATCH 27/33] tests --- .../test/specs/passing-release_mode.spec.ts | 9 +++++++-- packages/ep-sdk/src/services/EpSdkEnumVersionsService.ts | 2 +- .../ep-sdk/src/services/EpSdkEpEventVersionsService.ts | 2 +- .../ep-sdk/src/services/EpSdkEventApiVersionsService.ts | 2 +- .../ep-sdk/src/services/EpSdkSchemaVersionsService.ts | 2 +- 5 files changed, 11 insertions(+), 6 deletions(-) diff --git a/packages/ep-async-api-importer/test/specs/passing-release_mode.spec.ts b/packages/ep-async-api-importer/test/specs/passing-release_mode.spec.ts index 4e437668c..42792ecec 100644 --- a/packages/ep-async-api-importer/test/specs/passing-release_mode.spec.ts +++ b/packages/ep-async-api-importer/test/specs/passing-release_mode.spec.ts @@ -27,7 +27,12 @@ TestLogger.logMessage(scriptName, ">>> starting ..."); let FileList: Array = []; const initializeGlobals = () => { + // test individual specs only + // FileList.push(...CliUtils.createFileList(`${TestConfig.getConfig().dataRootDir}/passing/**/AcmeRetail-Central-IT-Provider-TillSystem-v1-Test.spec.yml`)); + + // test all specs found in dir FileList.push(...CliUtils.createFileList(`${TestConfig.getConfig().dataRootDir}/passing/**/*.spec.yml`)); + // set test specific importer options CliConfig.getCliImporterManagerOptions().asyncApiFileList = FileList; CliConfig.getCliImporterManagerOptions().cliImporterManagerMode = ECliImporterManagerMode.RELEASE_MODE; @@ -84,8 +89,8 @@ describe(`${scriptName}`, () => { const cliImporter = new CliImporterManager(CliConfig.getCliImporterManagerOptions()); const xvoid: void = await cliImporter.run(); const cliRunSummaryList: Array = CliRunSummary.getSummaryLogList(); - // DEBUG - // expect(false, JSON.stringify(cliRunSummaryList, null, 2)).to.be.true; + // // DEBUG + // expect(false, 'check imported specs & assets').to.be.true; } catch(e) { expect(e instanceof CliError, TestLogger.createNotCliErrorMesssage(e.message)).to.be.true; expect(false, TestLogger.createTestFailMessageWithCliError('failed', e)).to.be.true; diff --git a/packages/ep-sdk/src/services/EpSdkEnumVersionsService.ts b/packages/ep-sdk/src/services/EpSdkEnumVersionsService.ts index e7ffcbbba..b24e6ca92 100644 --- a/packages/ep-sdk/src/services/EpSdkEnumVersionsService.ts +++ b/packages/ep-sdk/src/services/EpSdkEnumVersionsService.ts @@ -279,7 +279,7 @@ export class EpSdkEnumVersionsServiceClass extends EpSdkVersionServiceClass { versionStrategy: EEpSdk_VersionTaskStrategy.EXACT_VERSION, enumVersionSettings: { stateId: fromTopicAddressEnumVersion.stateId, - displayName: fromTopicAddressEnumVersion.displayName ? fromTopicAddressEnumVersion.displayName : fromTopicAddressEnum.name, + displayName: fromTopicAddressEnumVersion.displayName ? fromTopicAddressEnumVersion.displayName : '', description: fromTopicAddressEnumVersion.description, }, enumValues: fromTopicAddressEnumVersion.values.map( (x) => { return x.value; }), diff --git a/packages/ep-sdk/src/services/EpSdkEpEventVersionsService.ts b/packages/ep-sdk/src/services/EpSdkEpEventVersionsService.ts index 778cfed22..2ba09095e 100644 --- a/packages/ep-sdk/src/services/EpSdkEpEventVersionsService.ts +++ b/packages/ep-sdk/src/services/EpSdkEpEventVersionsService.ts @@ -499,7 +499,7 @@ export class EpSdkEpEventVersionsServiceClass extends EpSdkVersionServiceClass { topicString: this.createTopicStringFromAddress({ address: targetEventVersionDeliveryDescriptorAddress }), eventVersionSettings: { stateId: fromEventVersion.stateId, - displayName: fromEventVersion.displayName ? fromEventVersion.displayName : fromEvent.name, + displayName: fromEventVersion.displayName ? fromEventVersion.displayName : '', description: fromEventVersion.description ? fromEventVersion.description : '', schemaVersionId: targetSchemaVersion.id, }, diff --git a/packages/ep-sdk/src/services/EpSdkEventApiVersionsService.ts b/packages/ep-sdk/src/services/EpSdkEventApiVersionsService.ts index 3d1ceec2d..7349e1276 100644 --- a/packages/ep-sdk/src/services/EpSdkEventApiVersionsService.ts +++ b/packages/ep-sdk/src/services/EpSdkEventApiVersionsService.ts @@ -423,7 +423,7 @@ export class EpSdkEventApiVersionsServiceClass extends EpSdkVersionServiceClass versionStrategy: EEpSdk_VersionTaskStrategy.EXACT_VERSION, eventApiVersionSettings: { stateId: fromEventApiVersion.stateId, - displayName: fromEventApiVersion.displayName ? fromEventApiVersion.displayName : fromEventApi.name, + displayName: fromEventApiVersion.displayName ? fromEventApiVersion.displayName : '', description: fromEventApiVersion.description ? fromEventApiVersion.description : '', consumedEventVersionIds: targetConsumedEventVersions.map( (targetConsumedEventVersion: EventVersion) => { /* istanbul ignore next */ diff --git a/packages/ep-sdk/src/services/EpSdkSchemaVersionsService.ts b/packages/ep-sdk/src/services/EpSdkSchemaVersionsService.ts index f9de5040e..1f9fe3b37 100644 --- a/packages/ep-sdk/src/services/EpSdkSchemaVersionsService.ts +++ b/packages/ep-sdk/src/services/EpSdkSchemaVersionsService.ts @@ -380,7 +380,7 @@ export class EpSdkSchemaVersionsServiceClass extends EpSdkVersionServiceClass { versionStrategy: EEpSdk_VersionTaskStrategy.EXACT_VERSION, schemaVersionSettings: { stateId: fromSchemaVersion.stateId, - displayName: fromSchemaVersion.displayName ? fromSchemaVersion.displayName : fromSchemaObject.name, + displayName: fromSchemaVersion.displayName ? fromSchemaVersion.displayName : '', description: fromSchemaVersion.description ? fromSchemaVersion.description : "", content: fromSchemaVersion.content, }, From 469f6dd1fd22871ff4764866fd18649b4b024c13 Mon Sep 17 00:00:00 2001 From: Ricardo Gomez_Ulmke Date: Mon, 13 Mar 2023 12:42:01 +0100 Subject: [PATCH 28/33] tests --- .../src/importers/CliApplicationImporter.ts | 12 +- .../src/importers/CliEventApiImporter.ts | 26 ++-- .../test/specs/ep-idempotency.x-spec.ts | 118 ++++++++++++++++-- .../src/documents/EpAsyncApiDocument.ts | 84 +++++++------ 4 files changed, 176 insertions(+), 64 deletions(-) diff --git a/packages/ep-async-api-importer/src/importers/CliApplicationImporter.ts b/packages/ep-async-api-importer/src/importers/CliApplicationImporter.ts index c879198bf..ec7dd6469 100644 --- a/packages/ep-async-api-importer/src/importers/CliApplicationImporter.ts +++ b/packages/ep-async-api-importer/src/importers/CliApplicationImporter.ts @@ -82,7 +82,7 @@ export class CliApplicationImporter extends CliImporter { // get latest version as reference const latestExistingApplicationVersionObjectBefore: ApplicationVersion | undefined = await EpSdkApplicationVersionsService.getLatestVersionForApplicationName({ applicationDomainId: applicationDomainId, - applicationName: epAsyncApiDocument.getEpApplicationName(), + applicationName: epAsyncApiDocument.getEpApiName(), }); // const latestExistingApplicationVersionString: string | undefined = latestExistingApplicationVersionObjectBefore?.version; @@ -107,7 +107,7 @@ export class CliApplicationImporter extends CliImporter { versionStrategy: EEpSdk_VersionTaskStrategy.EXACT_VERSION, applicationVersionSettings: { description: epAsyncApiDocument.getDescription(), - displayName: epAsyncApiDocument.getEpApplicationVersionName(), + displayName: epAsyncApiDocument.getEpApiVersionName(), stateId: this.get_EpSdkTask_StateId(), declaredConsumedEventVersionIds: cliPubSubEventVersionIds.publishEventVersionIdList, @@ -140,7 +140,7 @@ export class CliApplicationImporter extends CliImporter { if (latestExistingApplicationVersionObjectBefore === undefined) throw new CliInternalCodeInconsistencyError(logName, { message: "latestExistingApplicationVersionObjectBefore === undefined", applicationDomainId: applicationDomainId, - applicationName: epAsyncApiDocument.getEpApplicationName(), + applicationName: epAsyncApiDocument.getEpApiName(), }); // create a new application version and issue warning @@ -152,7 +152,7 @@ export class CliApplicationImporter extends CliImporter { versionStrategy: EEpSdk_VersionTaskStrategy.BUMP_PATCH, applicationVersionSettings: { description: epAsyncApiDocument.getDescription(), - displayName: epAsyncApiDocument.getEpApplicationVersionName(), + displayName: epAsyncApiDocument.getEpApiVersionName(), stateId: this.get_EpSdkTask_StateId(), declaredConsumedEventVersionIds: cliPubSubEventVersionIds.publishEventVersionIdList, declaredProducedEventVersionIds: cliPubSubEventVersionIds.subscribeEventVersionIdList, @@ -194,7 +194,7 @@ export class CliApplicationImporter extends CliImporter { versionStrategy: EEpSdk_VersionTaskStrategy.EXACT_VERSION, applicationVersionSettings: { description: epAsyncApiDocument.getDescription(), - displayName: epAsyncApiDocument.getEpApplicationVersionName(), + displayName: epAsyncApiDocument.getEpApiVersionName(), stateId: this.get_EpSdkTask_StateId(), declaredConsumedEventVersionIds: cliPubSubEventVersionIds.publishEventVersionIdList, declaredProducedEventVersionIds: cliPubSubEventVersionIds.subscribeEventVersionIdList, @@ -237,7 +237,7 @@ export class CliApplicationImporter extends CliImporter { const epSdkApplicationTask = new EpSdkApplicationTask({ epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, applicationDomainId: applicationDomainId, - applicationName: epAsyncApiDocument.getEpApplicationName(), + applicationName: epAsyncApiDocument.getEpApiName(), applicationObjectSettings: { applicationType: "standard", brokerType: epAsyncApiDocument.getBrokerType() as unknown as Application.brokerType diff --git a/packages/ep-async-api-importer/src/importers/CliEventApiImporter.ts b/packages/ep-async-api-importer/src/importers/CliEventApiImporter.ts index d507a9711..f451fe27b 100644 --- a/packages/ep-async-api-importer/src/importers/CliEventApiImporter.ts +++ b/packages/ep-async-api-importer/src/importers/CliEventApiImporter.ts @@ -124,7 +124,7 @@ export class CliEventApiImporter extends CliAssetsImporter { // get latest version as reference const latestExistingEventApiVersionObjectBefore: EventApiVersion | undefined = await EpSdkEventApiVersionsService.getLatestVersionForEventApiName({ applicationDomainId: applicationDomainId, - eventApiName: epAsyncApiDocument.getEpEventApiName(), + eventApiName: epAsyncApiDocument.getEpApiName(), }); // const latestExistingEventApiVersionString: string | undefined = latestExistingEventApiVersionObjectBefore?.version; // get the list of pub and sub events @@ -147,7 +147,7 @@ export class CliEventApiImporter extends CliAssetsImporter { versionStrategy: EEpSdk_VersionTaskStrategy.EXACT_VERSION, eventApiVersionSettings: { description: epAsyncApiDocument.getDescription(), - displayName: epAsyncApiDocument.getEpEventApiVersionName(), + displayName: epAsyncApiDocument.getEpApiVersionName(), producedEventVersionIds: cliPubSubEventVersionIds.publishEventVersionIdList, consumedEventVersionIds: cliPubSubEventVersionIds.subscribeEventVersionIdList, stateId: this.get_EpSdkTask_StateId(), @@ -177,7 +177,7 @@ export class CliEventApiImporter extends CliAssetsImporter { if (latestExistingEventApiVersionObjectBefore === undefined) throw new CliInternalCodeInconsistencyError(logName, { message: "latestExistingEventApiVersionObjectBefore === undefined", applicationDomainId: applicationDomainId, - applicationName: epAsyncApiDocument.getEpApplicationName(), + eventApiName: epAsyncApiDocument.getEpApiName(), }); if (CliRunContext.get().runMode === ECliRunContext_RunMode.RELEASE) { // create event api version and issue warning @@ -189,7 +189,7 @@ export class CliEventApiImporter extends CliAssetsImporter { versionStrategy: EEpSdk_VersionTaskStrategy.BUMP_PATCH, eventApiVersionSettings: { description: epAsyncApiDocument.getDescription(), - displayName: epAsyncApiDocument.getEpEventApiVersionName(), + displayName: epAsyncApiDocument.getEpApiVersionName(), producedEventVersionIds: cliPubSubEventVersionIds.publishEventVersionIdList, consumedEventVersionIds: cliPubSubEventVersionIds.subscribeEventVersionIdList, // stateId: CliEPStatesService.getTargetLifecycleState({cliAssetImport_TargetLifecycleState: ECliAssetImport_TargetLifecycleState.DRAFT }), @@ -243,7 +243,7 @@ export class CliEventApiImporter extends CliAssetsImporter { }); throw new CliImporterTestRunAssetsInconsistencyError(logName, { applicationDomainName: epAsyncApiDocument.getApplicationDomainName(), - eventApiName: epAsyncApiDocument.getEpEventApiName(), + eventApiName: epAsyncApiDocument.getEpApiName(), requestedUpdates: requestedUpdates, latestExistingEventApiVersionObjectBefore: latestExistingEventApiVersionObjectBefore, epSdkEventApiVersionTask_ExecuteReturn: epSdkEventApiVersionTask_ExecuteReturn_Check, @@ -259,7 +259,7 @@ export class CliEventApiImporter extends CliAssetsImporter { versionStrategy: EEpSdk_VersionTaskStrategy.EXACT_VERSION, eventApiVersionSettings: { description: epAsyncApiDocument.getDescription(), - displayName: epAsyncApiDocument.getEpEventApiVersionName(), + displayName: epAsyncApiDocument.getEpApiVersionName(), producedEventVersionIds: cliPubSubEventVersionIds.publishEventVersionIdList, consumedEventVersionIds: cliPubSubEventVersionIds.subscribeEventVersionIdList, stateId: this.get_EpSdkTask_StateId(), @@ -309,7 +309,7 @@ export class CliEventApiImporter extends CliAssetsImporter { const epSdkEventApiTask = new EpSdkEventApiTask({ epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, applicationDomainId: applicationDomainId, - eventApiName: epAsyncApiDocument.getEpEventApiName(), + eventApiName: epAsyncApiDocument.getEpApiName(), eventApiObjectSettings: { shared: true, brokerType: epAsyncApiDocument.getBrokerType() as unknown as EventApi.brokerType, @@ -350,7 +350,7 @@ export class CliEventApiImporter extends CliAssetsImporter { const funcName = "run_present"; const logName = `${CliEventApiImporter.name}.${funcName}()`; - const apiTitle: string = cliImporterRunPresentOptions.epAsyncApiDocument.getEpEventApiName(); + const apiTitle: string = cliImporterRunPresentOptions.epAsyncApiDocument.getEpApiName(); const apiVersion: string = cliImporterRunPresentOptions.epAsyncApiDocument.getVersion(); const apiBrokerType: string = cliImporterRunPresentOptions.epAsyncApiDocument.getBrokerType(); const epApplicationDomainName: string = cliImporterRunPresentOptions.epAsyncApiDocument.getApplicationDomainName(); @@ -481,7 +481,7 @@ export class CliEventApiImporter extends CliAssetsImporter { CliUtils.convertStringToFilePath( epAsyncApiDocument.getApplicationDomainName() ); - const apiTitleAsFilePath = epAsyncApiDocument.getEpEventApiNameAsFilePath(); + const apiTitleAsFilePath = epAsyncApiDocument.getEpApiNameAsFilePath(); const assetOutputRootDir: string = CliUtils.ensureDirExists( this.cliImporterOptions.assetOutputDir, applicationDomainNameAsFilePath + "/" + apiTitleAsFilePath @@ -490,8 +490,8 @@ export class CliEventApiImporter extends CliAssetsImporter { assetOutputRootDir, "schemas" ); - const asyncApiSpecFileNameJson = assetOutputRootDir + "/" + epAsyncApiDocument.getEpEventApiNameAsFileName("json"); - const asyncApiSpecFileNameYaml = assetOutputRootDir + "/" + epAsyncApiDocument.getEpEventApiNameAsFileName("yml"); + const asyncApiSpecFileNameJson = assetOutputRootDir + "/" + epAsyncApiDocument.getEpApiNameAsFileName("json"); + const asyncApiSpecFileNameYaml = assetOutputRootDir + "/" + epAsyncApiDocument.getEpApiNameAsFileName("yml"); CliLogger.trace(CliLogger.createLogEntry(logName, { code: ECliStatusCodes.GENERATING_ASSETS_OUTPUT, details: { applicationDomainNameAsFilePath: applicationDomainNameAsFilePath, apiTitleAsFilePath: apiTitleAsFilePath, @@ -508,7 +508,7 @@ export class CliEventApiImporter extends CliAssetsImporter { CliRunSummary.generatingApiOutput({ cliRunSummary_GenerateApiOutput: { type: ECliRunSummary_Type.ApiOutput, - apiName: epAsyncApiDocument.getEpEventApiName(), + apiName: epAsyncApiDocument.getEpApiName(), apiVersion: epAsyncApiDocument.getVersion(), outputDir: assetOutputRootDir, }}); @@ -621,7 +621,7 @@ export class CliEventApiImporter extends CliAssetsImporter { overrideChannelDelimiter: cliImporterRunOptions.overrideChannelDelimiter, validateBestPractices: this.cliImporterOptions.cliValidateApiSpecBestPractices, }); - cliEventApiImporterRunImportReturn.apiTitle = epAsyncApiDocument.getEpEventApiName(); + cliEventApiImporterRunImportReturn.apiTitle = epAsyncApiDocument.getEpApiName(); cliEventApiImporterRunImportReturn.applicationDomainName = epAsyncApiDocument.getApplicationDomainName(); cliEventApiImporterRunImportReturn.assetApplicationDomainName = epAsyncApiDocument.getAssetsApplicationDomainName(); diff --git a/packages/ep-async-api-importer/test/specs/ep-idempotency.x-spec.ts b/packages/ep-async-api-importer/test/specs/ep-idempotency.x-spec.ts index 6a2d03995..58e706e0c 100644 --- a/packages/ep-async-api-importer/test/specs/ep-idempotency.x-spec.ts +++ b/packages/ep-async-api-importer/test/specs/ep-idempotency.x-spec.ts @@ -3,6 +3,7 @@ import { expect } from "chai"; import path from "path"; import { ApiError, + ApplicationsService, EventApi, EventApIsService, } from "@solace-labs/ep-openapi-node"; @@ -121,8 +122,10 @@ let CopiedEventApi_Id: string | undefined; let App_Name: string; let App_Id: string | undefined; let AppVersion_Id: string | undefined; +let AppApiSpec: any; -let AsyncApiSpecFileNameJson: string; +let EventApiAsyncApiSpecFileNameJson: string; +let AppAsyncApiSpecFileNameJson: string; const initializeGlobals = () => { ApplicationDomain_Name = `${TestConfig.getAppId()}/${TestSpecName}`; @@ -164,6 +167,7 @@ describe(`${scriptName}`, () => { after(async () => { TestContext.newItId(); + // await applicationDomainTasks(EEpSdkTask_TargetState.ABSENT); }); it(`${scriptName}: should setup the domains`, async () => { @@ -427,7 +431,107 @@ describe(`${scriptName}`, () => { } }); - it(`${scriptName}: should get the event api spec`, async () => { + it(`${scriptName}: should get the application version api spec`, async () => { + try { + AppApiSpec = await ApplicationsService.getAsyncApiForApplicationVersion({ + applicationVersionId: AppVersion_Id + }) + // console.log(`AppApiSpec = ${JSON.stringify(AppApiSpec, null, 2)}`); + } catch (e) { + if (e instanceof ApiError) expect(false, TestLogger.createApiTestFailMessage("failed")).to.be.true; + expect(e instanceof EpSdkError, TestLogger.createNotEpSdkErrorMessage(e)).to.be.true; + expect(false, TestLogger.createEpSdkTestFailMessage("failed", e)).to.be.true; + } + }); + + it(`${scriptName}: should parse the application version api spec and save it to file`, async () => { + try { + const epAsyncApiDocument: EpAsyncApiDocument = await EpAsyncApiDocumentService.createFromAny({ + anySpec: AppApiSpec + }); + const applicationDomainName = epAsyncApiDocument.getApplicationDomainName(); + const assetsApplicationDomainName = epAsyncApiDocument.getAssetsApplicationDomainName(); + + AppAsyncApiSpecFileNameJson = TestConfig.getConfig().tmpDir + "/" + epAsyncApiDocument.getEpApiNameAsFileName("json"); + CliUtils.saveContents2File({ + filePath: AppAsyncApiSpecFileNameJson, + content: JSON.stringify(epAsyncApiDocument.getOriginalSpecAsJson(), null, 2 ), + }); + } catch (e) { + if (e instanceof ApiError) expect(false, TestLogger.createApiTestFailMessage("failed")).to.be.true; + expect(e instanceof EpSdkError, TestLogger.createNotEpSdkErrorMessage(e)).to.be.true; + expect(false, TestLogger.createEpSdkTestFailMessage("failed", e)).to.be.true; + } + }); + + it(`${scriptName}: should import application api spec`, async () => { + try { + CliConfig.getCliImporterManagerOptions().asyncApiFileList = [AppAsyncApiSpecFileNameJson]; + CliConfig.getCliImporterManagerOptions().cliImporterManagerMode = ECliImporterManagerMode.RELEASE_MODE; + CliConfig.getCliImporterManagerOptions().cliTestSetupDomainsForApis = true; + // CliConfig.getCliImporterManagerOptions().runId = scriptName; + // // DEBUG + // CliConfig.getCliImporterManagerOptions().cliImporterManagerMode = ECliImporterManagerMode.TEST_MODE_KEEP; + // CliConfig.getCliImporterManagerOptions().applicationDomainName = 'release_mode'; + CliConfig.getCliImporterManagerOptions().createEventApiApplication = true; + CliConfig.getCliImporterManagerOptions().cliImporterOptions.cliAssetImport_BrokerType = undefined; + CliConfig.getCliImporterManagerOptions().cliImporterOptions.cliAssetImport_ChannelDelimiter = undefined; + CliConfig.getCliImporterManagerOptions().cliImporterOptions.cliValidateApiSpecBestPractices = true; + CliConfig.getCliImporterManagerOptions().cliImporterOptions.cliAssetImport_TargetVersionStrategy = ECliAssetImport_TargetVersionStrategy.BUMP_PATCH; + + const cliImporter = new CliImporterManager(CliConfig.getCliImporterManagerOptions()); + const xvoid: void = await cliImporter.run(); + // // DEBUG + expect(false, 'check app import ok').to.be.true; + // const cliRunSummaryList: Array = CliRunSummary.getSummaryLogList(); + // expect(false, JSON.stringify(cliRunSummaryList, null, 2)).to.be.true; + } catch (e) { + TestLogger.logMessageWithId(TestLogger.createTestFailMessageForError('error', e)); + expect( e instanceof CliError, TestLogger.createNotCliErrorMesssage(e.message)).to.be.true; + expect(false, TestLogger.createTestFailMessageWithCliError("failed", e)).to.be.true; + if (e instanceof ApiError) expect(false, TestLogger.createApiTestFailMessage("failed")).to.be.true; + expect(e instanceof EpSdkError, TestLogger.createNotEpSdkErrorMessage(e)).to.be.true; + expect(false, TestLogger.createEpSdkTestFailMessage("failed", e)).to.be.true; + } + }); + + it(`${scriptName}: continue here`, async () => { + expect(false, 'continue here').to.be.true; + }); + + it(`${scriptName}: should check no new version created for application`, async () => { + + expect(false, 'continue here').to.be.true; + + try { + // TODO: write the correct checks + const enum_1_id_versions = await EpSdkEnumVersionsService.getVersionsForEnumId({enumId: Enum_1_Id}); + expect(enum_1_id_versions.length,'enum_1_id_versions.length not 1').to.equal(1); + const enum_2_id_versions = await EpSdkEnumVersionsService.getVersionsForEnumId({enumId: Enum_2_Id}); + expect(enum_2_id_versions.length,'enum_2_id_versions.length not 1').to.equal(1); + + const schema_1_id_versions = await EpSdkSchemaVersionsService.getVersionsForSchemaId({ schemaId: Schema_1_Id }); + expect(schema_1_id_versions.length,'schema_1_id_versions.length not 1').to.equal(1); + const schema_2_id_versions = await EpSdkSchemaVersionsService.getVersionsForSchemaId({ schemaId: Schema_2_Id }); + expect(schema_2_id_versions.length,'schema_2_id_versions.length not 1').to.equal(1); + + const event_1_id_versions = await EpSdkEpEventVersionsService.getVersionsForEventId({ eventId: Event_1_Id }); + expect(event_1_id_versions.length,'event_1_id_versions.length not 1').to.equal(1); + const event_2_id_versions = await EpSdkEpEventVersionsService.getVersionsForEventId({ eventId: Event_2_Id }); + expect(event_2_id_versions.length,'event_2_id_versions.length not 1').to.equal(1); + + const event_api_versions = await EpSdkEventApiVersionsService.getVersionsForEventApiId({ eventApiId: EventApi_Id }); + expect(event_api_versions.length,'event_api_versions.length not 1').to.equal(1); + + } catch (e) { + TestLogger.logMessageWithId(TestLogger.createTestFailMessageForError('error', e)); + if (e instanceof ApiError) expect(false, TestLogger.createApiTestFailMessage("failed")).to.be.true; + expect(e instanceof EpSdkError, TestLogger.createNotEpSdkErrorMessage(e)).to.be.true; + expect(false, TestLogger.createEpSdkTestFailMessage("failed", e)).to.be.true; + } + }); + + it(`${scriptName}: should get the event api version spec`, async () => { try { EventApiSpec = await EventApIsService.getAsyncApiForEventApiVersion({ eventApiVersionId: EventApiVersion_Id, @@ -448,9 +552,9 @@ describe(`${scriptName}`, () => { const applicationDomainName = epAsyncApiDocument.getApplicationDomainName(); const assetsApplicationDomainName = epAsyncApiDocument.getAssetsApplicationDomainName(); - AsyncApiSpecFileNameJson = TestConfig.getConfig().tmpDir + "/" + epAsyncApiDocument.getTitleAsFileName("json"); + EventApiAsyncApiSpecFileNameJson = TestConfig.getConfig().tmpDir + "/" + epAsyncApiDocument.getEpApiNameAsFileName("json"); CliUtils.saveContents2File({ - filePath: AsyncApiSpecFileNameJson, + filePath: EventApiAsyncApiSpecFileNameJson, content: JSON.stringify(epAsyncApiDocument.getOriginalSpecAsJson(), null, 2 ), }); } catch (e) { @@ -462,14 +566,14 @@ describe(`${scriptName}`, () => { it(`${scriptName}: should import event api spec`, async () => { try { - CliConfig.getCliImporterManagerOptions().asyncApiFileList = [AsyncApiSpecFileNameJson]; + CliConfig.getCliImporterManagerOptions().asyncApiFileList = [EventApiAsyncApiSpecFileNameJson]; CliConfig.getCliImporterManagerOptions().cliImporterManagerMode = ECliImporterManagerMode.RELEASE_MODE; CliConfig.getCliImporterManagerOptions().cliTestSetupDomainsForApis = true; // CliConfig.getCliImporterManagerOptions().runId = scriptName; // // DEBUG // CliConfig.getCliImporterManagerOptions().cliImporterManagerMode = ECliImporterManagerMode.TEST_MODE_KEEP; // CliConfig.getCliImporterManagerOptions().applicationDomainName = 'release_mode'; - CliConfig.getCliImporterManagerOptions().createEventApiApplication = true; + CliConfig.getCliImporterManagerOptions().createEventApiApplication = false; CliConfig.getCliImporterManagerOptions().cliImporterOptions.cliAssetImport_BrokerType = undefined; CliConfig.getCliImporterManagerOptions().cliImporterOptions.cliAssetImport_ChannelDelimiter = undefined; CliConfig.getCliImporterManagerOptions().cliImporterOptions.cliValidateApiSpecBestPractices = true; @@ -490,7 +594,7 @@ describe(`${scriptName}`, () => { } }); - it(`${scriptName}: should check no new version created`, async () => { + it(`${scriptName}: should check no new version created for event api`, async () => { try { const enum_1_id_versions = await EpSdkEnumVersionsService.getVersionsForEnumId({enumId: Enum_1_Id}); expect(enum_1_id_versions.length,'enum_1_id_versions.length not 1').to.equal(1); diff --git a/packages/ep-asyncapi/src/documents/EpAsyncApiDocument.ts b/packages/ep-asyncapi/src/documents/EpAsyncApiDocument.ts index c12234c4e..ef92c1a30 100644 --- a/packages/ep-asyncapi/src/documents/EpAsyncApiDocument.ts +++ b/packages/ep-asyncapi/src/documents/EpAsyncApiDocument.ts @@ -83,8 +83,8 @@ export class EpAsyncApiDocument { private overrideBrokerType: string | undefined; private channelDelimiter: EChannelDelimiters; private overrideChannelDelimiter: string | undefined; - private epEventApiName: string; - private epEventApiVersionName?: string; + private epApiName: string; + private epApiVersionName?: string; private getJSON(asyncApiDocument: AsyncAPIDocument): any { const funcName = "getJSON"; @@ -177,15 +177,15 @@ export class EpAsyncApiDocument { if(channelDelimiter === undefined) channelDelimiter = EpAsyncApiDocument.DefaultChannelDelimiter; return channelDelimiter as EChannelDelimiters; } - private createEpEventApiName(): string { - if(this.epEventApiName !== undefined) return this.epEventApiName; + private createEpApiName(): string { + if(this.epApiName !== undefined) return this.epApiName; return this.getTitle(); } - private createEpEventApiVersionName(): string { + private createEpApiVersionName(): string { if(!this.asyncApiDocument.info()) return ''; if(this.asyncApiDocument.info().hasExtension(EpApiInfoExtensions.xEpApiInfoVersionDisplayName)) { - const eventApiDisplayName = this.asyncApiDocument.info().extension(EpApiInfoExtensions.xEpApiInfoVersionDisplayName); - if(eventApiDisplayName && eventApiDisplayName.length > 0) return eventApiDisplayName; + const epApiDisplayName = this.asyncApiDocument.info().extension(EpApiInfoExtensions.xEpApiInfoVersionDisplayName); + if(epApiDisplayName && epApiDisplayName.length > 0) return epApiDisplayName; } // set to empty for better logging return ''; @@ -245,39 +245,39 @@ export class EpAsyncApiDocument { this.overrideChannelDelimiter = overrideChannelDelimiter; this.brokerType = this.createBrokerType(); this.channelDelimiter = this.createChannelDelimiter(); - this.epEventApiName = this.createEpEventApiName(); - this.epEventApiVersionName = this.createEpEventApiVersionName(); + this.epApiName = this.createEpApiName(); + this.epApiVersionName = this.createEpApiVersionName(); } - private validateEpEventApiName = () => { - const funcName = "validateEpEventApiName"; + private validateEpApiName = () => { + const funcName = "validateEpApiName"; const logName = `${EpAsyncApiDocument.name}.${funcName}()`; - const eventApiName = this.epEventApiName || this.createEpEventApiName(); + const epApiName = this.epApiName || this.createEpApiName(); const schema = $EventApi.properties.name; const v: Validator = new Validator(); - const validateResult: ValidatorResult = v.validate(eventApiName, schema); + const validateResult: ValidatorResult = v.validate(epApiName, schema); if (!validateResult.valid) throw new EpAsyncApiValidationError(logName,this.constructor.name,undefined,{ asyncApiSpecTitle: this.getTitle(), issues: validateResult.errors, value: { - epEventApiName: this.epEventApiName, + epApiName: this.epApiName, } }); }; - private validateEpEventApiVersionName = () => { - const funcName = "validateEpEventApiVersionName"; + private validateEpApiVersionName = () => { + const funcName = "validateEpApiVersionName"; const logName = `${EpAsyncApiDocument.name}.${funcName}()`; - const eventApiVersionName = this.epEventApiVersionName || this.createEpEventApiVersionName(); - if(eventApiVersionName === undefined) throw new EpAsyncApiInternalError(logName, this.constructor.name, 'eventApiVersionName === undefined'); + const epApiVersionName = this.epApiVersionName || this.createEpApiVersionName(); + if(epApiVersionName === undefined) throw new EpAsyncApiInternalError(logName, this.constructor.name, 'epApiVersionName === undefined'); const schema = $EventApiVersion.properties.displayName; const v: Validator = new Validator(); - const validateResult: ValidatorResult = v.validate(eventApiVersionName, schema); + const validateResult: ValidatorResult = v.validate(epApiVersionName, schema); if (!validateResult.valid) throw new EpAsyncApiValidationError(logName,this.constructor.name,undefined,{ asyncApiSpecTitle: this.getTitle(), issues: validateResult.errors, value: { - epEventApiVersionName: this.epEventApiVersionName, + epApiVersionName: this.epApiVersionName, }, }); }; @@ -326,8 +326,8 @@ export class EpAsyncApiDocument { public validate(): void { // this doc this.validate_VersionIsSemVerFormat(); - this.validateEpEventApiName(); - this.validateEpEventApiVersionName(); + this.validateEpApiName(); + this.validateEpApiVersionName(); this.validate_BrokerType(); this.validate_ChannelDelimiter(); // cascade validation to all elements @@ -394,30 +394,38 @@ export class EpAsyncApiDocument { public getChannelDelimiter(): EChannelDelimiters { return this.channelDelimiter; } - public getEpEventApiName(): string { return this.epEventApiName; } + public getEpApiName(): string { return this.epApiName; } - public getEpEventApiNameAsFilePath(): string { - return this.getEpEventApiName().replaceAll(/[^0-9a-zA-Z]+/g, "-"); + public getEpApiNameAsFilePath(): string { + return this.getEpApiName().replaceAll(/[^0-9a-zA-Z]+/g, "-"); } - public getEpEventApiNameAsFileName(ext: string): string { - return `${this.getEpEventApiNameAsFilePath()}.${ext}`; + public getEpApiNameAsFileName(ext: string): string { + return `${this.getEpApiNameAsFilePath()}.${ext}`; } - public getEpEventApiVersionName(): string { - if(this.epEventApiVersionName === undefined) return ''; - return this.epEventApiVersionName; + public getEpApiVersionName(): string { + if(this.epApiVersionName === undefined) return ''; + return this.epApiVersionName; } - public getEpApplicationName(): string { - // TODO: needs its own property, different create algo - return this.getEpEventApiName(); - } + // public getEpApplicationName(): string { + // // TODO: needs its own property, different create algo + // return this.getEpEventApiName(); + // } - public getEpApplicationVersionName(): string { - // TODO: needs its own property, different create algo - return this.getEpEventApiVersionName(); - } + // public getEpApplicationVersionName(): string { + // // TODO: needs its own property, different create algo + // return this.getEpEventApiVersionName(); + // } + + // public getEpApplicationNameAsFilePath(): string { + // return this.getEpApplicationName().replaceAll(/[^0-9a-zA-Z]+/g, "-"); + // } + + // public getEpApplicationNameAsFileName(ext: string): string { + // return `${this.getEpApplicationNameAsFilePath()}.${ext}`; + // } public getAsJson(): any { return this.asyncApiDocumentJson; } From 713e807f99ca06b3f4ec8b5df10ceb5bed8dab50 Mon Sep 17 00:00:00 2001 From: Ricardo Gomez_Ulmke Date: Mon, 13 Mar 2023 13:41:11 +0100 Subject: [PATCH 29/33] test --- .../ep-asyncapi/test/specs/unit/EpAsyncApiDocument.spec.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/ep-asyncapi/test/specs/unit/EpAsyncApiDocument.spec.ts b/packages/ep-asyncapi/test/specs/unit/EpAsyncApiDocument.spec.ts index 92136d54f..7cc832dc1 100644 --- a/packages/ep-asyncapi/test/specs/unit/EpAsyncApiDocument.spec.ts +++ b/packages/ep-asyncapi/test/specs/unit/EpAsyncApiDocument.spec.ts @@ -60,11 +60,11 @@ describe(`${scriptName}`, () => { expect(title, 'failed').to.eq(Global_Title); const expected_titleAsFilePath = "slash-amp-star-quotes-"; - const titleAsFilePath = Global_EpAsyncApiDocument.getEpEventApiNameAsFilePath(); + const titleAsFilePath = Global_EpAsyncApiDocument.getEpApiNameAsFilePath(); expect(titleAsFilePath, 'failed').to.eq(expected_titleAsFilePath); const expected_titleAsFileName = expected_titleAsFilePath + ".yml"; - const titleAsFileName = Global_EpAsyncApiDocument.getEpEventApiNameAsFileName('yml'); + const titleAsFileName = Global_EpAsyncApiDocument.getEpApiNameAsFileName('yml'); expect(titleAsFileName, 'failed').to.eq(expected_titleAsFileName); }); From 74d6943202676b6f8184636f7e78f3263501c210 Mon Sep 17 00:00:00 2001 From: Ricardo Gomez_Ulmke Date: Mon, 13 Mar 2023 13:49:40 +0100 Subject: [PATCH 30/33] tests --- .../src/cli-components/CliConfig.ts | 15 ++- .../src/cli-components/CliImporterManager.ts | 102 +++++++----------- .../src/cli-components/CliLogger.ts | 1 + .../src/importers/CliEventApiImporter.ts | 58 +++++----- .../test/specs/ep-idempotency.x-spec.ts | 24 ++--- .../test/specs/test-fail/test-fail.spec.ts | 2 +- 6 files changed, 92 insertions(+), 110 deletions(-) diff --git a/packages/ep-async-api-importer/src/cli-components/CliConfig.ts b/packages/ep-async-api-importer/src/cli-components/CliConfig.ts index 8d6e56e54..c19300386 100644 --- a/packages/ep-async-api-importer/src/cli-components/CliConfig.ts +++ b/packages/ep-async-api-importer/src/cli-components/CliConfig.ts @@ -78,6 +78,7 @@ enum ECliConfigEnvVarNames { CLI_IMPORT_ASSETS_TARGET_VERSION_STRATEGY = "CLI_IMPORT_ASSETS_TARGET_VERSION_STRATEGY", CLI_IMPORT_ASSETS_OUTPUT_DIR = "CLI_IMPORT_ASSETS_OUTPUT_DIR", CLI_IMPORT_CREATE_API_APPLICATION = "CLI_IMPORT_CREATE_API_APPLICATION", + CLI_IMPORT_CREATE_API_EVENT_API = "CLI_IMPORT_CREATE_API_EVENT_API", CLI_IMPORT_BROKER_TYPE = "CLI_IMPORT_BROKER_TYPE", CLI_IMPORT_CHANNEL_DELIMITER = "CLI_IMPORT_CHANNEL_DELIMITER", CLI_TEST_SETUP_DOMAINS_FOR_APIS = "CLI_TEST_SETUP_DOMAINS_FOR_APIS", @@ -101,6 +102,7 @@ const DEFAULT_CLI_IMPORT_ASSETS_TARGET_LIFECYLE_STATE = ECliAssetImport_TargetLi const DEFAULT_CLI_IMPORT_ASSETS_TARGET_VERSION_STRATEGY = ECliAssetImport_TargetVersionStrategy.BUMP_PATCH; const DEFAULT_CLI_IMPORT_ASSET_OUTPUT_DIR = "./tmp/output"; const DEFAULT_CLI_IMPORT_CREATE_API_APPLICATION = false; +const DEFAULT_CLI_IMPORT_CREATE_API_EVENT_API = true; const DEFAULT_CLI_TEST_SETUP_DOMAINS_FOR_APIS = false; const DEFAULT_CLI_VALIDATE_API_BEST_PRACTICES = true; @@ -217,12 +219,18 @@ const CliConfigEnvVarConfigList: Array = [ }, { envVarName: ECliConfigEnvVarNames.CLI_IMPORT_CREATE_API_APPLICATION, - description: - "Flag to create also an application representing the Event API.", + description: "Flag to create an Event Portal Application representing the API Spec.", required: false, default: String(DEFAULT_CLI_IMPORT_CREATE_API_APPLICATION), options: Object.values(ECliConfigBooleanOptions), }, + { + envVarName: ECliConfigEnvVarNames.CLI_IMPORT_CREATE_API_EVENT_API, + description: "Flag to create an Event Portal Event API representing the API Spec.", + required: false, + default: String(DEFAULT_CLI_IMPORT_CREATE_API_EVENT_API), + options: Object.values(ECliConfigBooleanOptions), + }, { envVarName: ECliConfigEnvVarNames.CLI_IMPORT_BROKER_TYPE, description: `The broker type setting for all imported objects. Overrides broker type specified in the spec, extension: ${E_EpAsyncApiExtensions.X_EP_BROKER_TYPE}`, @@ -499,7 +507,8 @@ class CliConfig { cliImporterManagerMode: this.getOptionalEnvVarValueAsString_From_Options_WithDefault(ECliConfigEnvVarNames.CLI_MODE, Object.values(ECliImporterManagerMode), DEFAULT_CLI_MODE) as ECliImporterManagerMode, applicationDomainName: applicationDomainName, assetApplicationDomainName: assetApplicationDomainName, - createEventApiApplication: this.getOptionalEnvVarValueAsBoolean_WithDefault(ECliConfigEnvVarNames.CLI_IMPORT_CREATE_API_APPLICATION, DEFAULT_CLI_IMPORT_CREATE_API_APPLICATION), + createApiApplication: this.getOptionalEnvVarValueAsBoolean_WithDefault(ECliConfigEnvVarNames.CLI_IMPORT_CREATE_API_APPLICATION, DEFAULT_CLI_IMPORT_CREATE_API_APPLICATION), + createApiEventApi: this.getOptionalEnvVarValueAsBoolean_WithDefault(ECliConfigEnvVarNames.CLI_IMPORT_CREATE_API_EVENT_API, DEFAULT_CLI_IMPORT_CREATE_API_EVENT_API), cliTestSetupDomainsForApis: this.getOptionalEnvVarValueAsBoolean_WithDefault(ECliConfigEnvVarNames.CLI_TEST_SETUP_DOMAINS_FOR_APIS, DEFAULT_CLI_TEST_SETUP_DOMAINS_FOR_APIS), cliImporterOptions: { runId: runId, diff --git a/packages/ep-async-api-importer/src/cli-components/CliImporterManager.ts b/packages/ep-async-api-importer/src/cli-components/CliImporterManager.ts index 1512e6932..a985e56bf 100644 --- a/packages/ep-async-api-importer/src/cli-components/CliImporterManager.ts +++ b/packages/ep-async-api-importer/src/cli-components/CliImporterManager.ts @@ -1,4 +1,5 @@ import { EpAsyncApiDocument } from "@solace-labs/ep-asyncapi"; +import { EEpSdkTask_TargetState, EpSdkEventApisService, EpSdkEventApiTask } from "@solace-labs/ep-sdk"; import { CliApplicationImporter, ICliApplicationImporterRunReturn, @@ -45,7 +46,8 @@ export interface ICliImporterManagerOptions { applicationDomainName?: string; assetApplicationDomainName?: string; cliImporterOptions: ICliImporterOptions; - createEventApiApplication: boolean; + createApiApplication: boolean; + createApiEventApi: boolean; cliTestSetupDomainsForApis: boolean; } @@ -56,10 +58,7 @@ export class CliImporterManager { this.cliImporterManagerOptions = cliImporterManagerOptions; } - private static createApplicationDomainPrefix4TestMode({ - appName, - runId, - }: { + private static createApplicationDomainPrefix4TestMode({appName, runId }: { appName: string; runId: string; }): string { @@ -78,20 +77,13 @@ export class CliImporterManager { const funcName = "setup_test_domains"; const logName = `${CliImporterManager.name}.${funcName}()`; - const rctxt: ICliSetupTestDomainsContext = { - runProcess: "setUpTestDomains", - }; + const rctxt: ICliSetupTestDomainsContext = { runProcess: "setUpTestDomains" }; CliRunContext.push(rctxt); - CliRunSummary.setUpTestDomains({ - cliRunSummary_SetupTestDomains: { - type: ECliRunSummary_Type.SetupTestDomains, - }, - }); + CliRunSummary.setUpTestDomains({cliRunSummary_SetupTestDomains: { type: ECliRunSummary_Type.SetupTestDomains }}); // clean application domains before test - let xvoid: void = - await CliApplicationDomainsService.absent_ApplicationDomains({ - applicationDomainNameList: applicationDomainNameList, - }); + let xvoid: void = await CliApplicationDomainsService.absent_ApplicationDomains({ + applicationDomainNameList: applicationDomainNameList, + }); xvoid = await CliApplicationDomainsService.absent_ApplicationDomains({ applicationDomainNameList: assetApplicationDomainNameList, }); @@ -101,14 +93,10 @@ export class CliImporterManager { if (this.cliImporterManagerOptions.cliTestSetupDomainsForApis) { // copy existing source event apis from source to target test domain(s) for (const epAsyncApiDocument of epAsyncApiDocumentList) { - const fromApplicationDomainName = - epAsyncApiDocument.getUnprefixedApplicationDomainName(); - const toApplicationDomainName = - epAsyncApiDocument.getApplicationDomainName(); - const fromAssetsApplicationDomainName = - epAsyncApiDocument.getUnprefixedAssetsApplicationDomainName(); - const toAssetsApplicationDomainName = - epAsyncApiDocument.getAssetsApplicationDomainName(); + const fromApplicationDomainName = epAsyncApiDocument.getUnprefixedApplicationDomainName(); + const toApplicationDomainName = epAsyncApiDocument.getApplicationDomainName(); + const fromAssetsApplicationDomainName = epAsyncApiDocument.getUnprefixedAssetsApplicationDomainName(); + const toAssetsApplicationDomainName = epAsyncApiDocument.getAssetsApplicationDomainName(); const rctxt: ICliSetupTestApiRunContext = { apiTitle: epAsyncApiDocument.getTitle(), @@ -125,30 +113,22 @@ export class CliImporterManager { }, }); - const copied: boolean = - await CliEventApisService.deepCopyLatestEventApiVersion({ - epAsyncApiDocument: epAsyncApiDocument, - }); + const copied: boolean = await CliEventApisService.deepCopyLatestEventApiVersion({ + epAsyncApiDocument: epAsyncApiDocument, + }); let loggerCode = ""; if (copied) { - loggerCode = - ECliStatusCodes.SETUP_TEST_DOMAIN_EVENT_API_VERSION_COPIED; + loggerCode = ECliStatusCodes.SETUP_TEST_DOMAIN_EVENT_API_VERSION_COPIED; } else { - loggerCode = - ECliStatusCodes.SETUP_TEST_DOMAIN_EVENT_API_VERSION_COPY_SKIPPED; + loggerCode = ECliStatusCodes.SETUP_TEST_DOMAIN_EVENT_API_VERSION_COPY_SKIPPED; } - CliLogger.info( - CliLogger.createLogEntry(logName, { - code: loggerCode, - details: { - apiTitle: epAsyncApiDocument.getTitle(), - fromApplicationDomainName: fromApplicationDomainName, - toApplicationDomainName: toApplicationDomainName, - fromAssetsApplicationDomainName: fromAssetsApplicationDomainName, - toAssetsApplicationDomainName: toAssetsApplicationDomainName, - }, - }) - ); + CliLogger.info(CliLogger.createLogEntry(logName, {code: loggerCode, details: { + apiTitle: epAsyncApiDocument.getTitle(), + fromApplicationDomainName: fromApplicationDomainName, + toApplicationDomainName: toApplicationDomainName, + fromAssetsApplicationDomainName: fromAssetsApplicationDomainName, + toAssetsApplicationDomainName: toAssetsApplicationDomainName, + }})); CliRunContext.pop(); } } @@ -235,16 +215,16 @@ export class CliImporterManager { checkmode: false, generateAssetsOutput: false, overrideBrokerType: this.cliImporterManagerOptions.cliImporterOptions.cliAssetImport_BrokerType, - overrideChannelDelimiter: this.cliImporterManagerOptions.cliImporterOptions.cliAssetImport_ChannelDelimiter + overrideChannelDelimiter: this.cliImporterManagerOptions.cliImporterOptions.cliAssetImport_ChannelDelimiter, + deleteEventApiAfter: false }}); if (cliEventApiImporterRunReturn.error !== undefined) throw cliEventApiImporterRunReturn.error; if (cliEventApiImporterRunReturn.applicationDomainName === undefined) throw new CliInternalCodeInconsistencyError(logName, "cliEventApiImporterRunReturn.applicationDomainName === undefined"); // create application - if (this.cliImporterManagerOptions.createEventApiApplication) { + if (this.cliImporterManagerOptions.createApiApplication) { const cliApplicationImporter = new CliApplicationImporter({ ...this.cliImporterManagerOptions.cliImporterOptions, - applicationDomainName: - cliEventApiImporterRunReturn.applicationDomainName, + applicationDomainName: cliEventApiImporterRunReturn.applicationDomainName, }); const cliApplicationImporterRunReturn: ICliApplicationImporterRunReturn = await cliApplicationImporter.run({ cliImporterRunOptions: { apiFile: asyncApiFile, @@ -299,7 +279,8 @@ export class CliImporterManager { checkmode: true, generateAssetsOutput: false, overrideBrokerType: this.cliImporterManagerOptions.cliImporterOptions.cliAssetImport_BrokerType, - overrideChannelDelimiter: this.cliImporterManagerOptions.cliImporterOptions.cliAssetImport_ChannelDelimiter + overrideChannelDelimiter: this.cliImporterManagerOptions.cliImporterOptions.cliAssetImport_ChannelDelimiter, + deleteEventApiAfter: false }}); if (cliEventApiImporterRunReturn.error !== undefined) throw cliEventApiImporterRunReturn.error; @@ -309,7 +290,7 @@ export class CliImporterManager { "cliEventApiImporterRunReturn.applicationDomainName === undefined" ); // create application - if (this.cliImporterManagerOptions.createEventApiApplication) { + if (this.cliImporterManagerOptions.createApiApplication) { const cliApplicationImporter = new CliApplicationImporter({ ...this.cliImporterManagerOptions.cliImporterOptions, applicationDomainName: @@ -330,10 +311,9 @@ export class CliImporterManager { } // clean up if specified if (cleanUp) { - let xvoid: void = - await CliApplicationDomainsService.absent_ApplicationDomains({ - applicationDomainNameList: applicationDomainNameList, - }); + let xvoid: void = await CliApplicationDomainsService.absent_ApplicationDomains({ + applicationDomainNameList: applicationDomainNameList, + }); xvoid = await CliApplicationDomainsService.absent_ApplicationDomains({ applicationDomainNameList: assetApplicationDomainNameList, }); @@ -343,10 +323,9 @@ export class CliImporterManager { CliRunContext.pop(); } catch (e) { if (cleanUp) { - let xvoid: void = - await CliApplicationDomainsService.absent_ApplicationDomains({ - applicationDomainNameList: applicationDomainNameList, - }); + let xvoid: void = await CliApplicationDomainsService.absent_ApplicationDomains({ + applicationDomainNameList: applicationDomainNameList, + }); xvoid = await CliApplicationDomainsService.absent_ApplicationDomains({ applicationDomainNameList: assetApplicationDomainNameList, }); @@ -405,12 +384,13 @@ export class CliImporterManager { checkmode: false, generateAssetsOutput: true, overrideBrokerType: this.cliImporterManagerOptions.cliImporterOptions.cliAssetImport_BrokerType, - overrideChannelDelimiter: this.cliImporterManagerOptions.cliImporterOptions.cliAssetImport_ChannelDelimiter + overrideChannelDelimiter: this.cliImporterManagerOptions.cliImporterOptions.cliAssetImport_ChannelDelimiter, + deleteEventApiAfter: !this.cliImporterManagerOptions.createApiEventApi }}); if (cliEventApiImporterRunReturn.error !== undefined) throw cliEventApiImporterRunReturn.error; if (cliEventApiImporterRunReturn.applicationDomainName === undefined) throw new CliInternalCodeInconsistencyError(logName, "cliEventApiImporterRunReturn.applicationDomainName === undefined"); // create application - if (this.cliImporterManagerOptions.createEventApiApplication) { + if (this.cliImporterManagerOptions.createApiApplication) { const cliApplicationImporter = new CliApplicationImporter({ ...this.cliImporterManagerOptions.cliImporterOptions, applicationDomainName: cliEventApiImporterRunReturn.applicationDomainName, diff --git a/packages/ep-async-api-importer/src/cli-components/CliLogger.ts b/packages/ep-async-api-importer/src/cli-components/CliLogger.ts index 54d4cb51c..bef029b79 100644 --- a/packages/ep-async-api-importer/src/cli-components/CliLogger.ts +++ b/packages/ep-async-api-importer/src/cli-components/CliLogger.ts @@ -53,6 +53,7 @@ export enum ECliStatusCodes { IMPORTING_EP_ENUM = "IMPORTING_EP_ENUM", IMPORTING_EP_ENUM_VERSION = "IMPORTING_ENUM_VERSION", IMPORTING_EP_EVENT_API = "IMPORTING_EP_EVENT_API", + IMPORTING_EP_EVENT_API_DELETED = "IMPORTING_EP_EVENT_API_DELETED", IMPORTING_EP_EVENT_API_VERSION_CHECK = "IMPORTING_EP_EVENT_API_VERSION_CHECK", IMPORTING_EP_EVENT_API_WITH_WARNING = "IMPORTING_EP_EVENT_API_WITH_WARNING", // IMPORTING_EP_EVENT_API_VERSION = 'IMPORTING_EP_EVENT_API_VERSION', diff --git a/packages/ep-async-api-importer/src/importers/CliEventApiImporter.ts b/packages/ep-async-api-importer/src/importers/CliEventApiImporter.ts index f451fe27b..a5bbc85dd 100644 --- a/packages/ep-async-api-importer/src/importers/CliEventApiImporter.ts +++ b/packages/ep-async-api-importer/src/importers/CliEventApiImporter.ts @@ -17,6 +17,7 @@ import { EEpSdkTask_TargetState, EEpSdk_VersionTaskStrategy, EpSdkApplicationDomainTask, + EpSdkEventApisService, EpSdkEventApiTask, EpSdkEventApiVersionsService, EpSdkEventApiVersionTask, @@ -95,6 +96,7 @@ export interface ICliEventApiImporterRunImportReturn extends ICliAssetsImporterR eventApiVersionId: string; } export interface ICliEventApiImporterRunOptions extends ICliAssetsImporterRunOptions { + deleteEventApiAfter: boolean; generateAssetsOutput: boolean; } export interface ICliEventApiImporterRunReturn extends ICliAssetsImporterRunReturn { @@ -652,40 +654,40 @@ export class CliEventApiImporter extends CliAssetsImporter { public async run({ cliImporterRunOptions, }: { cliImporterRunOptions: ICliEventApiImporterRunOptions; }): Promise { - // const funcName = 'run'; - // const logName = `${CliEventApiImporter.name}.${funcName}()`; + const funcName = 'run'; + const logName = `${CliEventApiImporter.name}.${funcName}()`; const cliEventApiImporterRunImportReturn: ICliEventApiImporterRunImportReturn = await this.run_import({ cliImporterRunOptions: cliImporterRunOptions, }); - if (cliEventApiImporterRunImportReturn.error !== undefined) return { - ...cliEventApiImporterRunImportReturn, - cliEventApiImporterGenerateAssetsReturn: { - assetOutputRootDir: undefined, - asyncApiSpecFileNameJson: undefined, - asyncApiSpecFileNameYaml: undefined, - schemasOutputDir: undefined, - error: undefined, - }, - }; - if (cliImporterRunOptions.generateAssetsOutput) { - const cliEventApiImporterGenerateAssetsReturn: ICliEventApiImporterGenerateAssetsReturn = - await this.generate_assets_ouput({ cliImporterGenerateAssetsOptions: { - cliEventApiImporterRunOptions: cliImporterRunOptions, - eventApiId: cliEventApiImporterRunImportReturn.eventApiId, - eventApiVersionId: - cliEventApiImporterRunImportReturn.eventApiVersionId, - applicationDomainId: - cliEventApiImporterRunImportReturn.applicationDomainId, - applicationDomainName: - cliEventApiImporterRunImportReturn.applicationDomainName, - apiTitle: cliEventApiImporterRunImportReturn.apiTitle, - }, - }); + ...cliEventApiImporterRunImportReturn, + cliEventApiImporterGenerateAssetsReturn: { + assetOutputRootDir: undefined, + asyncApiSpecFileNameJson: undefined, + asyncApiSpecFileNameYaml: undefined, + schemasOutputDir: undefined, + error: undefined, + }}; + if(cliImporterRunOptions.deleteEventApiAfter) { + const eventApi: EventApi = await EpSdkEventApisService.deleteById({ + eventApiId: cliEventApiImporterRunImportReturn.eventApiId + }); + CliLogger.trace(CliLogger.createLogEntry(logName, { code: ECliStatusCodes.IMPORTING_EP_EVENT_API_DELETED, details: { + eventApiId: cliEventApiImporterRunImportReturn.eventApiId, + eventApiName: eventApi.name, + }})); + } else if (cliImporterRunOptions.generateAssetsOutput) { + const cliEventApiImporterGenerateAssetsReturn: ICliEventApiImporterGenerateAssetsReturn = await this.generate_assets_ouput({ cliImporterGenerateAssetsOptions: { + cliEventApiImporterRunOptions: cliImporterRunOptions, + eventApiId: cliEventApiImporterRunImportReturn.eventApiId, + eventApiVersionId: cliEventApiImporterRunImportReturn.eventApiVersionId, + applicationDomainId: cliEventApiImporterRunImportReturn.applicationDomainId, + applicationDomainName: cliEventApiImporterRunImportReturn.applicationDomainName, + apiTitle: cliEventApiImporterRunImportReturn.apiTitle, + }}); return { ...cliEventApiImporterRunImportReturn, error: cliEventApiImporterGenerateAssetsReturn.error, - cliEventApiImporterGenerateAssetsReturn: - cliEventApiImporterGenerateAssetsReturn, + cliEventApiImporterGenerateAssetsReturn: cliEventApiImporterGenerateAssetsReturn, }; } return { diff --git a/packages/ep-async-api-importer/test/specs/ep-idempotency.x-spec.ts b/packages/ep-async-api-importer/test/specs/ep-idempotency.x-spec.ts index 58e706e0c..d97132bf1 100644 --- a/packages/ep-async-api-importer/test/specs/ep-idempotency.x-spec.ts +++ b/packages/ep-async-api-importer/test/specs/ep-idempotency.x-spec.ts @@ -56,6 +56,7 @@ import { EpAsyncApiDocumentService } from "@solace-labs/ep-asyncapi"; import { ECliAssetImport_TargetVersionStrategy } from "../../src/importers"; +import { EpSdkApplicationVersionsService } from "@solace-labs/ep-sdk"; const scriptName: string = path.basename(__filename); const TestSpecName = scriptName; @@ -473,7 +474,8 @@ describe(`${scriptName}`, () => { // // DEBUG // CliConfig.getCliImporterManagerOptions().cliImporterManagerMode = ECliImporterManagerMode.TEST_MODE_KEEP; // CliConfig.getCliImporterManagerOptions().applicationDomainName = 'release_mode'; - CliConfig.getCliImporterManagerOptions().createEventApiApplication = true; + CliConfig.getCliImporterManagerOptions().createApiApplication = true; + CliConfig.getCliImporterManagerOptions().createApiEventApi = false; CliConfig.getCliImporterManagerOptions().cliImporterOptions.cliAssetImport_BrokerType = undefined; CliConfig.getCliImporterManagerOptions().cliImporterOptions.cliAssetImport_ChannelDelimiter = undefined; CliConfig.getCliImporterManagerOptions().cliImporterOptions.cliValidateApiSpecBestPractices = true; @@ -481,10 +483,6 @@ describe(`${scriptName}`, () => { const cliImporter = new CliImporterManager(CliConfig.getCliImporterManagerOptions()); const xvoid: void = await cliImporter.run(); - // // DEBUG - expect(false, 'check app import ok').to.be.true; - // const cliRunSummaryList: Array = CliRunSummary.getSummaryLogList(); - // expect(false, JSON.stringify(cliRunSummaryList, null, 2)).to.be.true; } catch (e) { TestLogger.logMessageWithId(TestLogger.createTestFailMessageForError('error', e)); expect( e instanceof CliError, TestLogger.createNotCliErrorMesssage(e.message)).to.be.true; @@ -495,16 +493,8 @@ describe(`${scriptName}`, () => { } }); - it(`${scriptName}: continue here`, async () => { - expect(false, 'continue here').to.be.true; - }); - it(`${scriptName}: should check no new version created for application`, async () => { - - expect(false, 'continue here').to.be.true; - try { - // TODO: write the correct checks const enum_1_id_versions = await EpSdkEnumVersionsService.getVersionsForEnumId({enumId: Enum_1_Id}); expect(enum_1_id_versions.length,'enum_1_id_versions.length not 1').to.equal(1); const enum_2_id_versions = await EpSdkEnumVersionsService.getVersionsForEnumId({enumId: Enum_2_Id}); @@ -520,9 +510,8 @@ describe(`${scriptName}`, () => { const event_2_id_versions = await EpSdkEpEventVersionsService.getVersionsForEventId({ eventId: Event_2_Id }); expect(event_2_id_versions.length,'event_2_id_versions.length not 1').to.equal(1); - const event_api_versions = await EpSdkEventApiVersionsService.getVersionsForEventApiId({ eventApiId: EventApi_Id }); - expect(event_api_versions.length,'event_api_versions.length not 1').to.equal(1); - + const app_versions = await EpSdkApplicationVersionsService.getVersionsForApplicationId({ applicationId: App_Id }); + expect(app_versions.length,'app_versions.length not 1').to.equal(1); } catch (e) { TestLogger.logMessageWithId(TestLogger.createTestFailMessageForError('error', e)); if (e instanceof ApiError) expect(false, TestLogger.createApiTestFailMessage("failed")).to.be.true; @@ -573,7 +562,8 @@ describe(`${scriptName}`, () => { // // DEBUG // CliConfig.getCliImporterManagerOptions().cliImporterManagerMode = ECliImporterManagerMode.TEST_MODE_KEEP; // CliConfig.getCliImporterManagerOptions().applicationDomainName = 'release_mode'; - CliConfig.getCliImporterManagerOptions().createEventApiApplication = false; + CliConfig.getCliImporterManagerOptions().createApiApplication = false; + CliConfig.getCliImporterManagerOptions().createApiEventApi = true; CliConfig.getCliImporterManagerOptions().cliImporterOptions.cliAssetImport_BrokerType = undefined; CliConfig.getCliImporterManagerOptions().cliImporterOptions.cliAssetImport_ChannelDelimiter = undefined; CliConfig.getCliImporterManagerOptions().cliImporterOptions.cliValidateApiSpecBestPractices = true; diff --git a/packages/ep-asyncapi/test/specs/test-fail/test-fail.spec.ts b/packages/ep-asyncapi/test/specs/test-fail/test-fail.spec.ts index 80f43d282..99c484a6c 100644 --- a/packages/ep-asyncapi/test/specs/test-fail/test-fail.spec.ts +++ b/packages/ep-asyncapi/test/specs/test-fail/test-fail.spec.ts @@ -40,7 +40,7 @@ describe(`${scriptName}`, () => { expect(e instanceof EpAsyncApiError, TestLogger.createNotEpAsyncApiErrorMessage(e)).to.be.true; expect(e instanceof EpAsyncApiValidationError, TestLogger.createTestFailMessageForError('e instanceof EpAsyncApiValidationError', e)).to.be.true; const epAsyncApiValidationError: EpAsyncApiValidationError = e; - expect(JSON.stringify(epAsyncApiValidationError.details), TestLogger.createTestFailMessage(JSON.stringify(epAsyncApiValidationError.details, null, 2))).to.contain('epEventApiName'); + expect(JSON.stringify(epAsyncApiValidationError.details), TestLogger.createTestFailMessage(JSON.stringify(epAsyncApiValidationError.details, null, 2))).to.contain('epApiName'); } }); From 0f1a62ae2184f704536021bc4a771fa458bd03e0 Mon Sep 17 00:00:00 2001 From: Ricardo Gomez_Ulmke Date: Mon, 13 Mar 2023 14:05:16 +0100 Subject: [PATCH 31/33] test --- .../ep-async-api-importer/test/specs/asset-domain.spec.ts | 2 +- .../ep-async-api-importer/test/specs/best-practices.spec.ts | 2 +- .../test/specs/error-capture-and-logging.spec.ts | 2 +- .../test/specs/error-event-api-version.spec.ts | 2 +- .../test/specs/passing-release_mode.spec.ts | 4 ++-- .../test/specs/two-channels-same-message.spec.ts | 2 +- .../test/specs/warning-event-api-version.spec.ts | 2 +- 7 files changed, 8 insertions(+), 8 deletions(-) diff --git a/packages/ep-async-api-importer/test/specs/asset-domain.spec.ts b/packages/ep-async-api-importer/test/specs/asset-domain.spec.ts index 3087f7b10..ff5ecdc94 100644 --- a/packages/ep-async-api-importer/test/specs/asset-domain.spec.ts +++ b/packages/ep-async-api-importer/test/specs/asset-domain.spec.ts @@ -46,7 +46,7 @@ const initializeGlobals = () => { // // DEBUG // CliConfig.getCliImporterManagerOptions().cliImporterManagerMode = ECliImporterManagerMode.TEST_MODE_KEEP; // CliConfig.getCliImporterManagerOptions().applicationDomainName = 'release_mode'; - CliConfig.getCliImporterManagerOptions().createEventApiApplication = false; + CliConfig.getCliImporterManagerOptions().createApiApplication = false; CliConfig.getCliImporterManagerOptions().cliImporterOptions.cliAssetImport_BrokerType = undefined; CliConfig.getCliImporterManagerOptions().cliImporterOptions.cliAssetImport_ChannelDelimiter = undefined; }; diff --git a/packages/ep-async-api-importer/test/specs/best-practices.spec.ts b/packages/ep-async-api-importer/test/specs/best-practices.spec.ts index 8c553fdd0..3e4711607 100644 --- a/packages/ep-async-api-importer/test/specs/best-practices.spec.ts +++ b/packages/ep-async-api-importer/test/specs/best-practices.spec.ts @@ -43,7 +43,7 @@ const initializeGlobals = () => { // // DEBUG // CliConfig.getCliImporterManagerOptions().cliImporterManagerMode = ECliImporterManagerMode.TEST_MODE_KEEP; // CliConfig.getCliImporterManagerOptions().applicationDomainName = 'release_mode'; - CliConfig.getCliImporterManagerOptions().createEventApiApplication = false; + CliConfig.getCliImporterManagerOptions().createApiApplication = false; CliConfig.getCliImporterManagerOptions().cliImporterOptions.cliAssetImport_BrokerType = undefined; CliConfig.getCliImporterManagerOptions().cliImporterOptions.cliAssetImport_ChannelDelimiter = undefined; }; diff --git a/packages/ep-async-api-importer/test/specs/error-capture-and-logging.spec.ts b/packages/ep-async-api-importer/test/specs/error-capture-and-logging.spec.ts index 1c83571df..2ecf99180 100644 --- a/packages/ep-async-api-importer/test/specs/error-capture-and-logging.spec.ts +++ b/packages/ep-async-api-importer/test/specs/error-capture-and-logging.spec.ts @@ -49,7 +49,7 @@ const initializeGlobals = () => { CliConfig.getCliImporterManagerOptions().cliImporterManagerMode = ECliImporterManagerMode.RELEASE_MODE; CliConfig.getCliImporterManagerOptions().cliTestSetupDomainsForApis = true; - CliConfig.getCliImporterManagerOptions().createEventApiApplication = false; + CliConfig.getCliImporterManagerOptions().createApiApplication = false; }; describe(`${scriptName}`, () => { diff --git a/packages/ep-async-api-importer/test/specs/error-event-api-version.spec.ts b/packages/ep-async-api-importer/test/specs/error-event-api-version.spec.ts index cd2ed7835..6d3716d50 100644 --- a/packages/ep-async-api-importer/test/specs/error-event-api-version.spec.ts +++ b/packages/ep-async-api-importer/test/specs/error-event-api-version.spec.ts @@ -51,7 +51,7 @@ const initializeGlobals = () => { CliConfig.getCliImporterManagerOptions().cliImporterManagerMode = ECliImporterManagerMode.RELEASE_MODE; CliConfig.getCliImporterManagerOptions().cliTestSetupDomainsForApis = true; - CliConfig.getCliImporterManagerOptions().createEventApiApplication = false; + CliConfig.getCliImporterManagerOptions().createApiApplication = false; }; describe(`${scriptName}`, () => { diff --git a/packages/ep-async-api-importer/test/specs/passing-release_mode.spec.ts b/packages/ep-async-api-importer/test/specs/passing-release_mode.spec.ts index 42792ecec..1cba93784 100644 --- a/packages/ep-async-api-importer/test/specs/passing-release_mode.spec.ts +++ b/packages/ep-async-api-importer/test/specs/passing-release_mode.spec.ts @@ -37,7 +37,7 @@ const initializeGlobals = () => { CliConfig.getCliImporterManagerOptions().asyncApiFileList = FileList; CliConfig.getCliImporterManagerOptions().cliImporterManagerMode = ECliImporterManagerMode.RELEASE_MODE; CliConfig.getCliImporterManagerOptions().cliTestSetupDomainsForApis = true; - CliConfig.getCliImporterManagerOptions().createEventApiApplication = false; + CliConfig.getCliImporterManagerOptions().createApiApplication = false; } describe(`${scriptName}`, () => { @@ -112,7 +112,7 @@ describe(`${scriptName}`, () => { it(`${scriptName}: should import specs with application / version`, async () => { try { - CliConfig.getCliImporterManagerOptions().createEventApiApplication = true; + CliConfig.getCliImporterManagerOptions().createApiApplication = true; const cliImporter = new CliImporterManager(CliConfig.getCliImporterManagerOptions()); const xvoid: void = await cliImporter.run(); diff --git a/packages/ep-async-api-importer/test/specs/two-channels-same-message.spec.ts b/packages/ep-async-api-importer/test/specs/two-channels-same-message.spec.ts index 6607b5002..cbf120e92 100644 --- a/packages/ep-async-api-importer/test/specs/two-channels-same-message.spec.ts +++ b/packages/ep-async-api-importer/test/specs/two-channels-same-message.spec.ts @@ -33,7 +33,7 @@ const initializeGlobals = () => { CliConfig.getCliImporterManagerOptions().asyncApiFileList = FileList; CliConfig.getCliImporterManagerOptions().cliImporterManagerMode = ECliImporterManagerMode.RELEASE_MODE; CliConfig.getCliImporterManagerOptions().cliTestSetupDomainsForApis = true; - CliConfig.getCliImporterManagerOptions().createEventApiApplication = false; + CliConfig.getCliImporterManagerOptions().createApiApplication = false; } describe(`${scriptName}`, () => { diff --git a/packages/ep-async-api-importer/test/specs/warning-event-api-version.spec.ts b/packages/ep-async-api-importer/test/specs/warning-event-api-version.spec.ts index c6bee7198..2ff14f27c 100644 --- a/packages/ep-async-api-importer/test/specs/warning-event-api-version.spec.ts +++ b/packages/ep-async-api-importer/test/specs/warning-event-api-version.spec.ts @@ -50,7 +50,7 @@ const initializeGlobals = () => { CliConfig.getCliImporterManagerOptions().cliImporterManagerMode = ECliImporterManagerMode.RELEASE_MODE; CliConfig.getCliImporterManagerOptions().cliTestSetupDomainsForApis = false; - CliConfig.getCliImporterManagerOptions().createEventApiApplication = true; + CliConfig.getCliImporterManagerOptions().createApiApplication = true; }; describe(`${scriptName}`, () => { From e9339395c4cb46c63dd07cbd1183b17f8733496c Mon Sep 17 00:00:00 2001 From: Ricardo Gomez_Ulmke Date: Mon, 13 Mar 2023 14:09:09 +0100 Subject: [PATCH 32/33] tests --- ...tency.x-spec.ts => ep-idempotency.spec.ts} | 0 .../src/documents/EpAsyncApiDocument.ts | 26 ------------------- 2 files changed, 26 deletions(-) rename packages/ep-async-api-importer/test/specs/{ep-idempotency.x-spec.ts => ep-idempotency.spec.ts} (100%) diff --git a/packages/ep-async-api-importer/test/specs/ep-idempotency.x-spec.ts b/packages/ep-async-api-importer/test/specs/ep-idempotency.spec.ts similarity index 100% rename from packages/ep-async-api-importer/test/specs/ep-idempotency.x-spec.ts rename to packages/ep-async-api-importer/test/specs/ep-idempotency.spec.ts diff --git a/packages/ep-asyncapi/src/documents/EpAsyncApiDocument.ts b/packages/ep-asyncapi/src/documents/EpAsyncApiDocument.ts index ef92c1a30..af2b9048b 100644 --- a/packages/ep-asyncapi/src/documents/EpAsyncApiDocument.ts +++ b/packages/ep-asyncapi/src/documents/EpAsyncApiDocument.ts @@ -356,14 +356,6 @@ export class EpAsyncApiDocument { return this.asyncApiDocument.info().title(); } - // private getTitleAsFilePath(): string { - // return this.getTitle().replaceAll(/[^0-9a-zA-Z]+/g, "-"); - // } - - // private getTitleAsFileName(ext: string): string { - // return `${this.getTitleAsFilePath()}.${ext}`; - // } - public getVersion(): string { return this.asyncApiDocument.info().version(); } @@ -409,24 +401,6 @@ export class EpAsyncApiDocument { return this.epApiVersionName; } - // public getEpApplicationName(): string { - // // TODO: needs its own property, different create algo - // return this.getEpEventApiName(); - // } - - // public getEpApplicationVersionName(): string { - // // TODO: needs its own property, different create algo - // return this.getEpEventApiVersionName(); - // } - - // public getEpApplicationNameAsFilePath(): string { - // return this.getEpApplicationName().replaceAll(/[^0-9a-zA-Z]+/g, "-"); - // } - - // public getEpApplicationNameAsFileName(ext: string): string { - // return `${this.getEpApplicationNameAsFilePath()}.${ext}`; - // } - public getAsJson(): any { return this.asyncApiDocumentJson; } public getAsYamlString(): string { From d5cb94fddaadc814d57c2a89dad2968b6ab4daa6 Mon Sep 17 00:00:00 2001 From: Ricardo Gomez_Ulmke Date: Mon, 13 Mar 2023 17:01:13 +0100 Subject: [PATCH 33/33] docs --- .changeset/ep-asyncapi.md | 24 ++ .changeset/importer.md | 22 ++ .../apis-content/extensions.rst | 63 +++++ .../usage-content/overview.rst | 24 ++ .../src/importers/CliAssetsImporter.ts | 259 ++++++------------ .../test/specs/ep-idempotency.spec.ts | 2 +- ...=> ep-multi-application-domains.x-spec.ts} | 48 +++- 7 files changed, 255 insertions(+), 187 deletions(-) create mode 100644 .changeset/importer.md rename packages/ep-async-api-importer/test/specs/{multi-domain.xx-spec.ts => ep-multi-application-domains.x-spec.ts} (92%) diff --git a/.changeset/ep-asyncapi.md b/.changeset/ep-asyncapi.md index 13be866b0..3085f06c5 100644 --- a/.changeset/ep-asyncapi.md +++ b/.changeset/ep-asyncapi.md @@ -8,3 +8,27 @@ added ep extensions - priority: - existing extensions - ep extensions + +The following ep extensions are supported: + +```typescript +/** extensions used by EP when exporting spec */ +export enum EpParameterExtensions { + xEpEnumName = "x-ep-enum-name", + xEpEnumVersionDisplayName = "x-ep-enum-version-displayname", +} +/** extensions used by EP when exporting spec */ +export enum EpMessageExtensions { + xEpEventName = "x-ep-event-name", + xEpEventVersionDisplayName = "x-ep-event-version-displayname", +} +/** extensions used by EP when exporting spec */ +export enum EpSchemaExtensions { + xEpSchemaName = "x-ep-schema-name", + xEpSchemaVersionDisplayName = "x-ep-schema-version-displayname", +} +/** extensions used by EP when exporting spec */ +export enum EpApiInfoExtensions { + xEpApiInfoVersionDisplayName = "x-ep-displayname", +} +``` diff --git a/.changeset/importer.md b/.changeset/importer.md new file mode 100644 index 000000000..f80e32b09 --- /dev/null +++ b/.changeset/importer.md @@ -0,0 +1,22 @@ +--- +"@solace-labs/ep-async-api-importer": minor +--- + +Added support for additional ep extensions + +- see CHANGELOG.md for ep-asyncapi. + +Added new CLI environment variable: + +```bash +export CLI_IMPORT_CREATE_API_EVENT_API=true/false +``` + +if set to true, the importer will create the Event API. +if set to false, the import will not create the Event API. + +Use in conjunction with: + +```bash +export CLI_IMPORT_CREATE_API_APPLICATION=true/false +``` diff --git a/docs/source/ep-async-api-importer/apis-content/extensions.rst b/docs/source/ep-async-api-importer/apis-content/extensions.rst index 0342eb941..65a59dc29 100644 --- a/docs/source/ep-async-api-importer/apis-content/extensions.rst +++ b/docs/source/ep-async-api-importer/apis-content/extensions.rst @@ -31,3 +31,66 @@ The importer uses the following extensions: - Event Name = $.channel.{topic} - Event Version Name = EMPTY + + +In addition, it uses the following Event Portal extensions: + +.. list-table:: Event Portal Info Extensions + :widths: 30 100 + :header-rows: 1 + + * - Async Api Extension + - Description + * - $.info.x-ep-displayname + - The version display name for Event APIs and Applications. + + Defaults to empty string if omitted. + + +.. list-table:: Event Portal Message Extensions + :widths: 30 100 + :header-rows: 1 + + * - Async Api Extension + - Description + * - x-ep-event-name + - The Event name for the message. + + Defaults to `$.channels.{topic}.x-ep-event-name` if omitted. + * - x-ep-event-version-displayname + - The Event version name for the message. + + Defaults to empty string if omitted. + + +.. list-table:: Event Portal Schema Extensions + :widths: 30 100 + :header-rows: 1 + + * - Async Api Extension + - Description + * - x-ep-schema-name + - The Schema name for the schema. + + Defaults to `x-ep-event-name` if omitted. + * - x-ep-schema-version-displayname + - The Schema version name for the schema. + + Defaults to empty string if omitted. + + +.. list-table:: Event Portal Channel Parameter Extensions + :widths: 30 100 + :header-rows: 1 + + * - Async Api Extension + - Description + * - x-ep-enum-name + - The Enum name for the parameter. + + Defaults to the string in the channel parameter if omitted. + * - x-ep-enum-version-displayname + - The Enum version name for the parameter. + + Defaults to empty string if omitted. + diff --git a/docs/source/ep-async-api-importer/usage-content/overview.rst b/docs/source/ep-async-api-importer/usage-content/overview.rst index 72cf4ff20..969c3c07a 100644 --- a/docs/source/ep-async-api-importer/usage-content/overview.rst +++ b/docs/source/ep-async-api-importer/usage-content/overview.rst @@ -107,3 +107,27 @@ After each Api import the following output is generated: - {schema-name}.json - ... + + +Importing Api as Event API +-------------------------- + +The default mode is to import the Api as an Event API. + +You can switch it off by setting the following environment variable: + +.. code-block:: bash + + export CLI_IMPORT_CREATE_API_EVENT_API=false + + +Importing Api as Application +---------------------------- + +By default, importing the Api as an Application is switched off. + +You can switch it on by setting the following environment variable: + +.. code-block:: bash + + export CLI_IMPORT_CREATE_API_APPLICATION=true diff --git a/packages/ep-async-api-importer/src/importers/CliAssetsImporter.ts b/packages/ep-async-api-importer/src/importers/CliAssetsImporter.ts index 493fb7797..14076c3c2 100644 --- a/packages/ep-async-api-importer/src/importers/CliAssetsImporter.ts +++ b/packages/ep-async-api-importer/src/importers/CliAssetsImporter.ts @@ -392,12 +392,7 @@ export abstract class CliAssetsImporter extends CliImporter { CliRunSummary.processedEnumVersion({ epSdkEnumVersionTask_ExecuteReturn: epSdkEnumVersionTask_ExecuteReturn }); }; - private run_present_channel_parameters = async ({ - assetApplicationDomainId, - epAsyncApiChannelParameterDocumentMap, - specVersion, - checkmode, - }: { + private run_present_channel_parameters = async ({assetApplicationDomainId, epAsyncApiChannelParameterDocumentMap, specVersion, checkmode }: { assetApplicationDomainId: string; epAsyncApiChannelParameterDocumentMap?: T_EpAsyncApiChannelParameterDocumentMap; specVersion: string; @@ -407,47 +402,35 @@ export abstract class CliAssetsImporter extends CliImporter { const logName = `${CliAssetsImporter.name}.${funcName}()`; if (epAsyncApiChannelParameterDocumentMap === undefined) { - CliLogger.debug( - CliLogger.createLogEntry(logName, { - code: ECliStatusCodes.IMPORTING_API_CHANNEL_PARAMETERS, - details: { - channelParameters: [], - }, - }) - ); + CliLogger.debug(CliLogger.createLogEntry(logName, {code: ECliStatusCodes.IMPORTING_API_CHANNEL_PARAMETERS, details: { + channelParameters: [], + }})); return; } - for (const [ - parameterName, - epAsyncApiChannelParameterDocument, - ] of epAsyncApiChannelParameterDocumentMap) { - const parameterEnumList: Array = - epAsyncApiChannelParameterDocument.getParameterEnumValueList(); + for (const [parameterName, epAsyncApiChannelParameterDocument] of epAsyncApiChannelParameterDocumentMap) { + const parameterEnumList: Array = epAsyncApiChannelParameterDocument.getParameterEnumValueList(); const rctxt: ICliApiRunContext_Channel_Parameter = { parameter: parameterName, - parameterEnumList: - parameterEnumList.length > 0 ? parameterEnumList : undefined, + parameterEnumList: parameterEnumList.length > 0 ? parameterEnumList : undefined, }; CliRunContext.push(rctxt); - CliLogger.debug( - CliLogger.createLogEntry(logName, { - code: ECliStatusCodes.IMPORTING_API_CHANNEL_PARAMETER, - details: {}, - }) - ); - CliLogger.trace( - CliLogger.createLogEntry(logName, { - code: ECliStatusCodes.IMPORTING_API_CHANNEL_PARAMETER, - details: { - epAsyncApiChannelParameterDocument: - epAsyncApiChannelParameterDocument, - }, - }) - ); + CliLogger.debug(CliLogger.createLogEntry(logName, {code: ECliStatusCodes.IMPORTING_API_CHANNEL_PARAMETER, details: {}})); + CliLogger.trace(CliLogger.createLogEntry(logName, {code: ECliStatusCodes.IMPORTING_API_CHANNEL_PARAMETER, details: { + epAsyncApiChannelParameterDocument: epAsyncApiChannelParameterDocument, + }})); // only create the enum if there are any values in the list if (parameterEnumList.length > 0) { + + // problem: + // - only create the enum + version if not from a different applicationDomainId than + // the actual target assetApplicationDomainId + // - if they are from a different domain, then fail if there is a change, otherwise ?? + // how to check for the original applicationDomainId (if it even existed) + // + // checkmode = true for test_pass_2 + // present enum const epSdkEnumTask = new EpSdkEnumTask({ epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, @@ -459,42 +442,23 @@ export abstract class CliAssetsImporter extends CliImporter { epSdkTask_TransactionConfig: this.get_IEpSdkTask_TransactionConfig(), // TODO: checkmode? }); - const epSdkEnumTask_ExecuteReturn: IEpSdkEnumTask_ExecuteReturn = - await this.executeTask({ - epSdkTask: epSdkEnumTask, - expectNoAction: checkmode, - }); - const enumObject: TopicAddressEnum = - epSdkEnumTask_ExecuteReturn.epObject; + const epSdkEnumTask_ExecuteReturn: IEpSdkEnumTask_ExecuteReturn = await this.executeTask({epSdkTask: epSdkEnumTask, expectNoAction: checkmode }); + const enumObject: TopicAddressEnum = epSdkEnumTask_ExecuteReturn.epObject; /* istanbul ignore next */ - if (enumObject.id === undefined) - throw new CliEPApiContentError( - logName, - "enumObject.id === undefined", - { - enumObject: enumObject, - } - ); - - CliLogger.trace( - CliLogger.createLogEntry(logName, { - code: ECliStatusCodes.IMPORTING_EP_ENUM, - details: { - epSdkEnumTask_ExecuteReturn: epSdkEnumTask_ExecuteReturn, - }, - }) - ); - CliRunSummary.processedEnum({ - epSdkEnumTask_ExecuteReturn: epSdkEnumTask_ExecuteReturn, + if (enumObject.id === undefined) throw new CliEPApiContentError(logName,"enumObject.id === undefined", { + enumObject: enumObject, }); + CliLogger.trace(CliLogger.createLogEntry(logName, {code: ECliStatusCodes.IMPORTING_EP_ENUM,details: { + epSdkEnumTask_ExecuteReturn: epSdkEnumTask_ExecuteReturn, + }})); + CliRunSummary.processedEnum({epSdkEnumTask_ExecuteReturn: epSdkEnumTask_ExecuteReturn }); // present the enum version const xvoid: void = await this.run_present_enum_version({ assetApplicationDomainId: assetApplicationDomainId, enumObject: enumObject, specVersion: specVersion, - epAsyncApiChannelParameterDocument: - epAsyncApiChannelParameterDocument, + epAsyncApiChannelParameterDocument: epAsyncApiChannelParameterDocument, checkmode: checkmode, }); /* istanbul ignore next */ @@ -504,12 +468,7 @@ export abstract class CliAssetsImporter extends CliImporter { } }; - private run_present_channel = async ({ - assetApplicationDomainId, - epAsyncApiChannelDocument, - specVersion, - checkmode, - }: { + private run_present_channel = async ({assetApplicationDomainId, epAsyncApiChannelDocument, specVersion, checkmode }: { assetApplicationDomainId: string; epAsyncApiChannelDocument: EpAsyncApiChannelDocument; specVersion: string; @@ -518,8 +477,7 @@ export abstract class CliAssetsImporter extends CliImporter { const funcName = "run_present_channel"; const logName = `${CliAssetsImporter.name}.${funcName}()`; - const channelTopic: string = - epAsyncApiChannelDocument.getAsyncApiChannelKey(); + const channelTopic: string = epAsyncApiChannelDocument.getAsyncApiChannelKey(); const epEventName: string = epAsyncApiChannelDocument.getEpEventName(); const rctxt: ICliApiRunContext_Channel = { @@ -528,76 +486,50 @@ export abstract class CliAssetsImporter extends CliImporter { applicationDomainName: assetApplicationDomainId, }; CliRunContext.push(rctxt); - CliRunSummary.processingApiChannel({ - cliRunSummary_ApiChannel: { - type: ECliRunSummary_Type.ApiChannel, - channelTopic: channelTopic, - applicationDomainName: - epAsyncApiChannelDocument.getApplicationDomainName(), - }, - }); - CliLogger.trace( - CliLogger.createLogEntry(logName, { - code: ECliStatusCodes.IMPORTING_API_CHANNEL, - details: { - epAsyncApiChannelDocument: epAsyncApiChannelDocument, - }, - }) - ); + CliRunSummary.processingApiChannel({ cliRunSummary_ApiChannel: { + type: ECliRunSummary_Type.ApiChannel, + channelTopic: channelTopic, + applicationDomainName: epAsyncApiChannelDocument.getApplicationDomainName(), + }}); + CliLogger.trace(CliLogger.createLogEntry(logName, {code: ECliStatusCodes.IMPORTING_API_CHANNEL,details: { + epAsyncApiChannelDocument: epAsyncApiChannelDocument, + }})); let xvoid: void; // present channel parameters xvoid = await this.run_present_channel_parameters({ assetApplicationDomainId: assetApplicationDomainId, - epAsyncApiChannelParameterDocumentMap: - epAsyncApiChannelDocument.getEpAsyncApiChannelParameterDocumentMap(), + epAsyncApiChannelParameterDocumentMap: epAsyncApiChannelDocument.getEpAsyncApiChannelParameterDocumentMap(), specVersion: specVersion, checkmode: checkmode, }); // publish operations - const epAsynApiChannelPublishOperation: - | EpAsynApiChannelPublishOperation - | undefined = - epAsyncApiChannelDocument.getEpAsyncApiChannelPublishOperation(); + const epAsynApiChannelPublishOperation: EpAsynApiChannelPublishOperation | undefined = epAsyncApiChannelDocument.getEpAsyncApiChannelPublishOperation(); if (epAsynApiChannelPublishOperation !== undefined) { const rctxt: ICliApiRunContext_Channel_Operation = { type: ECliChannelOperation.Publish, }; CliRunContext.push(rctxt); - CliRunSummary.processingApiChannelOperation({ - cliRunSummary_ApiChannel_Operation: { - type: ECliRunSummary_Type.ApiChannelOperation, - operationType: ECliChannelOperationType.PUBLISH, - }, - }); - CliLogger.debug( - CliLogger.createLogEntry(logName, { - code: ECliStatusCodes.IMPORTING_API_CHANNEL_PUBLISH_OPERATION, - details: {}, - }) - ); + CliRunSummary.processingApiChannelOperation({ cliRunSummary_ApiChannel_Operation: { + type: ECliRunSummary_Type.ApiChannelOperation, + operationType: ECliChannelOperationType.PUBLISH, + }}); + CliLogger.debug(CliLogger.createLogEntry(logName, {code: ECliStatusCodes.IMPORTING_API_CHANNEL_PUBLISH_OPERATION,details: {}})); - const epAsyncApiMessageDocument: EpAsyncApiMessageDocument = - epAsynApiChannelPublishOperation.getEpAsyncApiMessageDocument(); + const epAsyncApiMessageDocument: EpAsyncApiMessageDocument = epAsynApiChannelPublishOperation.getEpAsyncApiMessageDocument(); // present message - const schemaVersionObject: SchemaVersion = - await this.run_present_channel_message({ - assetApplicationDomainId: assetApplicationDomainId, - epAsyncApiMessageDocument: epAsyncApiMessageDocument, - specVersion: specVersion, - checkmode: checkmode, - }); + const schemaVersionObject: SchemaVersion = await this.run_present_channel_message({ + assetApplicationDomainId: assetApplicationDomainId, + epAsyncApiMessageDocument: epAsyncApiMessageDocument, + specVersion: specVersion, + checkmode: checkmode, + }); /* istanbul ignore next */ - if (schemaVersionObject.id === undefined) - throw new CliEPApiContentError( - logName, - "schemaVersionObject.id === undefined", - { - schemaVersionObject: schemaVersionObject, - } - ); + if (schemaVersionObject.id === undefined) throw new CliEPApiContentError(logName, "schemaVersionObject.id === undefined", { + schemaVersionObject: schemaVersionObject, + }); // present event xvoid = await this.run_present_channel_event({ assetApplicationDomainId: assetApplicationDomainId, @@ -668,93 +600,60 @@ export abstract class CliAssetsImporter extends CliImporter { CliRunContext.pop(); }; - protected async run_present_assets({ - cliAssetsImporterRunPresentOptions, - }: { + protected async run_present_assets({ cliAssetsImporterRunPresentOptions }: { cliAssetsImporterRunPresentOptions: ICliAssetsImporterRunPresentOptions; }): Promise { const funcName = "run_present_assets"; const logName = `${CliAssetsImporter.name}.${funcName}()`; - CliLogger.debug( - CliLogger.createLogEntry(logName, { - code: ECliStatusCodes.IMPORTING_START_API_ASSETS, - details: { - cliAssetsImporterRunPresentOptions: - cliAssetsImporterRunPresentOptions, - }, - }) - ); + CliLogger.debug(CliLogger.createLogEntry(logName, {code: ECliStatusCodes.IMPORTING_START_API_ASSETS,details: { + cliAssetsImporterRunPresentOptions: cliAssetsImporterRunPresentOptions, + }})); // asset application domain present const assetApplicationDomainsTask = new EpSdkApplicationDomainTask({ epSdkTask_TargetState: EEpSdkTask_TargetState.PRESENT, - applicationDomainName: - cliAssetsImporterRunPresentOptions.epAsyncApiDocument.getAssetsApplicationDomainName(), + applicationDomainName: cliAssetsImporterRunPresentOptions.epAsyncApiDocument.getAssetsApplicationDomainName(), applicationDomainSettings: { // description: "a new description x" }, epSdkTask_TransactionConfig: this.get_IEpSdkTask_TransactionConfig(), checkmode: cliAssetsImporterRunPresentOptions.checkmode, }); - const epSdkAssetApplicationDomainTask_ExecuteReturn: IEpSdkApplicationDomainTask_ExecuteReturn = - await this.executeTask({ - epSdkTask: assetApplicationDomainsTask, - expectNoAction: cliAssetsImporterRunPresentOptions.checkmode, - }); - CliLogger.trace( - CliLogger.createLogEntry(logName, { - code: ECliStatusCodes.IMPORTING_EP_ASSET_APPLICATION_DOMAIN, - message: "asset application domain", - details: { - epSdkAssetApplicationDomainTask_ExecuteReturn: - epSdkAssetApplicationDomainTask_ExecuteReturn, - }, - }) - ); + const epSdkAssetApplicationDomainTask_ExecuteReturn: IEpSdkApplicationDomainTask_ExecuteReturn = await this.executeTask({ + epSdkTask: assetApplicationDomainsTask, + expectNoAction: cliAssetsImporterRunPresentOptions.checkmode, + }); + CliLogger.trace(CliLogger.createLogEntry(logName, { code: ECliStatusCodes.IMPORTING_EP_ASSET_APPLICATION_DOMAIN, message: "asset application domain", details: { + epSdkAssetApplicationDomainTask_ExecuteReturn: epSdkAssetApplicationDomainTask_ExecuteReturn, + }})); // create summary log CliRunSummary.processedAssetApplicationDomain({ - epSdkAssetApplicationDomainTask_ExecuteReturn: - epSdkAssetApplicationDomainTask_ExecuteReturn, + epSdkAssetApplicationDomainTask_ExecuteReturn: epSdkAssetApplicationDomainTask_ExecuteReturn, }); // we need the ids in subsequent calls /* istanbul ignore next */ - if (epSdkAssetApplicationDomainTask_ExecuteReturn.epObject.id === undefined) - throw new CliEPApiContentError( - logName, - "epSdkAssetApplicationDomainTask_ExecuteReturn.epObject.id === undefined", - { - applicationDomainObject: - epSdkAssetApplicationDomainTask_ExecuteReturn.epObject, - } - ); - const cliAssetsImporterRunPresentReturn: ICliAssetsImporterRunPresentReturn = - { - assetApplicationDomainId: - epSdkAssetApplicationDomainTask_ExecuteReturn.epObject.id, - }; + if (epSdkAssetApplicationDomainTask_ExecuteReturn.epObject.id === undefined) throw new CliEPApiContentError(logName, "epSdkAssetApplicationDomainTask_ExecuteReturn.epObject.id === undefined", { + applicationDomainObject: epSdkAssetApplicationDomainTask_ExecuteReturn.epObject, + }); + const cliAssetsImporterRunPresentReturn: ICliAssetsImporterRunPresentReturn = { + assetApplicationDomainId: epSdkAssetApplicationDomainTask_ExecuteReturn.epObject.id, + }; // present all channels - const epAsyncApiChannelDocumentMap: T_EpAsyncApiChannelDocumentMap = - cliAssetsImporterRunPresentOptions.epAsyncApiDocument.getEpAsyncApiChannelDocumentMap(); - for (const [ - topic, - epAsyncApiChannelDocument, - ] of epAsyncApiChannelDocumentMap) { + const epAsyncApiChannelDocumentMap: T_EpAsyncApiChannelDocumentMap = cliAssetsImporterRunPresentOptions.epAsyncApiDocument.getEpAsyncApiChannelDocumentMap(); + for (const [topic, epAsyncApiChannelDocument] of epAsyncApiChannelDocumentMap) { // CliLogger.trace(CliLogger.createLogEntry(logName, { code: ECliStatusCodes.IMPORTING, details: { // topic: topic, // channelDocument: channelDocument // }})); /* istanbul ignore next */ topic; - const xvoid: void = await this.run_present_channel({ - assetApplicationDomainId: - cliAssetsImporterRunPresentReturn.assetApplicationDomainId, + assetApplicationDomainId: cliAssetsImporterRunPresentReturn.assetApplicationDomainId, epAsyncApiChannelDocument: epAsyncApiChannelDocument, - specVersion: - cliAssetsImporterRunPresentOptions.epAsyncApiDocument.getVersion(), + specVersion: cliAssetsImporterRunPresentOptions.epAsyncApiDocument.getVersion(), checkmode: cliAssetsImporterRunPresentOptions.checkmode, }); /* istanbul ignore next */ diff --git a/packages/ep-async-api-importer/test/specs/ep-idempotency.spec.ts b/packages/ep-async-api-importer/test/specs/ep-idempotency.spec.ts index d97132bf1..50491912e 100644 --- a/packages/ep-async-api-importer/test/specs/ep-idempotency.spec.ts +++ b/packages/ep-async-api-importer/test/specs/ep-idempotency.spec.ts @@ -168,7 +168,7 @@ describe(`${scriptName}`, () => { after(async () => { TestContext.newItId(); - // await applicationDomainTasks(EEpSdkTask_TargetState.ABSENT); + await applicationDomainTasks(EEpSdkTask_TargetState.ABSENT); }); it(`${scriptName}: should setup the domains`, async () => { diff --git a/packages/ep-async-api-importer/test/specs/multi-domain.xx-spec.ts b/packages/ep-async-api-importer/test/specs/ep-multi-application-domains.x-spec.ts similarity index 92% rename from packages/ep-async-api-importer/test/specs/multi-domain.xx-spec.ts rename to packages/ep-async-api-importer/test/specs/ep-multi-application-domains.x-spec.ts index 584e42a8b..8dbd8823f 100644 --- a/packages/ep-async-api-importer/test/specs/multi-domain.xx-spec.ts +++ b/packages/ep-async-api-importer/test/specs/ep-multi-application-domains.x-spec.ts @@ -3,6 +3,7 @@ import { expect } from "chai"; import path from "path"; import { ApiError, + ApplicationsService, EventApi, EventApIsService, EventApiVersion, @@ -127,11 +128,13 @@ let CopiedEventApi_Id: string | undefined; let App_Name: string; let App_Id: string | undefined; let AppVersion_Id: string | undefined; +let AppApiSpec: any; let ApplicationDomain_Copy_Name: string; let ApplicationDomain_Copy_Id: string; -let AsyncApiSpecFileNameJson: string; +let EventApiAsyncApiSpecFileNameJson: string; +let AppAsyncApiSpecFileNameJson: string; // let AsyncApiSpecFile_X_EpApplicationDomainName: string; // let AsyncApiSpecFile_X_EpAssetApplicationDomainName: string; @@ -547,9 +550,9 @@ describe(`${scriptName}`, () => { const applicationDomainName = epAsyncApiDocument.getApplicationDomainName(); const assetsApplicationDomainName = epAsyncApiDocument.getAssetsApplicationDomainName(); - AsyncApiSpecFileNameJson = TestConfig.getConfig().tmpDir + "/" + epAsyncApiDocument.getTitleAsFileName("json"); + EventApiAsyncApiSpecFileNameJson = TestConfig.getConfig().tmpDir + "/" + epAsyncApiDocument.getEpApiNameAsFileName("json"); CliUtils.saveContents2File({ - filePath: AsyncApiSpecFileNameJson, + filePath: EventApiAsyncApiSpecFileNameJson, content: JSON.stringify(epAsyncApiDocument.getOriginalSpecAsJson(), null, 2 ), }); } catch (e) { @@ -559,15 +562,15 @@ describe(`${scriptName}`, () => { } }); - it(`${scriptName}: should import event api spec with test`, async () => { + it(`${scriptName}: should import event api spec`, async () => { try { - CliConfig.getCliImporterManagerOptions().asyncApiFileList = [AsyncApiSpecFileNameJson]; + CliConfig.getCliImporterManagerOptions().asyncApiFileList = [EventApiAsyncApiSpecFileNameJson]; CliConfig.getCliImporterManagerOptions().cliImporterManagerMode = ECliImporterManagerMode.RELEASE_MODE; // CliConfig.getCliImporterManagerOptions().runId = scriptName; // // DEBUG // CliConfig.getCliImporterManagerOptions().cliImporterManagerMode = ECliImporterManagerMode.TEST_MODE_KEEP; // CliConfig.getCliImporterManagerOptions().applicationDomainName = 'release_mode'; - CliConfig.getCliImporterManagerOptions().createEventApiApplication = true; + CliConfig.getCliImporterManagerOptions().createApiApplication = false; CliConfig.getCliImporterManagerOptions().cliImporterOptions.cliAssetImport_BrokerType = undefined; CliConfig.getCliImporterManagerOptions().cliImporterOptions.cliAssetImport_ChannelDelimiter = undefined; @@ -588,4 +591,37 @@ describe(`${scriptName}`, () => { } }); + it(`${scriptName}: should get the application version api spec`, async () => { + try { + AppApiSpec = await ApplicationsService.getAsyncApiForApplicationVersion({ + applicationVersionId: AppVersion_Id + }) + } catch (e) { + if (e instanceof ApiError) expect(false, TestLogger.createApiTestFailMessage("failed")).to.be.true; + expect(e instanceof EpSdkError, TestLogger.createNotEpSdkErrorMessage(e)).to.be.true; + expect(false, TestLogger.createEpSdkTestFailMessage("failed", e)).to.be.true; + } + }); + + it(`${scriptName}: should parse the application version api spec and save it to file`, async () => { + try { + const epAsyncApiDocument: EpAsyncApiDocument = await EpAsyncApiDocumentService.createFromAny({ + anySpec: AppApiSpec + }); + const applicationDomainName = epAsyncApiDocument.getApplicationDomainName(); + const assetsApplicationDomainName = epAsyncApiDocument.getAssetsApplicationDomainName(); + + AppAsyncApiSpecFileNameJson = TestConfig.getConfig().tmpDir + "/" + epAsyncApiDocument.getEpApiNameAsFileName("json"); + CliUtils.saveContents2File({ + filePath: AppAsyncApiSpecFileNameJson, + content: JSON.stringify(epAsyncApiDocument.getOriginalSpecAsJson(), null, 2 ), + }); + } catch (e) { + if (e instanceof ApiError) expect(false, TestLogger.createApiTestFailMessage("failed")).to.be.true; + expect(e instanceof EpSdkError, TestLogger.createNotEpSdkErrorMessage(e)).to.be.true; + expect(false, TestLogger.createEpSdkTestFailMessage("failed", e)).to.be.true; + } + }); + + });