openapi-backend icon indicating copy to clipboard operation
openapi-backend copied to clipboard

Incorrect formatters being used for Ajv in Validation

Open buildgreatthings opened this issue 3 years ago • 7 comments

I am getting errors on run from ajv that is being loaded in openapi-backend.

unknown format "date-time" ignored in schema at path "#/properties/timestamp"
unknown format "date-time" ignored in schema at path "#/properties/timestamp" 

The fix is this snippet that should go into the validation file.

const AJV = require('ajv').default;
const addFormats = require('ajv-formats').default;
const ajv = new AJV();
addFormats(ajv);

buildgreatthings avatar Dec 16 '21 22:12 buildgreatthings

If you just want to add date-time support you can use:

  const api = new OpenAPIBackend({
      definition: '...........',
      customizeAjv: (ajv, ajvOpts, validationContext) => {
          let dtFormat = {
              type: 'string',
              validate: /^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,
          };
          ajv.addFormat("date-time", dtFormat);
          return ajv;
      }
  });

The regex above was copied from the "ajv-formats" module, here: https://github.com/ajv-validator/ajv-formats/blob/8b424f1e11d23f556cc12f1b9fd16a37286cf326/src/formats.ts

ak683517 avatar Jan 20 '22 12:01 ak683517

Hi @ak683517,

That snippet returned an error with

index.ts:45:32 - error TS2345: Argument of type '{ type: string; validate: RegExp; }' is not assignable to parameter of type 'Format'.
  Property 'async' is missing in type '{ type: string; validate: RegExp; }' but required in type 'AsyncFormatDefinition<number>'.

45     ajv.addFormat("date-time", dtFormat);
                                  ~~~~~~~~

  node_modules/ajv/dist/types/index.d.ts:165:5
    165     async: true;
            ~~~~~
    'async' is declared here.


Found 1 error.

buildgreatthings avatar Jan 20 '22 16:01 buildgreatthings

I'd cast it as any:

ajv.addFormat("date-time", dtFormat as any);

sam3k avatar Feb 03 '22 00:02 sam3k

Any updates when this is going to be fixed?

drodil avatar Sep 29 '22 11:09 drodil

Would also like to get an update -> so we should add the formatter ourselves if needed?

BenCGI avatar May 23 '23 12:05 BenCGI

The following worked for me:

import { fullFormats } from 'ajv-formats/dist/formats'

const api = new OpenAPIBackend({
  definition: '...........',
  ajvOpts: {
    formats: fullFormats,
  },
})

wolfgangbecker avatar Aug 22 '23 21:08 wolfgangbecker

@anttiviljami Any updates when this is going to be fixed?

ydayagi avatar Dec 05 '23 09:12 ydayagi