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
Christopher Kolstad efcf04487d
chore: make it build with strict null checks set to true (#9554)
As part of preparation for ESM and node/TSC updates, this PR will make
Unleash build with strictNullChecks set to true, since that's what's in
our tsconfig file. Hence, this PR also removes the `--strictNullChecks
false` flag in our compile tasks in package.json.

TL;DR - Clean up your code rather than turning off compiler security
features :)
2025-03-19 10:01:49 +01:00

58 lines
1.7 KiB
TypeScript

import Ajv, { type ErrorObject } from 'ajv';
import { type SchemaId, schemas } from './index';
import { omitKeys } from '../util/omit-keys';
import { fromOpenApiValidationErrors } from '../error/bad-data-error';
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,
},
});
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 => {
// @ts-expect-error we validate that we have an $id field, AJV apparently does not think this is enough to be willing to validate.
if (!ajv.validate(schema, data)) {
return {
schema,
errors: ajv.errors ?? [],
};
}
};
export const throwOnInvalidSchema = <S = SchemaId>(
schema: S,
data: object,
): void => {
const validationErrors = validateSchema(schema, data);
if (validationErrors) {
const [firstError, ...remainingErrors] = validationErrors.errors;
throw fromOpenApiValidationErrors(data, [
firstError,
...remainingErrors,
]);
}
};