Pages

Monday, June 6, 2016

Learning Meteor.js [Part 28]: Calling the server with validated methods to modify data

All right, now that authentication is in place we can allow users to create and persist orders on the site. So far, there are 4 edit operations that users can do: add a meal, remove a meal, add a recipe/ingredient to a meal and remove a recipe/ingredient from a meal. It follows that there will be a meteor method exposed on the server for each operation.

mdg:validated-method is the recommended package for authoring methods, and this is how the 'remove a meal' method looks like this:
import { ValidatedMethod } from 'meteor/mdg:validated-method';
import { SimpleSchema } from 'meteor/aldeed:simple-schema';

export const removeMeal = new ValidatedMethod({
    name: 'meals.remove',
    validate: new SimpleSchema({
        mealId: { type: String }
    }).validator(),
    run({ mealId }) {
        if (!this.userId) {
           throw new Meteor.Error('unauthorized', 'You must be logged in to remove a meal.');
        }

        Meals.remove({ _id: mealId, userId: this.userId });
    }
});
  1. The first thing to note is the 'validate' property, which uses another package to verify that the information received from the client is valid (in this case a string argument must be provided).
  2. Next, the behavior is implemented in the run function where some additional business validation must be done before modifying the database. Specifically, the user must to be authenticated in order to execute.
  3. Lastly, it tells mongodb to remove the specified meal including the userId as part of the identifying document (to make sure that a user can only remove his or her own meals).

With the method in place, the client can now import it and call it:
import * as MealMethods from '../../api/meals/meals.methods.js';

Template.orderDetailsPart.events({  
    'click .remove-meal': function(event, template) {
        var mealId = $(event.target).parents('.meal').data('id');

        MealMethods.removeMeal.call({ mealId: mealId}, function(err,res) {
           if (err) alert(err);
        });
    }
});

You can check the code up to this point by using this commit or visit the live demo. The next few posts will continue exploring the changes to enable storing user information in the database.



No comments:

Post a Comment

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