From 8bd118d544dde7dda0b4ca2149b86ab11768b9fa Mon Sep 17 00:00:00 2001 From: Zeping Bai Date: Fri, 6 Sep 2024 21:55:04 +0800 Subject: [PATCH] feat: improve oas converter error output (#184) --- libs/converter-openapi/src/index.ts | 25 +++++++++++++++++++++--- libs/converter-openapi/src/schema.ts | 7 ++++++- libs/converter-openapi/tsconfig.lib.json | 1 + 3 files changed, 29 insertions(+), 4 deletions(-) diff --git a/libs/converter-openapi/src/index.ts b/libs/converter-openapi/src/index.ts index b10526ed..236c6e69 100644 --- a/libs/converter-openapi/src/index.ts +++ b/libs/converter-openapi/src/index.ts @@ -3,6 +3,7 @@ import { Listr } from 'listr2'; import { isEmpty } from 'lodash'; import { OpenAPIV3 } from 'openapi-types'; import slugify from 'slugify'; +import { ZodError } from 'zod'; import { ExtKey, parseExtPlugins } from './extension'; import { parseSeprateService, parseUpstream } from './parser'; @@ -17,9 +18,27 @@ export class OpenAPIConverter implements ADCSDK.Converter { return new Listr<{ local: ADCSDK.Configuration }>([ { title: 'Validate OpenAPI document', - task: () => { - const res = schema.safeParse(oas); - if (!res.success) throw new Error(res.error.toString()); //TODO optimize it + task: (ctx, task) => { + const result = schema.safeParse(oas); + + if (!result.success) { + let err = + 'Validate OpenAPI document\nThe following errors were found in OpenAPI document:\n'; + + if ('error' in result) { + (result.error as ZodError).errors.forEach((error, idx) => { + err += `#${idx + 1} ${error.message}, field: "${( + error.path ?? [] + ).join('.')}"\n`; + task.output = this.buildDebugOutput([ + `#${idx + 1} raw error: `, + JSON.stringify(error), + ]); + }); + } + + throw new Error(err); + } }, }, { diff --git a/libs/converter-openapi/src/schema.ts b/libs/converter-openapi/src/schema.ts index 25360740..8087a57c 100644 --- a/libs/converter-openapi/src/schema.ts +++ b/libs/converter-openapi/src/schema.ts @@ -37,7 +37,12 @@ export const schema = z.object({ servers: z .array( z.object({ - url: z.string().regex(/https?:\/\//g), + url: z + .string() + .regex( + /https?:\/\//g, + 'The URL must be start with "https://" or "http://"', + ), variables: z.optional( z.record( z.string(), diff --git a/libs/converter-openapi/tsconfig.lib.json b/libs/converter-openapi/tsconfig.lib.json index 840de3d5..04f1fcc9 100644 --- a/libs/converter-openapi/tsconfig.lib.json +++ b/libs/converter-openapi/tsconfig.lib.json @@ -4,6 +4,7 @@ "module": "commonjs", "outDir": "../../dist/out-tsc", "declaration": true, + "esModuleInterop": true, "types": [ "node" ],