From b7b6e84322d1becf2fcbf5fb65d3663629c876c0 Mon Sep 17 00:00:00 2001 From: Luuk Scholten Date: Mon, 5 Nov 2018 13:59:31 +0100 Subject: [PATCH] Add support for minLength and maxLength constraint humanization --- demo/openapi.yaml | 4 ++++ src/utils/openapi.ts | 43 +++++++++++++++++++++++++++---------------- 2 files changed, 31 insertions(+), 16 deletions(-) diff --git a/demo/openapi.yaml b/demo/openapi.yaml index 1a06f4f6..fc3ce073 100644 --- a/demo/openapi.yaml +++ b/demo/openapi.yaml @@ -296,6 +296,8 @@ paths: style: form schema: type: array + minItems: 1 + maxItems: 3 items: type: string enum: @@ -784,6 +786,7 @@ components: photoUrls: description: The list of URL to a cute photos featuring pet type: array + maxItems: 20 xml: name: photoUrl wrapped: true @@ -796,6 +799,7 @@ components: tags: description: Tags attached to the pet type: array + minItems: 1 xml: name: tag wrapped: true diff --git a/src/utils/openapi.ts b/src/utils/openapi.ts index 7e172132..bfe08655 100644 --- a/src/utils/openapi.ts +++ b/src/utils/openapi.ts @@ -141,29 +141,40 @@ export function isNamedDefinition(pointer?: string): boolean { return /^#\/components\/schemas\/[^\/]+$/.test(pointer || ''); } +function humanizeRangeConstraint(description: string, min: number | undefined, max: number | undefined): string | undefined { + let stringRange; + if (min !== undefined && max !== undefined) { + if (min === max) { + stringRange = `${min} ${description}`; + } else { + stringRange = `[ ${min} .. ${max} ] ${description}`; + } + } else if (max !== undefined) { + stringRange = `<= ${max} ${description}`; + } else if (min !== undefined) { + if (min === 1) { + stringRange = 'non-empty'; + } else { + stringRange = `>= ${min} ${description}`; + } + } + + return stringRange; +} + export function humanizeConstraints(schema: OpenAPISchema): string[] { const res: string[] = []; - let stringRange; - if (schema.minLength !== undefined && schema.maxLength !== undefined) { - if (schema.minLength === schema.maxLength) { - stringRange = `${schema.minLength} characters`; - } else { - stringRange = `[ ${schema.minLength} .. ${schema.maxLength} ] characters`; - } - } else if (schema.maxLength !== undefined) { - stringRange = `<= ${schema.maxLength} characters`; - } else if (schema.minLength !== undefined) { - if (schema.minLength === 1) { - stringRange = 'non-empty'; - } else { - stringRange = `>= ${schema.minLength} characters`; - } - } + const stringRange = humanizeRangeConstraint('characters', schema.minLength, schema.maxLength); if (stringRange !== undefined) { res.push(stringRange); } + const arrayRange = humanizeRangeConstraint('items', schema.minItems, schema.maxItems); + if (arrayRange !== undefined) { + res.push(arrayRange); + } + let numberRange; if (schema.minimum !== undefined && schema.maximum !== undefined) { numberRange = schema.exclusiveMinimum ? '( ' : '[ ';