51 lines
1.3 KiB
TypeScript
51 lines
1.3 KiB
TypeScript
import type { RemoveError, ValidationConfig, ValidationError, ValidationParams } from './types';
|
|
import { makeAutoObservable } from 'mobx';
|
|
import notification from 'ui/elements/notification';
|
|
|
|
export default class Validation {
|
|
private params: ValidationConfig;
|
|
private errors: Set<ValidationError>;
|
|
|
|
constructor(config: ValidationConfig) {
|
|
this.params = config;
|
|
this.errors = new Set();
|
|
makeAutoObservable(this);
|
|
}
|
|
|
|
public get hasErrors() {
|
|
return this.errors.size > 0;
|
|
}
|
|
|
|
public getErrors() {
|
|
return [...this.errors];
|
|
}
|
|
|
|
public removeError = ({ key }: Pick<ValidationError, 'key'>) => {
|
|
const error = [...this.errors].find((x) => x.key === key);
|
|
if (error) this.errors.delete(error);
|
|
if (this.errors.size === 0) notification.close(this.params.err_key);
|
|
};
|
|
|
|
public setError = ({ key, message, silent }: ValidationParams) => {
|
|
const error = [...this.errors].find((x) => x.key === key);
|
|
if (error) this.removeError({ key });
|
|
|
|
this.errors.add({ key, message });
|
|
|
|
if (!silent) {
|
|
notification.error({
|
|
description: message,
|
|
key: this.params.err_key,
|
|
message: this.params.err_title,
|
|
});
|
|
}
|
|
|
|
return (() => this.removeError({ key })) as RemoveError;
|
|
};
|
|
|
|
public clearErrors = () => {
|
|
this.errors.clear();
|
|
notification.close(this.params.err_key);
|
|
};
|
|
}
|