Pages

Thursday, July 7, 2016

Learning Meteor.js [Part 35]: Use SimpleSchema rules to better validate arguments to server methods

In my previous post I showed the server method to insert an ingredient, it is worth mentioning some details of the validated method that I skipped:
export const addIngredient = new ValidatedMethod({
    name: 'ingredients.add',
    validate: new SimpleSchema({
        name: { type: String },
        imageUrl: { type: String, optional: true, defaultValue: '/images/default-ingredient.png' }
    }).validator({ clean: true }),
    mixins: [Mixins.authenticated],
    run({ name, imageUrl }) {
        Ingredients.insert({
            name: name,
            imageUrl: imageUrl,
            userId: this.userId
        });
    }
});

Things to notice:

  • The 'imageUrl' schema has an optional=true flag, meaning that the client can omit this value.
  • It also has a defautValue property that is used if the client does not provide a value.
  • The validator() method receives an object with a clean=true flag which sanitizes the data before validation occurs. For example it trims and removes empty strings.
If any validation rule fails, an error is returned to the client. You can read more about the 'cleaning' of data in the github repo here.




No comments:

Post a Comment

Note: Only a member of this blog may post a comment.