55 lines
1.5 KiB
TypeScript
55 lines
1.5 KiB
TypeScript
import type RootStore from '../root';
|
|
import type { RemoveError, ValidationConfig, ValidationError, ValidationParams } from './types';
|
|
import { makeAutoObservable } from 'mobx';
|
|
import { notification } from 'ui/elements';
|
|
|
|
export default class Validation {
|
|
private root: RootStore;
|
|
private params: ValidationConfig;
|
|
private errors: Set<ValidationError>;
|
|
|
|
constructor(config: ValidationConfig, rootStore: RootStore) {
|
|
this.params = config;
|
|
this.errors = new Set();
|
|
this.root = rootStore;
|
|
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.open({
|
|
description: message,
|
|
key: this.params.err_key,
|
|
message: this.params.err_title,
|
|
type: this.root.$process.has('Unlimited') ? 'warning' : 'error',
|
|
});
|
|
}
|
|
|
|
return (() => this.removeError({ key })) as RemoveError;
|
|
};
|
|
|
|
public clearErrors = () => {
|
|
this.errors.clear();
|
|
notification.close(this.params.err_key);
|
|
};
|
|
}
|