mirror of
https://gitlab.com/openstapps/openstapps.git
synced 2026-01-20 08:33:11 +00:00
feat: improve monorepo dev experience
This commit is contained in:
48
packages/core-validator/src/index.ts
Normal file
48
packages/core-validator/src/index.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
import Ajv, {AnySchema} from 'ajv';
|
||||
import addFormats from 'ajv-formats';
|
||||
import schema from '../schema/core.schema.json';
|
||||
import {SchemaMap} from '../schema/core.schema.js';
|
||||
|
||||
export type RemoveNeverProperties<T> = {
|
||||
[K in Exclude<
|
||||
keyof T,
|
||||
{
|
||||
// eslint-disable-next-line @typescript-eslint/ban-types
|
||||
[P in keyof T]: T[P] extends Function ? P : never;
|
||||
}[keyof T]
|
||||
>]: T[K];
|
||||
};
|
||||
|
||||
export type IncludeProperty<T extends object, E> = RemoveNeverProperties<{
|
||||
[K in keyof T]: T[K] extends E ? T[K] : never;
|
||||
}>;
|
||||
|
||||
type NameOf<I extends SchemaMap[keyof SchemaMap]> = keyof IncludeProperty<SchemaMap, I>;
|
||||
|
||||
/**
|
||||
* StAppsCore validator
|
||||
*/
|
||||
export class Validator {
|
||||
private readonly ajv: Ajv.default;
|
||||
|
||||
constructor(additionalSchemas: AnySchema[] = []) {
|
||||
this.ajv = new Ajv.default({
|
||||
schemas: [schema, ...additionalSchemas],
|
||||
verbose: true,
|
||||
allowUnionTypes: true,
|
||||
});
|
||||
addFormats.default(this.ajv, {
|
||||
formats: ['date-time', 'time', 'uuid', 'duration'],
|
||||
mode: 'fast',
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates anything against a given schema name or infers schema name from object
|
||||
* @param instance Instance to validate
|
||||
* @param schema Name of schema to validate instance against or the schema itself
|
||||
*/
|
||||
public validate<T>(instance: unknown, schema: NameOf<T>): instance is T {
|
||||
return this.ajv.validate(schema as string, instance);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user