The easiest way that I could make this work is to keep two independent collections: one that is a full mongodb collection (for the authenticated users) and another client-only collection (for the anonymous user). The mongo collection is defined in the server:
import { Mongo } from 'meteor/mongo'; export const Meals = new Mongo.Collection('meals');
The client imports this collection but then also defines a local-only collection:
import { Mongo } from 'meteor/mongo'; import { Meals } from '../../api/meals/meals.js'; var LocalMeals = new Mongo.Collection(null);
When the view is initialized it subscribes to receive the documents for the authenticated user. It doesn't matter that the user is not authenticated to start with, once he/she signs in the publication on the server will send the documents.
Template.orderDetailsPart.onCreated(function() { this.subscribe('lastOrderAndMeals'); });
Next thing, is to either display the local or the remote collection depending if user is authenticated:
Template.orderDetailsPart.helpers({ meals() { if (Meteor.userId()) { return Meals.findFromPublication('lastOrderAndMeals'); } else { return LocalMeals.find(); } } });
The important thing is that the built-in Meteor.userId() is a reactive function, so when the user authenticates the view will automatically switch to render the other collection. Lastly, whenever an edit happens we can check the same userId() to decide whether to modify the local collection or invoke the remote method:
Template.orderDetailsPart.events({ 'click .remove-meal': function(event, template) { var mealId = $(event.target).parents('.meal').data('id'); if (Meteor.userId()) { MealMethods.removeMeal.call({ mealId: mealId}, methodReturnHandler); } else { LocalMeals.remove(mealId); } } });
I don't know if this is the recommended way to accomplish this, if you know of a better approach please let me know. You can play around with this in the live site and see how you can create an order as an anonymous user, but once you sign in the site will switch to show you an order from the database that is persisted.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.