There is a way to do this by hooking into the Accounts system and execute a callback when a user signs in, but I decided to use the concepts that I had already learned and place the provisioning code within an autorun of the template:
import * as OrderMethods from '../../api/orders/orders.methods.js'; Template.orderDetailsPart.onCreated(function() { this.subscribe('lastOrderAndMeals'); this.autorun(function() { if (Meteor.userId()) { OrderMethods.ensureOrderExists.call({}, ...); } }); });
Since the Meteor.userId() function is reactive, whenever the user signs in, the function will re-execute and invoke the 'ensureOrderExists' method. This method will insert documents in the database for the user (if they don't exist yet):
export const ensureOrderExists = new ValidatedMethod({ name: 'orders.ensureExists', validate: null, run() { if (Meteor.isServer && this.userId) { var order = Orders.findOne(); if (!order) { order = { _id: Random.id(), userId: this.userId, createdDate: new Date() }; Orders.insert(order); } if (Meals.find({ orderId: order['_id'] }).count() === 0) { Meals.insert({ orderId: order['_id'], userId: this.userId, createdDate: new Date() }); } } } })
Yes, there is an extra round trip after the user signs in to create his/her default order, but this is only paid the first time the user signs in to the application.
You can check the code up to this point by using this commit or visit the live demo.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.