mobx-react-form
Version:
Reactive MobX Form State Management
95 lines (91 loc) • 2.94 kB
JavaScript
;
Object.defineProperty(exports, '__esModule', { value: true });
function isPromise(obj) {
return (!!obj &&
typeof obj.then === "function" &&
(typeof obj === "object" || typeof obj === "function"));
}
class SVK {
promises;
config;
state;
extend;
validator;
schema;
constructor({ config, state = null, promises = [], }) {
this.state = state;
this.promises = promises;
this.config = config;
this.extend = config?.extend;
this.schema = config.schema;
this.initValidator();
}
extendOptions(options = {}) {
return {
...options,
errorDataPath: "property",
allErrors: true,
coerceTypes: true,
v5: true,
};
}
initValidator() {
const AJV = this.config.package;
const validatorInstance = new AJV(this.extendOptions(this.config.options));
if (typeof this.extend === "function") {
this.extend({
form: this.state.form,
validator: validatorInstance,
});
}
this.validator = validatorInstance.compile(this.schema);
}
validate(field) {
const result = this.validator(field.state.form.flatMapValues);
if (isPromise(result)) {
const $p = result
.then(() => field.setValidationAsyncData(true))
.catch((err) => err && this.handleAsyncError(field, err.errors))
.then(() => this.executeAsyncValidation(field));
this.promises.push($p);
return;
}
this.handleSyncError(field, this.validator.errors);
}
handleSyncError(field, errors) {
const fieldError = this.findError(field.path ?? '', errors);
if (!fieldError)
return;
const message = `${field.label} ${fieldError.message}`;
field.invalidate(message, false);
}
handleAsyncError(field, errors) {
const fieldError = this.findError(field.path ?? '', errors);
if (!fieldError)
return;
const message = `${field.label} ${fieldError.message}`;
field.setValidationAsyncData(false, message);
}
findError(path, errors) {
if (!errors)
return;
return errors.find(({ dataPath }) => {
let $dataPath;
$dataPath = dataPath.replace(/^\.+/, "");
$dataPath = $dataPath.replace(/\]/g, "");
$dataPath = $dataPath.replace(/\[/g, ".");
return $dataPath.includes(path);
});
}
executeAsyncValidation(field) {
if (field.validationAsyncData.valid === false) {
field.invalidate(field.validationAsyncData.message ?? undefined, false, true);
}
}
}
var SVK_default = (config) => ({
class: (SVK),
config,
});
exports.default = SVK_default;
//# sourceMappingURL=SVK.js.map