2020-09-30 11:33:01 +00:00
|
|
|
import Service, { inject as service } from '@ember/service';
|
|
|
|
|
|
|
|
import lookupValidator from 'ember-changeset-validations';
|
|
|
|
import { Changeset as createChangeset } from 'ember-changeset';
|
|
|
|
|
|
|
|
import Changeset from 'consul-ui/utils/form/changeset';
|
|
|
|
|
|
|
|
import intentionPermissionValidator from 'consul-ui/validations/intention-permission';
|
|
|
|
import intentionPermissionHttpHeaderValidator from 'consul-ui/validations/intention-permission-http-header';
|
|
|
|
|
|
|
|
const validators = {
|
|
|
|
'intention-permission': intentionPermissionValidator,
|
|
|
|
'intention-permission-http-header': intentionPermissionHttpHeaderValidator,
|
|
|
|
};
|
|
|
|
|
2020-11-09 09:25:35 +00:00
|
|
|
export default class ChangeService extends Service {
|
|
|
|
@service('schema')
|
|
|
|
schema;
|
2020-09-30 11:33:01 +00:00
|
|
|
|
2020-11-09 09:25:35 +00:00
|
|
|
init() {
|
|
|
|
super.init(...arguments);
|
2020-09-30 11:33:01 +00:00
|
|
|
this._validators = new Map();
|
2020-11-09 09:25:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
willDestroy() {
|
2020-09-30 11:33:01 +00:00
|
|
|
this._validators = null;
|
2020-11-09 09:25:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
changesetFor(modelName, model, options = {}) {
|
2020-09-30 11:33:01 +00:00
|
|
|
const validator = this.validatorFor(modelName, options);
|
|
|
|
let changeset;
|
|
|
|
if (validator) {
|
|
|
|
let validatorFunc = validator;
|
|
|
|
if (typeof validator !== 'function') {
|
|
|
|
validatorFunc = lookupValidator(validator);
|
|
|
|
}
|
|
|
|
changeset = createChangeset(model, validatorFunc, validator, { changeset: Changeset });
|
|
|
|
} else {
|
|
|
|
changeset = createChangeset(model);
|
|
|
|
}
|
|
|
|
return changeset;
|
2020-11-09 09:25:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
validatorFor(modelName, options = {}) {
|
2020-09-30 11:33:01 +00:00
|
|
|
if (!this._validators.has(modelName)) {
|
|
|
|
const factory = validators[modelName];
|
|
|
|
let validator;
|
|
|
|
if (typeof factory !== 'undefined') {
|
|
|
|
validator = factory(this.schema);
|
|
|
|
}
|
|
|
|
this._validators.set(modelName, validator);
|
|
|
|
}
|
|
|
|
return this._validators.get(modelName);
|
2020-11-09 09:25:35 +00:00
|
|
|
}
|
|
|
|
}
|