Search code examples
meteorangular2-meteor

How Meteor Methods are executed?


folowing this http://www.angular-meteor.com/tutorials/socially/angular2/meteor-methods

having :

Meteor.methods({
    invite: function(partyId: string, userId: string) {
        check(partyId, String);
        check(userId, String);

        let party = Parties.findOne(partyId);

        if (!party)
            throw new Meteor.Error('404', 'No such party!');

        if (party.public)
            throw new Meteor.Error('400', 'That party is public. No need to invite people.');

        if (party.owner !== this.userId)
            throw new Meteor.Error('403', 'No permissions!');

        if (userId !== party.owner && (party.invited || []).indexOf(userId) == -1) {
            Parties.update(partyId, { $addToSet: { invited: userId } });

            let from = getContactEmail(Meteor.users.findOne(this.userId));
            let to = getContactEmail(Meteor.users.findOne(userId));

            if (Meteor.isServer && to) {
                Email.send({
                    from: 'noreply@socially.com',
                    to: to,
                    replyTo: from || undefined,
                    subject: 'PARTY: ' + party.name,
                    text: `Hi, I just invited you to ${party.name} on Socially.
                        \n\nCome check it out: ${Meteor.absoluteUrl()}\n`
                });
            }
        }
    }
})

then in the Party-Detail.ts we have

invite(user:Meteor.User) {
        this.call('invite', this.party._id, user._id, (error) => {
            if (error) {
                alert(`Failed to invite due to ${error}`);
                return;
            }

            alert('User successfully invited.');
        });

    }

When the user click on Invite how the code is executed ?

In the client and the Server at the same time ?


Solution

  • Assuming that your Meteor.methods() are in your /lib folder then when a method is called:

    1. It will execute first on the client and return results asynchronously without incurring any network delays. This is a process known as simulation.
    2. The server will then execute the same code asynchronously.
    3. If the results on the server differ from those on the client the server will instruct the client to change its results to match. (The server always wins).

    The overall effect is called latency compensation. The client gets the illusion (simulation) of an instant result while the server is given time to catch up in the background.