1
0
mirror of https://github.com/Unleash/unleash.git synced 2025-11-24 20:06:55 +01:00
unleash.unleash/src/lib/openapi/validate.ts
Gastón Fournier 898073878b
chore!: remove isAPI from userSchema response (#10060)
isAPI is not needed for responses, removing it from the system is much
more complex, so I had to cut it with a scalpel...
2025-05-30 11:37:50 +02:00

61 lines
1.6 KiB
TypeScript

import type { ErrorObject } from 'ajv';
import { Ajv } from 'ajv';
import { type SchemaId, schemas } from './index.js';
import { omitKeys } from '../util/index.js';
import { fromOpenApiValidationErrors } from '../error/bad-data-error.js';
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', 'x-enforcer-exception-skip-codes'],
formats: {
'date-time': true,
date: true,
uri: true,
},
code: {
esm: 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: SchemaId,
data: unknown,
): ISchemaValidationErrors<SchemaId> | undefined => {
if (!ajv.validate(schema, data)) {
return {
schema,
errors: ajv.errors ?? [],
};
}
};
export const throwOnInvalidSchema = <S = SchemaId>(
schema: SchemaId,
data: object,
): void => {
const validationErrors = validateSchema(schema, data);
if (validationErrors) {
const [firstError, ...remainingErrors] = validationErrors.errors;
throw fromOpenApiValidationErrors(data, [
firstError,
...remainingErrors,
]);
}
};