2022-06-08 08:01:14 +02:00
|
|
|
import Ajv, { ErrorObject } from 'ajv';
|
|
|
|
import addFormats from 'ajv-formats';
|
|
|
|
import { SchemaId, schemas } from './index';
|
|
|
|
import { omitKeys } from '../util/omit-keys';
|
|
|
|
|
2022-06-24 13:44:16 +02:00
|
|
|
interface ISchemaValidationErrors {
|
2022-06-08 08:01:14 +02:00
|
|
|
schema: SchemaId;
|
|
|
|
errors: ErrorObject[];
|
|
|
|
}
|
|
|
|
|
|
|
|
const ajv = new Ajv({
|
|
|
|
schemas: Object.values(schemas).map((schema) =>
|
|
|
|
omitKeys(schema, 'components'),
|
|
|
|
),
|
|
|
|
});
|
|
|
|
|
|
|
|
addFormats(ajv, ['date-time']);
|
|
|
|
|
2022-06-24 13:44:16 +02:00
|
|
|
export const validateSchema = (
|
2022-06-08 08:01:14 +02:00
|
|
|
schema: SchemaId,
|
2022-06-24 13:44:16 +02:00
|
|
|
data: unknown,
|
|
|
|
): ISchemaValidationErrors | undefined => {
|
2022-06-08 08:01:14 +02:00
|
|
|
if (!ajv.validate(schema, data)) {
|
|
|
|
return {
|
|
|
|
schema,
|
|
|
|
errors: ajv.errors ?? [],
|
|
|
|
};
|
|
|
|
}
|
|
|
|
};
|