mirror of
https://github.com/Unleash/unleash.git
synced 2024-11-01 19:07:38 +01:00
80cf27476b
## What This PR changes our AJV configuration to return all errors it finds with a schema instead of stopping at the first one. Because of this, a number of the snapshot tests that we have must be updated. ## Why DX! As someone using an API: if I send a faulty request, I'd rather have the API tell me about the five things that are wrong than for me to learn about one thing, send a new request, learn about another thing, send a new request, .... etc. Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
42 lines
1.0 KiB
TypeScript
42 lines
1.0 KiB
TypeScript
import Ajv, { ErrorObject } from 'ajv';
|
|
import { SchemaId, schemas } from './index';
|
|
import { omitKeys } from '../util/omit-keys';
|
|
|
|
export interface ISchemaValidationErrors<S = SchemaId> {
|
|
schema: S;
|
|
errors: ErrorObject[];
|
|
}
|
|
|
|
const ajv = new Ajv({
|
|
schemas: Object.values(schemas).map((schema) =>
|
|
omitKeys(schema, 'components'),
|
|
),
|
|
// example was superseded by examples in openapi 3.1, but we're still on 3.0, so
|
|
// let's add it back in!
|
|
keywords: ['example'],
|
|
formats: {
|
|
'date-time': true,
|
|
uri: true,
|
|
},
|
|
allErrors: true,
|
|
});
|
|
|
|
export const addAjvSchema = (schemaObjects: any[]): any => {
|
|
const newSchemas = schemaObjects.filter(
|
|
(schema) => !ajv.getSchema(schema.$id),
|
|
);
|
|
return ajv.addSchema(newSchemas);
|
|
};
|
|
|
|
export const validateSchema = <S = SchemaId>(
|
|
schema: S,
|
|
data: unknown,
|
|
): ISchemaValidationErrors<S> | undefined => {
|
|
if (!ajv.validate(schema, data)) {
|
|
return {
|
|
schema,
|
|
errors: ajv.errors ?? [],
|
|
};
|
|
}
|
|
};
|