Files
DiceCloud/app/imports/api/mixins/updateSchemaMixin.js
2019-03-19 15:57:21 +02:00

62 lines
2.2 KiB
JavaScript

const argumentSchema = new SimpleSchema({
_id: SimpleSchema.RegEx.Id,
update: {
type: Object,
blackbox: true,
},
});
// Modified simpleSchemaMixin
import SimpleSchema from 'simpl-schema';
export default function updateSchemaMixin(methodOptions) {
// If the user didn't give us a schema and they did give us a validate, assume
// that they are choosing to use the validate way of doing things in this call.
// If they've built a wrapper around ValidateMethod that includes this mixin
// all the time, this could happen semi-"intentionally". There may be times they
// just don't want to use a schema and have specified a "validate" option. So
// returning the unchanged options instead of an error seems proper.
if ((
typeof methodOptions.updateSchema === 'undefined' &&
typeof methodOptions.validate !== 'undefined'
) || (
typeof methodOptions.updateSchema !== 'undefined' &&
methodOptions.updateSchema === null &&
typeof methodOptions.validate !== 'undefined' &&
methodOptions.validate !== null
)) {
return methodOptions;
}
// If they truly gave us both... that just doesn't seem proper.
if (methodOptions.validate && methodOptions.validate !== null) {
throw new Meteor.Error(
'simpleSchemaMixin.options',
'"schema" and "validate" options cannot be used together');
}
// Note that setting them both null will make it through, defaulting to the
// schema = null behavior (enforce no args) instead of the validate = null
// behavior (do no validation).
// Apply default validator options if none are provided
methodOptions.schemaValidatorOptions =
methodOptions.schemaValidatorOptions ||
{ clean: true, modifier: true };
// Make the update schema a SimpleSchema, if it isn't already
let updateSchema;
if (methodOptions.updateSchema instanceof SimpleSchema) {
updateSchema = methodOptions.updateSchema;
} else {
updateSchema = new SimpleSchema(methodOptions.updateSchema);
}
// Set up the new validation
methodOptions.validate = function(args){
argumentSchema.validate(args);
updateSchema.validate(args.update, methodOptions.schemaValidatorOptions);
};
return methodOptions;
}