feat: define dashboard model schema
This commit is contained in:
parent
59baec9831
commit
7cfd5b4069
9 changed files with 714 additions and 2 deletions
66
src/lib/model/validation.ts
Normal file
66
src/lib/model/validation.ts
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
import Ajv, { type ErrorObject } from "ajv";
|
||||
import addFormats from "ajv-formats";
|
||||
import {
|
||||
DashboardDocumentSchema,
|
||||
type DashboardDocument,
|
||||
} from "./schema";
|
||||
|
||||
export interface DashboardValidationFailure {
|
||||
valid: false;
|
||||
errors: string[];
|
||||
details: ErrorObject[];
|
||||
}
|
||||
|
||||
export interface DashboardValidationSuccess {
|
||||
valid: true;
|
||||
data: DashboardDocument;
|
||||
}
|
||||
|
||||
export type DashboardValidationResult =
|
||||
| DashboardValidationFailure
|
||||
| DashboardValidationSuccess;
|
||||
|
||||
const ajv = addFormats(
|
||||
new Ajv({
|
||||
allErrors: true,
|
||||
strict: false,
|
||||
}),
|
||||
);
|
||||
|
||||
const validateDashboard = ajv.compile<DashboardDocument>(DashboardDocumentSchema);
|
||||
|
||||
export function formatValidationErrors(errors: ErrorObject[] = []): string[] {
|
||||
return errors.map((error) => {
|
||||
const path = error.instancePath || "/";
|
||||
const message = error.message || "is invalid";
|
||||
return `${path} ${message}`;
|
||||
});
|
||||
}
|
||||
|
||||
export function validateDashboardDocument(
|
||||
value: unknown,
|
||||
): DashboardValidationResult {
|
||||
if (validateDashboard(value)) {
|
||||
return { valid: true, data: value };
|
||||
}
|
||||
|
||||
const details = [...(validateDashboard.errors || [])];
|
||||
return {
|
||||
valid: false,
|
||||
errors: formatValidationErrors(details),
|
||||
details,
|
||||
};
|
||||
}
|
||||
|
||||
export function assertDashboardDocument(
|
||||
value: unknown,
|
||||
): asserts value is DashboardDocument {
|
||||
const result = validateDashboardDocument(value);
|
||||
if (!result.valid) {
|
||||
throw new Error(`Invalid dashboard document: ${result.errors.join("; ")}`);
|
||||
}
|
||||
}
|
||||
|
||||
export function isDashboardDocument(value: unknown): value is DashboardDocument {
|
||||
return validateDashboardDocument(value).valid;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue