Pages

Thursday, June 9, 2016

Learning Meteor.js [Part 31]: Provision database when a user signs in

When a user signs in to the application the UI should already have a meal ready for the user to drag/drop ingredients into it. In order to reuse all the view logic that I already had, I wanted to provision an order and a meal the first time the user signs in.

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.